papersearch 0.4.8 → 0.4.10

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.
Files changed (104) hide show
  1. package/README.en.md +50 -62
  2. package/README.md +50 -62
  3. package/assets/overview.en.png +0 -0
  4. package/assets/overview.png +0 -0
  5. package/assets/progress-capsule.en.png +0 -0
  6. package/assets/progress-capsule.png +0 -0
  7. package/carsi/README.md +5 -6
  8. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  9. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  10. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  11. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  12. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  13. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  14. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  15. package/carsi/paper_search_carsi/assets/capsule.html +199 -24
  16. package/carsi/paper_search_carsi/browser/backend.py +270 -227
  17. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  18. package/carsi/paper_search_carsi/browser/challenge_interaction.py +79 -43
  19. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  20. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  21. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  22. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  23. package/carsi/paper_search_carsi/browser/login.py +12 -18
  24. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  25. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  26. package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
  27. package/carsi/paper_search_carsi/capsule_placement.py +266 -0
  28. package/carsi/paper_search_carsi/cli.py +22 -7
  29. package/carsi/paper_search_carsi/cold_start.py +65 -51
  30. package/carsi/paper_search_carsi/config.py +6 -4
  31. package/carsi/paper_search_carsi/engine/batch.py +9 -5
  32. package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
  33. package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
  34. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  35. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +4 -2
  36. package/carsi/paper_search_carsi/engine/batch_institution.py +146 -17
  37. package/carsi/paper_search_carsi/engine/batch_login.py +79 -26
  38. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  39. package/carsi/paper_search_carsi/engine/batch_waits.py +92 -37
  40. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  41. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  42. package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
  43. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  44. package/carsi/paper_search_carsi/network.py +1 -1
  45. package/carsi/paper_search_carsi/progress_capsule.py +233 -93
  46. package/carsi/paper_search_carsi/progress_reporter.py +88 -7
  47. package/carsi/paper_search_carsi/progress_view.py +61 -0
  48. package/carsi/paper_search_carsi/server.py +47 -10
  49. package/carsi/paper_search_carsi/session_broker.py +1 -1
  50. package/carsi/paper_search_carsi/user_settings.py +1 -1
  51. package/carsi/pyproject.toml +7 -7
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  54. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  56. package/dist/capabilities/pdf-discovery/batch.js +15 -5
  57. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  58. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
  59. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  60. package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
  61. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  62. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  63. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
  65. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
  67. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  68. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
  69. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  75. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  77. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
  79. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  81. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  82. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  83. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  84. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  85. package/dist/cli.js +13 -9
  86. package/dist/cli.js.map +1 -1
  87. package/dist/management/carsi/installer.d.ts +26 -14
  88. package/dist/management/carsi/installer.d.ts.map +1 -1
  89. package/dist/management/carsi/installer.js +113 -69
  90. package/dist/management/carsi/installer.js.map +1 -1
  91. package/dist/management/carsi/runtime.d.ts +12 -1
  92. package/dist/management/carsi/runtime.d.ts.map +1 -1
  93. package/dist/management/carsi/runtime.js +30 -1
  94. package/dist/management/carsi/runtime.js.map +1 -1
  95. package/package.json +1 -1
  96. package/skills/paper-search/SKILL.md +4 -4
  97. package/skills/paper-search/references/browser-download.md +3 -3
  98. package/skills/paper-search/references/carsi-setup.md +7 -6
  99. package/skills/paper-search/references/cli-contract.md +4 -4
  100. package/skills/paper-search/references/management-layer.md +2 -2
  101. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  102. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  103. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  104. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -7,7 +7,7 @@ from __future__ import annotations
7
7
  import re
8
8
  import time
9
9
  from typing import Any
10
- from urllib.parse import parse_qs, unquote, urlencode, urlparse
10
+ from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
11
11
 
12
12
  from .batch_common import DownloadResult, _is_browser_error, logger, open_page, pump_until, settle
13
13
 
@@ -86,6 +86,12 @@ class InstitutionMixin:
86
86
  return True
87
87
  if self.institution_query and self._assist_configured_institution(page, result):
88
88
  return True
89
+ if self.institution_query and self._select_carsi_federation_link(page, result, here):
90
+ return True
91
+ if self.institution_query and not getattr(result, "_institution_not_listed", False):
92
+ self._check_carsi_school_links(page, result, here)
93
+ if getattr(result, "_institution_not_listed", False):
94
+ return False
89
95
  if self.adapter.prepare_institution_choice(page, result) is False:
90
96
  return False
91
97
  if self._open_seamlessaccess_chooser(page, result):
@@ -225,6 +231,8 @@ class InstitutionMixin:
225
231
  return null;
226
232
  }"""
227
233
  _CARSI_OPTION = re.compile(r"\bCARSI\b", re.I)
234
+ _FEDERATION_LINK_LIST = "ul.federation--list"
235
+ _FEDERATION_SCHOOL_LIST = "ul.federation--list-inner"
228
236
  # How long one pass waits for the school's option once the federation is chosen
229
237
  # (ACS answered after 35-50 s, 2026-11-02; the login loop asks again).
230
238
  LIST_WAIT_SEC = 15
@@ -325,6 +333,61 @@ class InstitutionMixin:
325
333
  result._federation_pages = getattr(result, "_federation_pages", set()) | {here}
326
334
  self._event(result, "institution_federation_selected", detail)
327
335
 
336
+ def _select_carsi_federation_link(self, page: Any, result: DownloadResult, url: str) -> bool:
337
+ if not self._on_publisher_host(url):
338
+ return False
339
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
340
+ try:
341
+ if listing.is_visible() is not True:
342
+ return False
343
+ links = listing.get_by_role("link", name=self._CARSI_OPTION)
344
+ if links.count() != 1:
345
+ return False
346
+ href = links.first.get_attribute("href", timeout=800)
347
+ if not href or not self._manual_institution_target_allowed(urljoin(url, href)):
348
+ return False
349
+ here = self._federation_choice_page(page, result)
350
+ if here is None or not self._click_control(page, links.first, result, "choose CARSI federation"):
351
+ return False
352
+ except Exception as exc:
353
+ if not _is_browser_error(exc):
354
+ raise
355
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
356
+ return False
357
+ self._federation_chosen(result, here, f"carsi: federation link @ {url}")
358
+ return True
359
+
360
+ def _check_carsi_school_links(self, page: Any, result: DownloadResult, url: str) -> None:
361
+ """Only a complete link directory can establish absence after choosing CARSI."""
362
+ if not self._on_publisher_host(url):
363
+ return
364
+ try:
365
+ listing = page.locator(self._FEDERATION_SCHOOL_LIST).first
366
+ if listing.is_visible() is not True:
367
+ return
368
+ heading = page.get_by_role("heading", level=1, name=self._CARSI_OPTION).first
369
+ if heading.is_visible() is not True or self._is_challenge_page(page):
370
+ return
371
+ rows = listing.locator(":scope > li")
372
+ entries = page.evaluate(self._ENTRIES_JS, self._FEDERATION_SCHOOL_LIST + " > li > a[href]")
373
+ if (not entries or len(entries) != rows.count()
374
+ or listing.evaluate("""el => !!el.closest('[aria-busy=true]') ||
375
+ !!el.closest('section')?.querySelector('input:not([type=hidden]), [aria-busy=true], [rel=next]')""",
376
+ timeout=800)):
377
+ return
378
+ # Even a partial name match is enough to leave the choice open for the user.
379
+ entity_id = self._entity_id()
380
+ names = {self._canonical_school_name(name) for name in self._institution_names()} - {""}
381
+ if any(self._institution_entry_score(entry, entity_id)
382
+ or self._canonical_school_name(entry["t"]) in names for entry in entries):
383
+ return
384
+ self._event(result, "auto_institution_not_found", f"{self.institution_query} (CARSI list, {len(entries)} schools) @ {url}")
385
+ result._institution_not_listed = True
386
+ except Exception as exc:
387
+ if not _is_browser_error(exc):
388
+ raise
389
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
390
+
328
391
  def _close_blank_overlay(self, page: Any, result: DownloadResult) -> None:
329
392
  try:
330
393
  closed = page.evaluate(self._BLANK_OVERLAY_JS)
@@ -487,6 +550,11 @@ class InstitutionMixin:
487
550
  .filter(it => it.t && it.t.length <= 160);
488
551
  }"""
489
552
 
553
+ def _institution_entry_score(self, entry: dict, entity_id: str) -> int:
554
+ if self._carries_entity_id(str(entry.get("ids") or ""), entity_id):
555
+ return 4
556
+ return self._institution_match_score(entry.get("t", ""))
557
+
490
558
  def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
491
559
  """Click the single best visible entry for the configured school.
492
560
 
@@ -506,12 +574,7 @@ class InstitutionMixin:
506
574
  return False
507
575
  entity_id = self._entity_id()
508
576
 
509
- def score(item: dict) -> int:
510
- if self._carries_entity_id(str(item.get("ids") or ""), entity_id):
511
- return 4
512
- return self._institution_match_score(item.get("t", ""))
513
-
514
- scored = [(score(it), it) for it in items if isinstance(it, dict)]
577
+ scored = [(self._institution_entry_score(it, entity_id), it) for it in items if isinstance(it, dict)]
515
578
  top = max([score for score, _ in scored] or [0])
516
579
  best = [it for score, it in scored if score == top]
517
580
  same = (len(best) == 1 or top == 4
@@ -538,12 +601,31 @@ class InstitutionMixin:
538
601
  except Exception as exc:
539
602
  if not _is_browser_error(exc):
540
603
  raise
541
- # Covered or moving: the script's click, as before.
604
+ # Custom listboxes can commit their option on mousedown (Cambridge
605
+ # WAYF), before blur closes the list. HTMLElement.click() alone
606
+ # leaves the option unselected even though no error is raised.
607
+ # This is only the already matched institution, never a challenge
608
+ # widget, credential field or another default choice.
609
+ # Omit MouseEventInit.view: an isolated evaluation world's window
610
+ # can be rejected as a Window, and the selection does not need it.
542
611
  try:
543
- page.evaluate("() => { const el = document.querySelector('[data-paper-search-entry]'); if (el) el.click(); }")
612
+ clicked = page.evaluate("""() => {
613
+ const el = document.querySelector('[data-paper-search-entry]');
614
+ if (!el || !el.getClientRects().length || el.closest('[disabled], [aria-disabled="true"]'))
615
+ return false;
616
+ const options = {bubbles:true, cancelable:true, button:0};
617
+ el.dispatchEvent(new MouseEvent('mousedown', {...options, buttons:1}));
618
+ el.dispatchEvent(new MouseEvent('mouseup', options));
619
+ el.click();
620
+ return true;
621
+ }""")
622
+ if clicked is not True:
623
+ return False
624
+ self._event(result, "institution_entry_dispatched", "mouse sequence after native click failure")
544
625
  except Exception as again:
545
626
  if not _is_browser_error(again):
546
627
  raise
628
+ self._event(result, "institution_select_error", str(again).split("\n", 1)[0][:200])
547
629
  return False
548
630
  self._event(result, "auto_institution_entry", f"{target['t'][:80]} @ {url}")
549
631
  self._event(result, "institution_selected", target["t"][:80] + (" (entityID)" if top == 4 else ""))
@@ -576,11 +658,55 @@ class InstitutionMixin:
576
658
  return False
577
659
  if not _is_browser_error(exc):
578
660
  raise
579
- # The wait was cut off by the navigation itself (Firefox's
580
- # NS_BINDING_ABORTED, a detached frame: an Atypon chooser going on to
581
- # the school failed the article, 2026-11-01): the page has gone on.
661
+ # The wait was cut off by the navigation itself (an aborted
662
+ # navigation, a detached frame: an Atypon chooser going on to the
663
+ # school failed the article, 2026-11-01): the page has gone on.
582
664
  return True
583
665
 
666
+ _NO_INSTITUTION_SEARCH_RESULTS = re.compile(
667
+ r"^(?:no (?:institutions?|results?|matches) found(?:[.!]?$|\s+for\b)"
668
+ r"|we couldn['’]t find any results? for\b)", re.I)
669
+ _INSTITUTION_LIST_LINK = re.compile(r"^(?:select|choose) (?:your|an) institution from (?:a|the) list$", re.I)
670
+
671
+ def _handle_institution_search_miss(self, page: Any, result: DownloadResult, url: str) -> bool:
672
+ """Use a visible negative result for our search, and try an offered list first."""
673
+ if (not (self._on_publisher_host(url) or self._is_federation_chooser(url))
674
+ or self._is_challenge_page(page)
675
+ or any(e["state"] == "auto_institution_list_opened" and e.get("detail") == url for e in result.events)):
676
+ return False
677
+ queries = {e.get("detail", "") for e in result.events if e["state"] == "auto_institution_search"}
678
+ try:
679
+ notice = page.get_by_text(self._NO_INSTITUTION_SEARCH_RESULTS).filter(visible=True).first
680
+ if notice.is_visible() is not True:
681
+ return False # no candidate yet does not establish an empty result
682
+ message = notice.inner_text(timeout=800)
683
+ named = re.split(r"\bfor\b", message, maxsplit=1, flags=re.I)[1:]
684
+ for selector in self._institution_search_selectors(page):
685
+ box = page.locator(selector).first
686
+ if box.is_visible() is not True:
687
+ continue
688
+ typed = str(box.input_value(timeout=800) or "").strip()
689
+ if f"{typed} @ {url}" not in queries:
690
+ continue
691
+ if named and self._canonical_school_name(named[0]) != self._canonical_school_name(typed):
692
+ continue # the reply names a different query
693
+ listing = page.get_by_role("link", name=self._INSTITUTION_LIST_LINK).filter(visible=True).first
694
+ if listing.is_visible() is True:
695
+ href = listing.get_attribute("href", timeout=800)
696
+ if (href and self._manual_institution_target_allowed(urljoin(url, href))
697
+ and self._click_control(page, listing, result, "open institution list")):
698
+ self._event(result, "auto_institution_list_opened", url)
699
+ return True
700
+ return False # there is another route; don't call the school missing
701
+ self._event(result, "auto_institution_not_found", f"{message[:120]} @ {url}")
702
+ result._institution_not_listed = True
703
+ return False
704
+ except Exception as exc:
705
+ if not _is_browser_error(exc):
706
+ raise
707
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
708
+ return False
709
+
584
710
  def _assist_configured_institution(self, page: Any, result: DownloadResult) -> bool:
585
711
  """Pick the user's configured institution on the current page.
586
712
 
@@ -659,7 +785,9 @@ class InstitutionMixin:
659
785
  # 4. type the school into an empty institution search box (once per page);
660
786
  # never on a verification page, which the challenge wait takes first: a
661
787
  # search there found no school and ended the login (fixture, 2026-11-01).
662
- if not self._is_challenge_page(page) and once("institution_search"):
788
+ if not once("institution_search"):
789
+ return self._handle_institution_search_miss(page, result, url)
790
+ if not self._is_challenge_page(page):
663
791
  if self._assist_carsi_discovery(page, result):
664
792
  self._event(result, "auto_institution_search", f"carsi @ {url}")
665
793
  return True
@@ -694,10 +822,11 @@ class InstitutionMixin:
694
822
  # The results list as soon as it shows the school (at most 5 s).
695
823
  if pump_until(page, lambda: self._click_unique_institution_entry(page, result, url), 5_000):
696
824
  return True
697
- self._event(result, "auto_institution_not_found", f"{query} @ {url}")
698
- # The publisher has no login route for the school: the login ends
699
- # here instead of waiting out the user's time (Neurology, 2026-11-01).
700
- result._institution_not_listed = True
825
+ # No successful selection within this short poll does not
826
+ # prove absence: results may arrive later, be ambiguous or
827
+ # temporarily unclickable. The login's existing page budget
828
+ # bounds later passes, which inspect the entries again.
829
+ self._event(result, "institution_list_not_ready", f"search selection pending @ {url}")
701
830
  return False
702
831
  except Exception as exc:
703
832
  # Kept, not dropped: this step once stalled 30 s without a trace.
@@ -215,6 +215,14 @@ class LoginMixin:
215
215
  a wait of more than 10 s records how it ended."""
216
216
  self._phase(result, "login")
217
217
  started, signed_in = time.time(), False
218
+
219
+ def observe_login_navigation(frame):
220
+ # A reused school session can cross the IdP and return between two
221
+ # polling passes. Observe only the main-frame host, never form data.
222
+ if frame == page.main_frame and self._is_idp_host(urlparse(str(frame.url)).netloc):
223
+ result._visited_idp = True
224
+
225
+ page.on("framenavigated", observe_login_navigation)
218
226
  try:
219
227
  from ..browser import watchdog
220
228
  # Human authentication has its own budget, not the automation's.
@@ -224,6 +232,7 @@ class LoginMixin:
224
232
  self._return_to_article_after_login(page, result)
225
233
  return signed_in
226
234
  finally:
235
+ page.remove_listener("framenavigated", observe_login_navigation)
227
236
  self._set_login_attention(result, "")
228
237
  last = next((e["state"] for e in reversed(result.events) if e["state"] != "wait"), "")
229
238
  self._note_wait(result, "school login", started, "signed in" if signed_in else (result.reason or last))
@@ -248,6 +257,8 @@ class LoginMixin:
248
257
  progress_reporter.report_stage("waiting_login", current=result.doi)
249
258
  else:
250
259
  progress_reporter.clear_attention(key)
260
+ if (progress_reporter.read_state() or {}).get("stage") == "waiting_login":
261
+ progress_reporter.report_stage("checking_access", current=result.doi)
251
262
  result._login_attention = message
252
263
 
253
264
  @contextmanager
@@ -355,6 +366,11 @@ class LoginMixin:
355
366
  f"{self._login_wait_page(page)} after {self.page_wait_sec:.0f} s")
356
367
  self._wait_ran_out(result)
357
368
  return False
369
+ # Navigation and auto-submit can finish during the preceding
370
+ # wait. Never publish the classification of the old document.
371
+ user_step = self._users_login_step(page)
372
+ wait.observe(page, user_step)
373
+ deadline = wait.deadline
358
374
  message = ""
359
375
  if user_step:
360
376
  kind = self._login_wait_page(page)
@@ -372,8 +388,9 @@ class LoginMixin:
372
388
  away_from_publisher = True
373
389
  elif here.hostname and away_from_publisher:
374
390
  away_from_publisher, returned = False, True
375
- result._login_round_trip = True
376
- self._event(result, "login_round_trip_returned", here.geturl()[:160])
391
+ if getattr(result, "_visited_idp", False):
392
+ result._login_round_trip = True
393
+ self._event(result, "login_round_trip_returned", here.geturl()[:160])
377
394
  if (on_publisher and self._is_success_article_url(here.geturl())
378
395
  and not self._is_auth_page(here.geturl()) and not self._challenge_shell(page)
379
396
  and (returned or time.time() - last_probe >= self.WAIT_PROBE_EVERY_SEC)
@@ -381,7 +398,7 @@ class LoginMixin:
381
398
  # Whoever signed in (this program or the user), the article page may
382
399
  # give its PDF although it still looks signed out to the rules (ASCE's
383
400
  # "GET ACCESS" after the login waited out five minutes, 2026-11-02): try it.
384
- after_login, returned, last_probe = returned, False, time.time()
401
+ after_login, returned, last_probe = returned and self._school_login_done(), False, time.time()
385
402
  if self._probe_pdf_while_waiting(page, result, after_login=after_login):
386
403
  return False # signed in, and the page still offers or denies the article
387
404
  elif (visited_idp and on_publisher and article_returns < 2
@@ -579,6 +596,12 @@ class LoginMixin:
579
596
  or any(self._CARSI_OPTION.search(label) for label in entries)):
580
597
  continue
581
598
  return f"{name}: {', '.join(label[:40] for label in entries[:6])}"
599
+ if self._on_publisher_host(str(getattr(page, "url", "") or "")):
600
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
601
+ if listing.is_visible() is True:
602
+ entries = [label.strip() for label in listing.get_by_role("link").all_text_contents() if label.strip()]
603
+ if len(entries) >= 2 and not any(self._CARSI_OPTION.search(label) for label in entries):
604
+ return f"federation links: {', '.join(label[:40] for label in entries[:6])}"
582
605
  return ""
583
606
 
584
607
  def _openathens_lacks_school(self, page: Any) -> bool:
@@ -1234,16 +1257,45 @@ class LoginMixin:
1234
1257
  return now - outside_since >= self.page_wait_sec, outside_since
1235
1258
 
1236
1259
  def _users_login_step(self, page: Any) -> bool:
1237
- """The user's own step of the login, which may take the long wait
1238
- (``login_timeout_sec``): the school's login page (a password field, or the
1239
- school's identity provider), or a school chooser when no school is
1240
- configured or the user chooses by hand. Any other page off the publisher's
1241
- site is not: Atypon's iam.atypon.com hub, where AHA's login stopped on
1242
- 2026-11-03, was taken for the school's page and waited three minutes."""
1260
+ """Require a current credential/consent control, not just an IdP URL."""
1243
1261
  url = str(getattr(page, "url", "") or "")
1244
- if self._school_password_box(page, url) or self._is_idp_host(urlparse(url).netloc):
1262
+ if self._is_human_login_page(page):
1245
1263
  return True
1246
- return self._is_auth_page(url) and (not self.institution_query or bool(getattr(self, "_manual_school", False)))
1264
+ return (not self._is_idp_host(urlparse(url).netloc) and self._is_auth_page(url)
1265
+ and (not self.institution_query or bool(getattr(self, "_manual_school", False))))
1266
+
1267
+ def _idp_user_action(self, page: Any) -> bool:
1268
+ if not self._is_idp_host(urlparse(str(getattr(page, "url", "") or "")).netloc):
1269
+ return False
1270
+ if self._idp_confirmation(page):
1271
+ return True
1272
+ # Username-first and QR login pages may have no password box. Inspect
1273
+ # only visibility and labels; never collect input or QR contents.
1274
+ try:
1275
+ return self._idp_controls(page)
1276
+ except Exception as exc:
1277
+ if not _is_navigation_cut(exc):
1278
+ raise
1279
+ return self._read_cut_as_users_step("login controls", exc)
1280
+
1281
+ def _read_cut_as_users_step(self, what: str, exc: BaseException) -> bool:
1282
+ """A read cut off by the page navigating (Ovid right after the remembered
1283
+ school, on Chrome, 2026-11-07): this pass leaves the page to the user, as
1284
+ ``_has_visible_editable_input`` does, and the next pass reads the new page."""
1285
+ self._event(getattr(self, "_item_result", None), "page_read_interrupted",
1286
+ f"{what}, taken as the user's step: {type(exc).__name__}: {(str(exc).splitlines() or [''])[0][:160]}")
1287
+ return True
1288
+
1289
+ @staticmethod
1290
+ def _idp_controls(page: Any) -> bool:
1291
+ return page.evaluate("""() => {
1292
+ const visible = el => el.getClientRects().length > 0;
1293
+ const input = [...document.querySelectorAll('input')].some(el => visible(el)
1294
+ && !el.disabled && !el.readOnly && ['text','email','tel'].includes(el.type));
1295
+ const qr = [...document.querySelectorAll('img,canvas,[role="img"]')].some(el => visible(el)
1296
+ && /qr|二维码|扫码/i.test([el.id,el.className,el.getAttribute('alt'),el.getAttribute('aria-label')].join(' ')));
1297
+ return input || qr;
1298
+ }""") is True
1247
1299
 
1248
1300
  def _login_wait_page(self, page: Any) -> str:
1249
1301
  """Where a login that waited on the user ended (ADR 0012):
@@ -1259,26 +1311,27 @@ class LoginMixin:
1259
1311
  url = str(getattr(page, "url", "") or "")
1260
1312
  # The school's own page, by the same test as the long wait: a publisher's
1261
1313
  # SSO hub (iam.atypon.com) is no school login (2026-11-03).
1262
- if self._school_password_box(page, url) or self._is_idp_host(urlparse(url).netloc):
1314
+ if self._school_password_box(page, url) or self._idp_user_action(page):
1263
1315
  return "school_login"
1316
+ if self._is_idp_host(urlparse(url).netloc):
1317
+ return "authentication_redirect"
1264
1318
  if self._is_auth_page(url):
1265
1319
  return "institution_chooser" if self.institution_query else "school_choice"
1266
1320
  return "publisher" if self._on_publisher_host(url) else "other"
1267
1321
 
1268
1322
  def _is_human_login_page(self, page: Any) -> bool:
1269
- current_url = str(getattr(page, "url", "") or "")
1270
- host = (urlparse(current_url).netloc or "").lower()
1271
- if self.config.get("publisher_institution_federation") == "carsi":
1272
- if self._school_password_box(page, current_url):
1273
- return True
1274
- if not self._on_publisher_host(current_url):
1275
- return not self._is_federation_chooser(current_url)
1276
- return self._is_idp_host(host)
1323
+ url = str(getattr(page, "url", "") or "")
1324
+ return self._school_password_box(page, url) or self._idp_user_action(page)
1277
1325
 
1278
1326
  def _school_password_box(self, page: Any, url: str) -> bool:
1279
1327
  """A password or one-time-code field that is not a personal account's box on the publisher's site."""
1280
- return bool(page.locator('input[type="password"]:visible, input[autocomplete="one-time-code"]:visible').count()
1281
- and not self._personal_login_box(page, url))
1328
+ try:
1329
+ return bool(page.locator('input[type="password"]:visible, input[autocomplete="one-time-code"]:visible').count()
1330
+ and not self._personal_login_box(page, url))
1331
+ except Exception as exc:
1332
+ if not _is_navigation_cut(exc):
1333
+ raise
1334
+ return self._read_cut_as_users_step("password box", exc)
1282
1335
 
1283
1336
  def _personal_login_box(self, page: Any, url: str) -> bool:
1284
1337
  """A publisher account form can be on an article, login page or SSO host.
@@ -1645,16 +1698,16 @@ class LoginMixin:
1645
1698
  try:
1646
1699
  button = (page.get_by_role("button", name="Next", exact=True) if selector == self._NEXT_BUTTON
1647
1700
  else page.locator(selector)).first
1648
- if button.is_visible(timeout=1_500):
1701
+ if button.is_visible(timeout=1_500) and button.is_enabled():
1649
1702
  try:
1650
1703
  text = (button.inner_text(timeout=1_000) or "").strip().lower()
1651
1704
  except Exception:
1652
1705
  text = ""
1653
1706
  if "continue reading" in text:
1654
1707
  continue
1655
- button.click(timeout=5_000, no_wait_after=True)
1656
- self._event(result, "institution_continue", selector)
1657
- return
1708
+ if self._click_control(page, button, result, "institution continue"):
1709
+ self._event(result, "institution_continue", selector)
1710
+ return
1658
1711
  except Exception as exc:
1659
1712
  if after_selection:
1660
1713
  # Our own selection's Continue failed: keep why (RSC's Next, 2026-11-01).
@@ -125,6 +125,7 @@ class UserRequestsMixin:
125
125
  return
126
126
  from ..browser.foreground import show
127
127
 
128
+ show(page, self.config)
128
129
  wait = getattr(result, "_login_wait", None)
129
130
  if wait is not None and getattr(result, "_login_attention", ""):
130
131
  wait.take_over()
@@ -132,7 +133,6 @@ class UserRequestsMixin:
132
133
  verification_wait = getattr(result, "_verification_wait", None)
133
134
  if verification_wait is not None:
134
135
  verification_wait.take_over()
135
- show(page, self.config)
136
136
  except (watchdog.BrowserUnresponsive, UserMarkedNoEntitlement):
137
137
  raise
138
138
  except Exception as exc: