papersearch 0.4.5 → 0.4.7

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 (71) hide show
  1. package/README.en.md +7 -4
  2. package/README.md +7 -4
  3. package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
  4. package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
  5. package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
  6. package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
  7. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
  8. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
  9. package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
  10. package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
  11. package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
  12. package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
  13. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
  14. package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
  15. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
  16. package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
  17. package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
  18. package/carsi/paper_search_carsi/assets/capsule.html +64 -21
  19. package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
  20. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +142 -0
  21. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
  22. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
  23. package/carsi/paper_search_carsi/browser/backend.py +36 -0
  24. package/carsi/paper_search_carsi/browser/background.py +68 -0
  25. package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
  26. package/carsi/paper_search_carsi/browser/challenges.py +10 -0
  27. package/carsi/paper_search_carsi/browser/foreground.py +201 -0
  28. package/carsi/paper_search_carsi/browser/login.py +3 -1
  29. package/carsi/paper_search_carsi/browser/preview.py +3 -1
  30. package/carsi/paper_search_carsi/config.py +4 -1
  31. package/carsi/paper_search_carsi/engine/batch.py +62 -20
  32. package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
  33. package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
  34. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +31 -10
  35. package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
  36. package/carsi/paper_search_carsi/engine/batch_login.py +264 -204
  37. package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
  38. package/carsi/paper_search_carsi/engine/batch_waits.py +76 -30
  39. package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
  40. package/carsi/paper_search_carsi/engine/page_activity.py +177 -0
  41. package/carsi/paper_search_carsi/engine/supplements.py +12 -1
  42. package/carsi/paper_search_carsi/entitlements.py +23 -3
  43. package/carsi/paper_search_carsi/progress_capsule.py +130 -18
  44. package/carsi/paper_search_carsi/progress_macos.py +166 -0
  45. package/carsi/paper_search_carsi/progress_reporter.py +22 -1
  46. package/carsi/paper_search_carsi/progress_view.py +8 -6
  47. package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
  48. package/carsi/paper_search_carsi/server.py +17 -1
  49. package/carsi/paper_search_carsi/user_settings.py +4 -4
  50. package/carsi/pyproject.toml +1 -1
  51. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  53. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  54. package/dist/capabilities/pdf-discovery/batch.js +28 -4
  55. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  56. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  57. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
  58. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  59. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  60. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  61. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.js +3 -2
  63. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  64. package/dist/management/carsi/installer.d.ts +2 -1
  65. package/dist/management/carsi/installer.d.ts.map +1 -1
  66. package/dist/management/carsi/installer.js +24 -1
  67. package/dist/management/carsi/installer.js.map +1 -1
  68. package/package.json +1 -1
  69. package/skills/paper-search/references/browser-download.md +11 -7
  70. package/skills/paper-search/references/carsi-setup.md +1 -0
  71. package/skills/paper-search/references/publisher-support.md +42 -41
@@ -126,32 +126,58 @@ class PublisherBatchDownloader(
126
126
  self._adapter = cls(self)
127
127
  return self._adapter
128
128
 
129
- def _download_in_new_tab(self, page: Any, url: str) -> tuple[Path, str]:
129
+ def _download_in_new_tab(self, page: Any, url: str, *, result: DownloadResult | None = None) -> tuple[Path, str]:
130
130
  """Open the file in a new tab, as typed in the address bar, and take what
131
131
  the browser downloads. Clicks on the page were flaky after the first
132
132
  file (a later file's download never started); new tabs took 8 of 8
133
133
  (Taylor & Francis with ego, 2026-11-01)."""
134
+ from .page_activity import transfer
135
+ from .supplements import MAX_FILE_BYTES
136
+
134
137
  tab = page.context.new_page()
138
+ path = None
139
+ completed = False
135
140
  try:
136
- with tab.expect_download(timeout=60_000) as info:
137
- try:
138
- tab.goto(url, referer=str(page.url), timeout=60_000)
139
- except Exception as exc:
140
- if not _is_browser_error(exc):
141
- raise # the navigation ends where the download starts
142
- download = info.value
141
+ activity = getattr(result, "_page_activity", None)
142
+ if activity is not None:
143
+ activity.observe(tab)
144
+ downloads = []
145
+ tab.on("download", lambda item: downloads.append(item))
146
+ deadline = time.monotonic() + 60
147
+ try:
148
+ referer = str(page.url)
149
+ tab.goto(url, timeout=60_000,
150
+ **({"referer": referer} if referer.startswith(("http://", "https://")) else {}))
151
+ except Exception as exc:
152
+ if not _is_browser_error(exc):
153
+ raise
143
154
  with tempfile.NamedTemporaryFile(prefix="papersearch-supplement-", suffix=".part", delete=False) as fh:
144
155
  path = Path(fh.name)
145
- try:
146
- download.save_as(str(path))
147
- name = download.suggested_filename
148
- # Keep the browser's temporary copy out of the Python heap.
149
- download.delete()
150
- except BaseException:
151
- path.unlink(missing_ok=True)
152
- raise
153
- return path, name
156
+ while time.monotonic() < deadline:
157
+ if result is not None:
158
+ self._check_user_decision(result, tab)
159
+ if downloads:
160
+ download = downloads[0]
161
+ with transfer(result):
162
+ download.save_as(str(path))
163
+ name = download.suggested_filename
164
+ download.delete()
165
+ completed = True
166
+ return path, name
167
+ if self._pdf_viewer_present(tab):
168
+ # Inline attachments produce no download event. Reuse the
169
+ # native reader, copying at most 1 MiB across each bridge
170
+ # call directly to disk, under the attachment size limit.
171
+ with transfer(result):
172
+ saved = self._capture_loaded_pdf_viewer(tab, url, output=path, max_bytes=MAX_FILE_BYTES)
173
+ if saved == path:
174
+ completed = True
175
+ return path, Path(unquote(urlparse(url).path)).name or "supplement.pdf"
176
+ tab.wait_for_timeout(min(250, max(1, int((deadline - time.monotonic()) * 1000))))
177
+ raise TimeoutError("attachment download or native PDF was not ready")
154
178
  finally:
179
+ if path is not None and not completed:
180
+ path.unlink(missing_ok=True)
155
181
  tab.close()
156
182
 
157
183
  def collect_supplements(self, context: Any, doi: str, output_dir: Path,
@@ -162,6 +188,7 @@ class PublisherBatchDownloader(
162
188
  from .supplement_transfer import browser_request
163
189
 
164
190
  self._phase(result, "supplements")
191
+ main_state = result.state
165
192
  progress_reporter.update(part="supplements", supplements_saved=0, supplements_total=None)
166
193
  try:
167
194
  page = context.new_page()
@@ -191,8 +218,20 @@ class PublisherBatchDownloader(
191
218
  self._event(result, "supplements_failed", "verification not completed")
192
219
  return [{"status": "failed", "reason": "challenge_timeout", "url": url, "label": ""}]
193
220
  settle(page, 2_000)
194
- self._wait_for_page_text(page, result)
195
- links = self._settled_supplement_links(page, doi)
221
+ while True:
222
+ # The initial check can finish on a blank redirect, and
223
+ # the adapter can trigger a later navigation. Neither is
224
+ # evidence that the article has no supplementary files.
225
+ self._wait_for_page_text(page, result)
226
+ if not self._wait_for_challenge(page, result):
227
+ self._event(result, "supplements_failed", "verification not completed")
228
+ return [{"status": "failed", "reason": "challenge_timeout", "url": url, "label": ""}]
229
+ self._wait_for_page_text(page, result)
230
+ if self._challenge_shell(page) or self._is_challenge_page(page):
231
+ continue
232
+ links = self._settled_supplement_links(page, doi)
233
+ if not (self._challenge_shell(page) or self._is_challenge_page(page)):
234
+ break
196
235
  if links is None:
197
236
  self._event(result, "supplements_not_supported", self.profile.name)
198
237
  return [{"status": "skipped", "reason": "supplements_not_supported", "url": url, "label": ""}]
@@ -215,7 +254,8 @@ class PublisherBatchDownloader(
215
254
  files = supplements.collect(request, links, Path(output_dir), doi,
216
255
  manifest_dir=manifest_dir,
217
256
  target_dir=Path(output_dir) / "supplements" if self.config.get("diagnostics_dir") else None,
218
- download=lambda url: self._download_in_new_tab(page, url),
257
+ download=lambda url: self._download_in_new_tab(page, url, result=result),
258
+ activity=user_watch.activity.progress,
219
259
  progress=lambda saved: progress_reporter.update(supplements_saved=saved))
220
260
  saved = sum(1 for f in files if f.get("status") == "saved")
221
261
  self._event(result, "supplements_saved", f"{saved}/{len(files)}")
@@ -250,6 +290,8 @@ class PublisherBatchDownloader(
250
290
  finally:
251
291
  user_watch.set()
252
292
  watchdog.clear_interrupt()
293
+ if result.ok:
294
+ result.state = main_state
253
295
  self._close_phase(result)
254
296
  try:
255
297
  page.close()
@@ -19,6 +19,7 @@ from urllib.parse import urljoin, urlparse
19
19
  import requests
20
20
 
21
21
  from . import access_rules
22
+ from .page_activity import transfer
22
23
  from .batch_common import (
23
24
  page_operation,
24
25
  POLL_MS,
@@ -173,7 +174,8 @@ class CaptureMixin:
173
174
  continue
174
175
  tries[url] = tries.get(url, 0) + 1
175
176
  try:
176
- fetched = page.evaluate(self._FETCH_PDF_JS, {"url": url, "timeout": int(min(10, remaining) * 1000)})
177
+ with transfer(result):
178
+ fetched = page.evaluate(self._FETCH_PDF_JS, {"url": url, "timeout": int(min(10, remaining) * 1000)})
177
179
  except Exception as exc:
178
180
  if not _is_browser_error(exc):
179
181
  raise
@@ -410,7 +412,8 @@ class CaptureMixin:
410
412
  or not self._response_matches_article(response, doi, **article_options)):
411
413
  rejected_pdf_urls.update(self._response_urls(response))
412
414
  return
413
- payload = cdp_session.send("Fetch.getResponseBody", {"requestId": request_id})
415
+ with transfer(result):
416
+ payload = cdp_session.send("Fetch.getResponseBody", {"requestId": request_id})
414
417
  body = (
415
418
  base64.b64decode(payload["body"], validate=True)
416
419
  if payload.get("base64Encoded")
@@ -534,7 +537,8 @@ class CaptureMixin:
534
537
  if self._should_defer_response_body(url):
535
538
  captured["deferred_url"] = url
536
539
  return
537
- body = response.body()
540
+ with transfer(result):
541
+ body = response.body()
538
542
  # Body-level block-page detection (some block pages are 200
539
543
  # with an HTML "IP Address Blocked" body).
540
544
  if not body[:5] == b"%PDF-" and not captured["block_reason"]:
@@ -714,7 +718,8 @@ class CaptureMixin:
714
718
  if not self._refusal_answer(response):
715
719
  rejected_pdf_urls.update(self._response_urls(response))
716
720
  else:
717
- body = response.body()
721
+ with transfer(result):
722
+ body = response.body()
718
723
  if self._accept_pdf_body(body, response_url):
719
724
  captured["bytes"] = body
720
725
  captured["url"] = response.url
@@ -1145,7 +1150,8 @@ class CaptureMixin:
1145
1150
  if (self._uses_article_pdf_validation()
1146
1151
  and self._is_supplementary_url(str(getattr(download, "suggested_filename", "") or ""))):
1147
1152
  return None, pdf_url
1148
- path = download.path()
1153
+ with transfer(result):
1154
+ path = download.path()
1149
1155
  body = Path(path).read_bytes()
1150
1156
  final_url = str(getattr(download, "url", "") or pdf_url)
1151
1157
  if self._uses_article_pdf_validation() and (
@@ -1358,7 +1364,8 @@ class CaptureMixin:
1358
1364
  page.wait_for_timeout(2 * POLL_MS)
1359
1365
  return None, ""
1360
1366
 
1361
- def _capture_loaded_pdf_viewer(self, page: Any, source_url: str) -> bytes | None:
1367
+ def _capture_loaded_pdf_viewer(self, page: Any, source_url: str, *,
1368
+ output: Path | None = None, max_bytes: int | None = None) -> bytes | Path | None:
1362
1369
  """Read a PDF already loaded by Firefox's native PDF.js viewer.
1363
1370
 
1364
1371
  The viewer runs in a privileged native realm. Accessing its
@@ -1369,7 +1376,7 @@ class CaptureMixin:
1369
1376
  repeated ``app.open`` calls while the document loads.
1370
1377
  """
1371
1378
  script = r"""
1372
- async (sourceUrl) => {
1379
+ async ({sourceUrl, maxBytes}) => {
1373
1380
  try {
1374
1381
  const nativeWindow = window.wrappedJSObject || window;
1375
1382
  const nativeLocation = String(nativeWindow.location?.href || "");
@@ -1409,7 +1416,12 @@ class CaptureMixin:
1409
1416
  if (!app.pdfDocument || typeof app.pdfDocument.getData !== "function") {
1410
1417
  return null;
1411
1418
  }
1419
+ if (maxBytes) {
1420
+ const info = await app.pdfDocument.getDownloadInfo();
1421
+ if (info.length > maxBytes) return {oversized: info.length};
1422
+ }
1412
1423
  const data = await app.pdfDocument.getData();
1424
+ if (maxBytes && data.byteLength > maxBytes) return {oversized: data.byteLength};
1413
1425
  // Crossing the Xray/automation boundary with one large Blob
1414
1426
  // causes a large transient allocation. Keep the native bytes
1415
1427
  // here and transfer at most 1 MiB per bridge call instead.
@@ -1439,11 +1451,14 @@ class CaptureMixin:
1439
1451
  }
1440
1452
  """
1441
1453
  try:
1442
- encoded = page.evaluate(script, source_url)
1454
+ encoded = page.evaluate(script, {"sourceUrl": source_url, "maxBytes": max_bytes})
1443
1455
  except Exception:
1444
1456
  return None
1457
+ if isinstance(encoded, dict) and "oversized" in encoded:
1458
+ from .supplements import SupplementTooLarge
1459
+ raise SupplementTooLarge(encoded["oversized"])
1445
1460
  if isinstance(encoded, dict) and isinstance(encoded.get("transfer"), str):
1446
- return self._read_viewer_chunks(page, encoded["transfer"], encoded.get("size"))
1461
+ return self._read_viewer_chunks(page, encoded["transfer"], encoded.get("size"), output=output)
1447
1462
  if not isinstance(encoded, str) or not encoded.startswith("data:"):
1448
1463
  return None
1449
1464
  try:
@@ -1452,11 +1467,14 @@ class CaptureMixin:
1452
1467
  except (ValueError, TypeError):
1453
1468
  return None
1454
1469
  if len(body) > MIN_PDF_BYTES and body.startswith(b"%PDF-"):
1470
+ if output is not None:
1471
+ output.write_bytes(body)
1472
+ return output
1455
1473
  return body
1456
1474
  return None
1457
1475
 
1458
1476
  @staticmethod
1459
- def _read_viewer_chunks(page: Any, token: str, size: Any) -> bytes | None:
1477
+ def _read_viewer_chunks(page: Any, token: str, size: Any, *, output: Path | None = None) -> bytes | Path | None:
1460
1478
  """Bound bridge/Blob allocations while preserving exact bytes and cleanup."""
1461
1479
  read_chunk = r"""async ({token, offset, length}) => {
1462
1480
  try {
@@ -1476,22 +1494,38 @@ class CaptureMixin:
1476
1494
  } catch (_) { return null; }
1477
1495
  }"""
1478
1496
  body = bytearray()
1497
+ sink = None
1498
+ complete = False
1479
1499
  try:
1480
1500
  if type(size) is not int or size <= MIN_PDF_BYTES:
1481
1501
  return None
1502
+ if output is not None:
1503
+ sink = output.open("wb")
1482
1504
  for offset in range(0, size, 1024 * 1024):
1483
1505
  length = min(1024 * 1024, size - offset)
1484
1506
  encoded = page.evaluate(read_chunk, {"token": token, "offset": offset, "length": length})
1485
1507
  if not isinstance(encoded, str) or not encoded.startswith("data:"):
1486
1508
  return None
1487
1509
  part = base64.b64decode(encoded.split(",", 1)[1], validate=True)
1488
- if len(part) != length:
1510
+ if len(part) != length or (offset == 0 and not part.startswith(b"%PDF-")):
1489
1511
  return None
1490
- body.extend(part)
1512
+ if sink is not None:
1513
+ sink.write(part)
1514
+ else:
1515
+ body.extend(part)
1516
+ complete = True
1517
+ if output is not None:
1518
+ return output
1491
1519
  return bytes(body) if body.startswith(b"%PDF-") else None
1492
1520
  except Exception:
1521
+ if output is not None:
1522
+ raise
1493
1523
  return None
1494
1524
  finally:
1525
+ if sink is not None:
1526
+ sink.close()
1527
+ if output is not None and not complete:
1528
+ output.unlink(missing_ok=True)
1495
1529
  try:
1496
1530
  page.evaluate("""token => { const w = window.wrappedJSObject || window;
1497
1531
  if (w.__carsiPdfTransfer?.token === token) delete w.__carsiPdfTransfer; }""", token)
@@ -1547,13 +1581,14 @@ class CaptureMixin:
1547
1581
  from ..network import proxy_dict
1548
1582
  proxies = proxy_dict(ctx_proxy)
1549
1583
  try:
1550
- resp = requests.get(
1551
- url,
1552
- headers=headers,
1553
- timeout=(10, 60),
1554
- allow_redirects=True,
1555
- proxies=proxies,
1556
- )
1584
+ with transfer(getattr(self, "_item_result", None)):
1585
+ resp = requests.get(
1586
+ url,
1587
+ headers=headers,
1588
+ timeout=(10, 60),
1589
+ allow_redirects=True,
1590
+ proxies=proxies,
1591
+ )
1557
1592
  # This request is not the browser: a 403/429 here (bot protection,
1558
1593
  # ScienceDirect's challenge, 2026-10-31) says nothing about the
1559
1594
  # browser's access and must not stop the batch. Only a block page counts.
@@ -212,7 +212,10 @@ def pump_until(page: Any, done: Callable[[], bool], timeout_ms: int, step_ms: in
212
212
  # after the request and held DOMContentLoaded back until 33 s on an ad script
213
213
  # that never answered (headless probe, 2026-11-02); the login's returns to the
214
214
  # article waited 32-40 s each for it.
215
- _DOCUMENT_STATE_JS = "() => [document.readyState, document.body ? document.body.innerText.length : 0]"
215
+ # This is DOM readiness, not an access verdict. Avoid laying out the whole
216
+ # article, and do not read its body at all once the parser has finished.
217
+ _DOCUMENT_STATE_JS = """() => [document.readyState,
218
+ document.readyState === 'loading' && document.body ? document.body.textContent.length : 0]"""
216
219
 
217
220
 
218
221
  def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int = 15_000, **kwargs: Any) -> Any:
@@ -221,7 +224,31 @@ def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int =
221
224
  parsed or its text stops growing; a verification page is left untouched at
222
225
  once. The caller checks the page state it needs (``settle``, the access rule,
223
226
  the verification wait). Returns the response."""
224
- response = page.goto(url, wait_until="commit", timeout=timeout_ms, **kwargs)
227
+ committed = False
228
+
229
+ def navigated(frame: Any) -> None:
230
+ nonlocal committed
231
+ if frame == page.main_frame and str(frame.url).startswith(("https://", "http://")):
232
+ committed = True
233
+
234
+ started = time.monotonic()
235
+ page.on("framenavigated", navigated)
236
+ try:
237
+ try:
238
+ response = page.goto(url, wait_until="commit", timeout=timeout_ms, **kwargs)
239
+ except Exception as exc:
240
+ # A script redirect can replace the requested navigation before goto
241
+ # returns (Firefox NS_ERROR_ABORT). Continue only after an observed
242
+ # top-level document commit; the caller still checks identity/access.
243
+ if not _is_browser_error(exc) or not any(
244
+ marker in str(exc) for marker in ("NS_ERROR_ABORT", "net::ERR_ABORTED")):
245
+ raise
246
+ left = max(0, min(ready_ms, timeout_ms - int((time.monotonic() - started) * 1000)))
247
+ if not committed and not pump_until(page, lambda: committed, left):
248
+ raise
249
+ response = None
250
+ finally:
251
+ page.remove_listener("framenavigated", navigated)
225
252
  text = {"size": -1, "since": time.time()} # the body text's length, and since when
226
253
 
227
254
  def readable() -> bool:
@@ -75,18 +75,34 @@ class DiagnosticsMixin:
75
75
  f"{spent['slowest']} {spent['slowest_sec']:.0f} s")
76
76
  result._last_event_at = now
77
77
  result.events.append(item)
78
+ activity = getattr(result, "_page_activity", None)
79
+ if activity is not None and state in {
80
+ "article_open", "institution_federation_selected", "article_access_ready",
81
+ "pdf_capture_started", "browser_pdf_response_captured", "pdf_saved",
82
+ "supplements_found", "supplements_saved", "challenge_resolved",
83
+ # The login steps the program takes itself: while it is still
84
+ # choosing the school the page is not waiting for the user (JBJS on
85
+ # OpenAthens, 2026-11-06: five remembered-school clicks in 25 s, no
86
+ # main-frame navigation, and a "no progress" reminder in between).
87
+ "sso_entry_clicked", "openathens_entry", "seamlessaccess_chooser_opened",
88
+ "auto_remembered_entry", "institution_selected", "auto_institution_search",
89
+ "institution_search_submitted", "institution_search_retyped",
90
+ "institution_list_submitted", "institution_continue",
91
+ "login_round_trip_returned", "redirect_page_passed",
92
+ }:
93
+ activity.progress()
78
94
  # Only publish fixed phase text; event details can contain signed URLs.
79
95
  report = {
80
96
  "article_open": ("打开论文页面", "opening_article"),
81
- "sso_start": ("机构登录", "waiting_login"),
82
- "institution_federation_selected": ("已进入所选机构认证联盟", "waiting_login"),
83
- "institution_selection_required": ("请在 CARSI 页面自行选择学校并完成登录", "waiting_login"),
84
- "institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "waiting_login"),
85
- "login_state": ("机构登录", "waiting_login"),
97
+ "sso_start": ("正在查找机构登录入口", "checking_access"),
98
+ "institution_federation_selected": ("已进入所选机构认证联盟", "checking_access"),
99
+ "institution_selection_required": ("检查学校选择入口", "checking_access"),
100
+ "institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "checking_access"),
101
+ "login_state": ("检查机构登录页面", "checking_access"),
86
102
  "idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
87
- "login_attempt_started": ("正在尝试机构登录", "waiting_login"),
88
- "login_retry_wait": ("机构登录暂未完成,准备重试", "waiting_login"),
89
- "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "waiting_login"),
103
+ "login_attempt_started": ("正在尝试机构登录", "checking_access"),
104
+ "login_retry_wait": ("机构登录暂未完成,准备重试", "checking_access"),
105
+ "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "checking_access"),
90
106
  "login_stopped": ("机构登录未完成", "route_failed"),
91
107
  "challenge_manual_wait": ("等待人工安全验证", "waiting_verification"),
92
108
  "challenge_wait": ("正在检查安全验证", "checking_access"),
@@ -99,17 +115,19 @@ class DiagnosticsMixin:
99
115
  "browser_pdf_response_captured": ("PDF 已捕获,正在保存", "pdf_captured"),
100
116
  "pdf_saved": ("PDF 已保存,待内容核验", "saved_pending_verification"),
101
117
  }.get(state)
118
+ if state == "login_state" and getattr(result, "_login_attention", ""):
119
+ report = ("等待在浏览器完成机构登录", "waiting_login")
102
120
  if state == "challenge_wait" and detail.startswith("manual "):
103
121
  report = ("等待人工安全验证", "waiting_verification")
104
122
  if state == "login_attempt_started" and detail in {"1/3", "2/3", "3/3"}:
105
- report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "waiting_login")
123
+ report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "checking_access")
106
124
  if state == "login_observed":
107
125
  if detail == "verification":
108
126
  report = ("正在检查安全验证", "checking_access")
109
127
  elif detail == "human_login":
110
128
  report = ("等待在浏览器完成机构登录", "waiting_login")
111
129
  else:
112
- report = ("检查机构登录页面", "waiting_login")
130
+ report = ("检查机构登录页面", "checking_access")
113
131
  # A click can finish after a synchronous PDF response was captured;
114
132
  # capture_started supplies its stage without moving it backwards.
115
133
  if report:
@@ -125,6 +143,9 @@ class DiagnosticsMixin:
125
143
  return ""
126
144
  now = time.monotonic()
127
145
  current = getattr(result, "_phase_now", None)
146
+ activity = getattr(result, "_page_activity", None)
147
+ if activity is not None and name and (current is None or current[0] != name):
148
+ activity.progress()
128
149
  if current:
129
150
  result.phases[current[0]] = round(result.phases.get(current[0], 0.0) + now - current[1], 1)
130
151
  result._phase_now = (name, now) if name else None
@@ -190,9 +190,10 @@ class InstitutionMixin:
190
190
  }
191
191
  return null;
192
192
  }"""
193
- # The chooser's own submit: the nearest shown control around what was chosen,
194
- # the first after it ("Access through Institution" on ACS, "Go" on JAMA). What
195
- # was chosen is a list (its index among document.querySelectorAll('select')) or
193
+ # The chooser's own submit: the nearest control around what was chosen,
194
+ # the first after it. A custom UI can hide both its school list and native
195
+ # submit; a unique nearby native Select/Continue still belongs to it.
196
+ # What was chosen is a list (its index among document.querySelectorAll('select')) or
196
197
  # an entry (a selector), whose form's controls only, or with no form none of
197
198
  # another form's; ``controls`` names the controls that count (null: any button
198
199
  # or link-button). Never a control of the page outside the chooser, such as the
@@ -200,18 +201,23 @@ class InstitutionMixin:
200
201
  _LIST_SUBMIT_JS = r"""([anchor, controls]) => {
201
202
  const s = typeof anchor === 'number' ? document.querySelectorAll('select')[anchor] : document.querySelector(anchor);
202
203
  if (!s) return null;
203
- const own = typeof anchor === 'number' ? undefined : s.closest('form');
204
+ const own = s.form || s.closest('form');
204
205
  const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden' && !el.disabled;
205
- const text = el => (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || '')
206
+ const text = el => (el.innerText || el.value || el.textContent || el.getAttribute('aria-label') || el.getAttribute('title') || '')
206
207
  .replace(/\s+/g, ' ').trim();
207
208
  const CONTROL = controls || ('button, input[type="submit"], input[type="button"], input[type="image"], '
208
209
  + 'a[href^="javascript" i], a[role="button"], [role="button"], a.button, a.btn');
209
- const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot/i;
210
+ const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot|subscribe|purchase|\bbuy\b/i;
211
+ const NATIVE_ACTION = /^(?:select|continue|go|next|sign\s*in|log\s*in|选择|继续|登录)$|access.*institut/i;
210
212
  for (let box = s.parentElement, n = 0; box && n < 6; box = box.parentElement, n++) {
211
- const found = [...box.querySelectorAll(CONTROL)].filter(c => !s.contains(c) && shown(c) && text(c).length <= 60
212
- && !NOT.test(text(c)) && (own === undefined || !('form' in c) || c.form === own));
213
- if (!found.length) continue;
214
- const pick = found.find(c => s.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING) || found[found.length - 1];
213
+ const candidates = [...box.querySelectorAll(CONTROL)].filter(c => !s.contains(c) && !c.disabled && text(c).length <= 60
214
+ && !NOT.test(text(c)) && (('form' in c ? c.form : c.closest('form')) === own));
215
+ const found = candidates.filter(shown);
216
+ const native = typeof anchor === 'number' && !shown(s) && own
217
+ ? candidates.filter(c => c.type === 'submit' && c.form === own && !shown(c) && NATIVE_ACTION.test(text(c))) : [];
218
+ if (!found.length && native.length !== 1) continue;
219
+ const pick = native.length === 1 ? native[0]
220
+ : (found.find(c => s.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING) || found[found.length - 1]);
215
221
  document.querySelectorAll('[data-paper-search-submit]').forEach(e => e.removeAttribute('data-paper-search-submit'));
216
222
  pick.setAttribute('data-paper-search-submit', '');
217
223
  return text(pick).slice(0, 80) || pick.tagName;
@@ -260,9 +266,18 @@ class InstitutionMixin:
260
266
 
261
267
  @staticmethod
262
268
  def _filled_lists(lists: Any, federation: dict) -> dict:
263
- """The lists other than the federation's with more than a placeholder."""
269
+ """Filled school lists, not the header's journal/language/search lists.
270
+
271
+ Only positive institution evidence can establish that a school is
272
+ missing. An unrelated filled dropdown says nothing about an empty
273
+ institution list that is still loading.
274
+ """
275
+ school = re.compile(r"institut|school|universit|\buniv\b|college|organi[sz]ation|\bidp\b|大学|学院|研究院", re.I)
264
276
  return {str(s.get("name")): list(s.get("options") or ()) for s in lists or ()
265
- if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1}
277
+ if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1
278
+ and (school.search(str(s.get("name") or "")) or any(
279
+ school.search(str(o[1])) for o in s.get("options") or ()
280
+ if isinstance(o, (list, tuple)) and len(o) == 2))}
266
281
 
267
282
  # The list chosen in, marked by its index among document.querySelectorAll('select'):
268
283
  # a locator's "select" would also count lists inside shadow roots.
@@ -591,12 +606,39 @@ class InstitutionMixin:
591
606
  entries = []
592
607
  for role in ("link", "button"):
593
608
  try:
594
- for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s+\S", re.I)).all()[:10]:
609
+ for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s*\S", re.I)).all()[:10]:
595
610
  if entry.is_visible() is True:
596
- label = re.sub(r"^\s*access through\s+", "", entry.inner_text(timeout=1_000), flags=re.I)
611
+ label = re.sub(r"^\s*access through\s*", "", entry.inner_text(timeout=1_000), flags=re.I)
597
612
  entries.append((self._institution_match_score(label), label, entry))
598
613
  except Exception:
599
614
  continue
615
+ if not any(score >= 2 for score, _, _ in entries):
616
+ # A widget's accessible name can differ from its visible school
617
+ # text, or it can be a clickable div/span without a role. Use
618
+ # the visible control text, still requiring a click affordance.
619
+ candidates = page.evaluate("""() => {
620
+ document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
621
+ e.removeAttribute('data-paper-search-remembered'));
622
+ const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
623
+ const native = el.matches('a[href],button,[role="button"]');
624
+ if (!native && el.closest('a,button,[role="button"]')) return false;
625
+ const text = (el.textContent || '').trim();
626
+ return text.length <= 160 && /^access through\\s*\\S/i.test(text)
627
+ && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
628
+ && !el.disabled && el.getAttribute('aria-disabled') !== 'true'
629
+ && (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
630
+ });
631
+ return items.filter(el => !items.some(other => other !== el && el.contains(other)))
632
+ .slice(0,10).map((el,i) => {
633
+ el.setAttribute('data-paper-search-remembered', String(i));
634
+ return {i, text:(el.textContent || '').trim()};
635
+ });
636
+ }""")
637
+ if isinstance(candidates, list):
638
+ for candidate in candidates:
639
+ label = re.sub(r"^\s*access through\s*", "", candidate["text"], flags=re.I)
640
+ entries.append((self._institution_match_score(label), label,
641
+ page.locator(f'[data-paper-search-remembered="{candidate["i"]}"]')))
600
642
  top = max((score for score, _, _ in entries), default=0)
601
643
  best = [(label, entry) for score, label, entry in entries if score == top]
602
644
  if top >= 2 and len(best) == 1: