papersearch 0.4.4 → 0.4.6

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 (72) 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 +112 -32
  19. package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
  20. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -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 +73 -21
  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 +10 -0
  35. package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
  36. package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
  37. package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
  38. package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
  39. package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
  40. package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
  41. package/carsi/paper_search_carsi/engine/supplement_transfer.py +55 -0
  42. package/carsi/paper_search_carsi/engine/supplements.py +96 -24
  43. package/carsi/paper_search_carsi/entitlements.py +23 -3
  44. package/carsi/paper_search_carsi/progress_capsule.py +246 -30
  45. package/carsi/paper_search_carsi/progress_macos.py +166 -0
  46. package/carsi/paper_search_carsi/progress_reporter.py +22 -1
  47. package/carsi/paper_search_carsi/progress_view.py +1 -0
  48. package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
  49. package/carsi/paper_search_carsi/server.py +17 -1
  50. package/carsi/paper_search_carsi/user_settings.py +4 -4
  51. package/carsi/pyproject.toml +1 -1
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  54. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.js +28 -4
  56. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  57. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  58. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
  59. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  61. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  63. package/dist/infrastructure/runlog/failureClass.js +3 -2
  64. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  65. package/dist/management/carsi/installer.d.ts +2 -1
  66. package/dist/management/carsi/installer.d.ts.map +1 -1
  67. package/dist/management/carsi/installer.js +24 -1
  68. package/dist/management/carsi/installer.js.map +1 -1
  69. package/package.json +1 -1
  70. package/skills/paper-search/references/browser-download.md +11 -7
  71. package/skills/paper-search/references/carsi-setup.md +1 -0
  72. package/skills/paper-search/references/publisher-support.md +42 -41
@@ -0,0 +1,201 @@
1
+ """An explicit capsule click brings its download browser to the foreground.
2
+
3
+ No browser is launched here. Native activation is limited to the connected
4
+ ego profile's owner or descendants of this page's Playwright driver.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import ctypes
9
+ import os
10
+ import subprocess
11
+ import threading
12
+ from concurrent.futures import Future
13
+ from typing import Any
14
+
15
+ def _process_parents() -> dict[int, int]:
16
+ if os.name != "nt":
17
+ result = subprocess.run(["ps", "-axo", "pid=,ppid="], capture_output=True, text=True,
18
+ check=True, timeout=2)
19
+ return {int(parts[0]): int(parts[1]) for line in result.stdout.splitlines()
20
+ if len(parts := line.split()) == 2}
21
+ from ctypes import wintypes
22
+
23
+ class ProcessEntry(ctypes.Structure):
24
+ _fields_ = [("size", wintypes.DWORD), ("usage", wintypes.DWORD), ("pid", wintypes.DWORD),
25
+ ("heap", ctypes.c_size_t), ("module", wintypes.DWORD), ("threads", wintypes.DWORD),
26
+ ("parent", wintypes.DWORD), ("priority", wintypes.LONG), ("flags", wintypes.DWORD),
27
+ ("exe", wintypes.WCHAR * 260)]
28
+
29
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
30
+ kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
31
+ kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
32
+ for name in ("Process32FirstW", "Process32NextW"):
33
+ fn = getattr(kernel, name)
34
+ fn.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
35
+ fn.restype = wintypes.BOOL
36
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
37
+ snapshot = kernel.CreateToolhelp32Snapshot(2, 0)
38
+ if snapshot == ctypes.c_void_p(-1).value:
39
+ raise ctypes.WinError(ctypes.get_last_error())
40
+ try:
41
+ entry = ProcessEntry(size=ctypes.sizeof(ProcessEntry))
42
+ more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
43
+ parents = {}
44
+ while more and len(parents) < 65536:
45
+ parents[int(entry.pid)] = int(entry.parent)
46
+ more = kernel.Process32NextW(snapshot, ctypes.byref(entry))
47
+ return parents
48
+ finally:
49
+ kernel.CloseHandle(snapshot)
50
+
51
+
52
+ def _browser_pids(page: Any, config: dict) -> list[int]:
53
+ from .backend import BACKEND_EGO, ego_user_data_dir, resolve_backend
54
+ from .profiles import _profile_owner_pid
55
+
56
+ if resolve_backend(config) == BACKEND_EGO:
57
+ pid = _profile_owner_pid(str(ego_user_data_dir(config)))
58
+ return [pid] if pid else []
59
+ # Playwright has no public browser PID. Its pipe transport is the driver
60
+ # that launched this exact browser, including a persistent context.
61
+ driver = page.context._impl_obj._connection._transport._proc.pid
62
+ if not isinstance(driver, int) or isinstance(driver, bool) or driver <= 1:
63
+ raise RuntimeError("the download browser driver has no valid owner PID")
64
+ parents = _process_parents()
65
+ frontier, found = {int(driver)}, []
66
+ while frontier:
67
+ children = {pid for pid, parent in parents.items() if parent in frontier and pid not in found}
68
+ found.extend(sorted(children))
69
+ frontier = children
70
+ return found
71
+
72
+
73
+ def _activate_windows(pids: list[int], title: str = "") -> bool:
74
+ from ctypes import wintypes
75
+
76
+ user = ctypes.WinDLL("user32", use_last_error=True)
77
+ callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
78
+ user.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]
79
+ user.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
80
+ user.IsWindowVisible.argtypes = [wintypes.HWND]
81
+ user.IsIconic.argtypes = [wintypes.HWND]
82
+ user.GetWindow.argtypes = [wintypes.HWND, wintypes.UINT]
83
+ user.GetWindow.restype = wintypes.HWND
84
+ user.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
85
+ user.SetForegroundWindow.argtypes = [wintypes.HWND]
86
+ user.GetForegroundWindow.restype = wintypes.HWND
87
+ user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
88
+ found = []
89
+
90
+ @callback_type
91
+ def visit(hwnd, _):
92
+ pid = wintypes.DWORD()
93
+ user.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
94
+ if pid.value in pids and user.IsWindowVisible(hwnd) and not user.GetWindow(hwnd, 4):
95
+ found.append(hwnd)
96
+ return True
97
+
98
+ user.EnumWindows(visit, 0)
99
+ if not found:
100
+ return False
101
+ matches = []
102
+ for hwnd in found:
103
+ text = ctypes.create_unicode_buffer(1024)
104
+ user.GetWindowTextW(hwnd, text, len(text))
105
+ if title and text.value.casefold().startswith(title.casefold()):
106
+ matches.append(hwnd)
107
+ active = user.GetForegroundWindow()
108
+ candidates = matches or found
109
+ hwnd = active if active in candidates else candidates[0]
110
+ if user.IsIconic(hwnd):
111
+ user.ShowWindow(hwnd, 9) # SW_RESTORE, only this browser's minimized window
112
+ return bool(user.SetForegroundWindow(hwnd))
113
+
114
+
115
+ def mac_browser_pid(page: Any, config: dict) -> int:
116
+ """The owned browser application, never one of its nonactivatable helpers."""
117
+ import AppKit
118
+
119
+ for pid in _browser_pids(page, config):
120
+ app = AppKit.NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
121
+ if (app is not None and app.bundleURL() is not None
122
+ and app.activationPolicy() == AppKit.NSApplicationActivationPolicyRegular):
123
+ return pid
124
+ return 0
125
+
126
+
127
+ def activate_mac(pid: int) -> bool:
128
+ """Called by the clicked capsule, whose Cocoa loop owns the activation handoff.
129
+
130
+ macOS 14+ requires cooperative activation. The CLI's worker has no Cocoa
131
+ main loop and must not dispatch UI work to its own main thread.
132
+ """
133
+ import AppKit
134
+
135
+ def activate() -> bool:
136
+ app = AppKit.NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
137
+ if app is None or app.activationPolicy() != AppKit.NSApplicationActivationPolicyRegular:
138
+ return False
139
+ current = AppKit.NSRunningApplication.currentApplication()
140
+ native = AppKit.NSApplication.sharedApplication()
141
+ app.unhide()
142
+ if hasattr(native, "yieldActivationToApplication_"):
143
+ native.yieldActivationToApplication_(app)
144
+ activated = bool(app.activateFromApplication_options_(current, AppKit.NSApplicationActivateAllWindows))
145
+ else:
146
+ activated = bool(app.activateWithOptions_(AppKit.NSApplicationActivateIgnoringOtherApps
147
+ | AppKit.NSApplicationActivateAllWindows))
148
+ # Activation alone leaves miniaturized Firefox windows in the Dock.
149
+ # The same reopen event as a Dock click restores them. Address the
150
+ # existing PID, so a stale request can never launch another browser.
151
+ return activated and _reopen_mac(pid)
152
+
153
+ if threading.current_thread() is threading.main_thread():
154
+ return activate()
155
+ from PyObjCTools import AppHelper
156
+
157
+ answer: Future[bool] = Future()
158
+
159
+ def on_main():
160
+ if not answer.set_running_or_notify_cancel():
161
+ return
162
+ try:
163
+ answer.set_result(activate())
164
+ except Exception as exc:
165
+ answer.set_exception(exc)
166
+
167
+ AppHelper.callAfter(on_main)
168
+ try:
169
+ return answer.result(timeout=2)
170
+ except TimeoutError as exc:
171
+ answer.cancel()
172
+ raise TimeoutError("browser activation did not reach the capsule's native thread") from exc
173
+
174
+
175
+ def _reopen_mac(pid: int) -> bool:
176
+ import Foundation
177
+
178
+ descriptor = Foundation.NSAppleEventDescriptor
179
+ event = descriptor.appleEventWithEventClass_eventID_targetDescriptor_returnID_transactionID_(
180
+ int.from_bytes(b"aevt", "big"), int.from_bytes(b"rapp", "big"),
181
+ descriptor.descriptorWithProcessIdentifier_(pid), -1, 0)
182
+ _, error = event.sendEventWithOptions_timeout_error_(
183
+ Foundation.NSAppleEventSendWaitForReply | Foundation.NSAppleEventSendNeverInteract, 2, None)
184
+ if error is not None:
185
+ raise RuntimeError("the owned browser did not accept its reopen event")
186
+ return True
187
+
188
+
189
+ def show(page: Any, config: dict) -> None:
190
+ page.bring_to_front() # select this task's tab; macOS activation is done by the capsule
191
+ if os.name != "nt":
192
+ return
193
+ from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
194
+
195
+ try:
196
+ title = page.locator('head > title').first.text_content(timeout=1000) or ""
197
+ except PlaywrightTimeoutError:
198
+ title = "" # a title is optional; native activation still selects the task browser
199
+ if _activate_windows(_browser_pids(page, config), title.strip()):
200
+ return
201
+ raise RuntimeError("the download browser window could not be activated")
@@ -172,7 +172,9 @@ class PersistentBrowser:
172
172
 
173
173
  # Module-level singleton
174
174
  _browser = PersistentBrowser()
175
- atexit.register(_browser.close)
175
+ # Logging/capture streams may already be closed during interpreter shutdown.
176
+ # Explicit close still logs; the exit hook only releases owned browser resources.
177
+ atexit.register(_browser._cleanup)
176
178
 
177
179
 
178
180
  def get_browser(config: dict[str, Any] | None = None):
@@ -154,7 +154,9 @@ class BrowserPreview:
154
154
  row = {'page_id': page_id, 'host': host, 'kind': kind, 'screenshot_status': 'unavailable'}
155
155
  captured_at = time.time()
156
156
  try:
157
- if page.locator('input[type="password"]:visible').count():
157
+ # This is only a preview label, not an access decision. The
158
+ # :visible selector forces layout of a potentially long article.
159
+ if page.locator('input[type="password"]').count():
158
160
  row['kind'] = 'login'
159
161
  # The user requested the actual rendered page without preview
160
162
  # masks. Field values are never extracted into JSON or logs.
@@ -101,12 +101,14 @@ DEFAULT_CONFIG: dict[str, Any] = {
101
101
  # 任务启动时自动弹出悬浮进度条(独立进程,已有实例则不重复弹出)。
102
102
  "progress_bar_auto": True,
103
103
  # 需要登录学校或完成验证时,除了进度胶囊变色,再发一条系统通知;进度窗口的设置里可以关。
104
- "progress_notify": True,
104
+ "progress_notify": False,
105
105
  # 每篇文章在学校登录页等待用户输入的总时长上限,秒;从第一次等待算起。
106
106
  "browser_login_timeout": 180,
107
107
  # 不在学校登录页时(出版社页面、选机构页、人机验证、取 PDF 时等待处理)最多等多久,秒;
108
108
  # 连续超过就结束这一篇。进度窗口里可以改。
109
109
  "browser_page_wait_timeout": 60,
110
+ # 页面没有实际进展多久后提醒人工查看;仅控制提醒,不延长页面等待上限。
111
+ "browser_stall_notify_after": 30,
110
112
  # 每个出版社每小时最多打开的文章数,防止学校因下载过多被出版社暂停访问;0 = 不限。
111
113
  "publisher_hourly_limit": 100,
112
114
  # Turnstile 交互门(如 sci-hub.vg):无头会话下无法点击,默认跳过并冷却。
@@ -163,6 +165,7 @@ def save_config(config: dict[str, Any]) -> None:
163
165
 
164
166
  _VALIDATION_RULES: dict[str, tuple[type, Any, Any]] = {
165
167
  # key: (type, min_value, max_value)
168
+ "browser_stall_notify_after": (int, 1, 600),
166
169
  "connect_timeout": (int, 1, 60),
167
170
  "read_timeout": (int, 1, 120),
168
171
  "request_delay_min": (float, 0.0, 30.0),
@@ -19,6 +19,7 @@ import os
19
19
  import re
20
20
  import shutil
21
21
  import threading
22
+ import tempfile
22
23
  import time
23
24
  from dataclasses import asdict, dataclass, field
24
25
  from datetime import datetime
@@ -125,27 +126,58 @@ class PublisherBatchDownloader(
125
126
  self._adapter = cls(self)
126
127
  return self._adapter
127
128
 
128
- def _download_in_new_tab(self, page: Any, url: str) -> tuple[bytes, str]:
129
+ def _download_in_new_tab(self, page: Any, url: str, *, result: DownloadResult | None = None) -> tuple[Path, str]:
129
130
  """Open the file in a new tab, as typed in the address bar, and take what
130
131
  the browser downloads. Clicks on the page were flaky after the first
131
132
  file (a later file's download never started); new tabs took 8 of 8
132
133
  (Taylor & Francis with ego, 2026-11-01)."""
134
+ from .page_activity import transfer
135
+ from .supplements import MAX_FILE_BYTES
136
+
133
137
  tab = page.context.new_page()
138
+ path = None
139
+ completed = False
134
140
  try:
135
- with tab.expect_download(timeout=60_000) as info:
136
- try:
137
- tab.goto(url, referer=str(page.url), timeout=60_000)
138
- except Exception as exc:
139
- if not _is_browser_error(exc):
140
- raise # the navigation ends where the download starts
141
- download = info.value
142
- body = Path(download.path()).read_bytes()
143
- name = download.suggested_filename
144
- # Playwright keeps the browser's copy under a random id in a temp
145
- # folder; the file is saved under its own name, so the copy goes now.
146
- download.delete()
147
- return body, name
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
154
+ with tempfile.NamedTemporaryFile(prefix="papersearch-supplement-", suffix=".part", delete=False) as fh:
155
+ path = Path(fh.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")
148
178
  finally:
179
+ if path is not None and not completed:
180
+ path.unlink(missing_ok=True)
149
181
  tab.close()
150
182
 
151
183
  def collect_supplements(self, context: Any, doi: str, output_dir: Path,
@@ -153,8 +185,10 @@ class PublisherBatchDownloader(
153
185
  """Open the article page in a new tab of ``context`` (already logged in)
154
186
  and download every supplementary file the adapter lists there."""
155
187
  from . import supplements
188
+ from .supplement_transfer import browser_request
156
189
 
157
190
  self._phase(result, "supplements")
191
+ main_state = result.state
158
192
  progress_reporter.update(part="supplements", supplements_saved=0, supplements_total=None)
159
193
  try:
160
194
  page = context.new_page()
@@ -184,8 +218,20 @@ class PublisherBatchDownloader(
184
218
  self._event(result, "supplements_failed", "verification not completed")
185
219
  return [{"status": "failed", "reason": "challenge_timeout", "url": url, "label": ""}]
186
220
  settle(page, 2_000)
187
- self._wait_for_page_text(page, result)
188
- 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
189
235
  if links is None:
190
236
  self._event(result, "supplements_not_supported", self.profile.name)
191
237
  return [{"status": "skipped", "reason": "supplements_not_supported", "url": url, "label": ""}]
@@ -202,11 +248,15 @@ class PublisherBatchDownloader(
202
248
  return [{"status": "failed", "reason": incomplete, "url": "", "label": ""}]
203
249
  self._event(result, "supplements_found", str(len(links)))
204
250
  progress_reporter.update(supplements_total=len(links))
205
- files = supplements.collect(page.context.request, links, Path(output_dir), doi,
206
- manifest_dir=manifest_dir,
207
- target_dir=Path(output_dir) / "supplements" if self.config.get("diagnostics_dir") else None,
208
- download=lambda url: self._download_in_new_tab(page, url),
209
- progress=lambda saved: progress_reporter.update(supplements_saved=saved))
251
+ files = []
252
+ if links:
253
+ with browser_request(page, self.config, proxy=self._context_proxy.get(id(context))) as request:
254
+ files = supplements.collect(request, links, Path(output_dir), doi,
255
+ manifest_dir=manifest_dir,
256
+ target_dir=Path(output_dir) / "supplements" if self.config.get("diagnostics_dir") else None,
257
+ download=lambda url: self._download_in_new_tab(page, url, result=result),
258
+ activity=user_watch.activity.progress,
259
+ progress=lambda saved: progress_reporter.update(supplements_saved=saved))
210
260
  saved = sum(1 for f in files if f.get("status") == "saved")
211
261
  self._event(result, "supplements_saved", f"{saved}/{len(files)}")
212
262
  return files
@@ -240,6 +290,8 @@ class PublisherBatchDownloader(
240
290
  finally:
241
291
  user_watch.set()
242
292
  watchdog.clear_interrupt()
293
+ if result.ok:
294
+ result.state = main_state
243
295
  self._close_phase(result)
244
296
  try:
245
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,6 +75,13 @@ 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
+ }:
84
+ activity.progress()
78
85
  # Only publish fixed phase text; event details can contain signed URLs.
79
86
  report = {
80
87
  "article_open": ("打开论文页面", "opening_article"),
@@ -125,6 +132,9 @@ class DiagnosticsMixin:
125
132
  return ""
126
133
  now = time.monotonic()
127
134
  current = getattr(result, "_phase_now", None)
135
+ activity = getattr(result, "_page_activity", None)
136
+ if activity is not None and name and (current is None or current[0] != name):
137
+ activity.progress()
128
138
  if current:
129
139
  result.phases[current[0]] = round(result.phases.get(current[0], 0.0) + now - current[1], 1)
130
140
  result._phase_now = (name, now) if name else None