papersearch 0.4.9 → 0.4.11

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 (142) hide show
  1. package/LICENSE +1 -1
  2. package/NOTICE +23 -0
  3. package/README.en.md +136 -247
  4. package/README.md +136 -247
  5. package/assets/carsi-flow.en.png +0 -0
  6. package/assets/carsi-flow.png +0 -0
  7. package/assets/overview.en.png +0 -0
  8. package/assets/overview.png +0 -0
  9. package/assets/progress-capsule.en.png +0 -0
  10. package/assets/progress-capsule.png +0 -0
  11. package/carsi/README.md +6 -7
  12. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  13. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  14. package/carsi/paper_search_carsi/adapters/iop/__init__.py +8 -2
  15. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  16. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  17. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  18. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  19. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
  20. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  21. package/carsi/paper_search_carsi/assets/capsule.html +134 -18
  22. package/carsi/paper_search_carsi/browser/backend.py +269 -233
  23. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  24. package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
  25. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  26. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  27. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  28. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  29. package/carsi/paper_search_carsi/browser/login.py +12 -18
  30. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  31. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  32. package/carsi/paper_search_carsi/browser/watchdog.py +113 -58
  33. package/carsi/paper_search_carsi/cli.py +22 -7
  34. package/carsi/paper_search_carsi/cold_start.py +65 -51
  35. package/carsi/paper_search_carsi/config.py +6 -4
  36. package/carsi/paper_search_carsi/download_diagnostics.py +2 -1
  37. package/carsi/paper_search_carsi/engine/batch.py +17 -7
  38. package/carsi/paper_search_carsi/engine/batch_capture.py +97 -31
  39. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  40. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
  41. package/carsi/paper_search_carsi/engine/batch_institution.py +132 -13
  42. package/carsi/paper_search_carsi/engine/batch_login.py +151 -18
  43. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  44. package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
  45. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  46. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  47. package/carsi/paper_search_carsi/engine/supplements.py +36 -2
  48. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  49. package/carsi/paper_search_carsi/network.py +1 -1
  50. package/carsi/paper_search_carsi/progress_capsule.py +6 -2
  51. package/carsi/paper_search_carsi/progress_reporter.py +107 -9
  52. package/carsi/paper_search_carsi/progress_view.py +78 -1
  53. package/carsi/paper_search_carsi/server.py +53 -10
  54. package/carsi/paper_search_carsi/session_broker.py +1 -1
  55. package/carsi/pyproject.toml +7 -7
  56. package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
  57. package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
  58. package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
  59. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  61. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  62. package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
  63. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/batch.js +59 -14
  65. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +28 -0
  67. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  68. package/dist/capabilities/pdf-discovery/batchSummary.js +155 -0
  69. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +56 -1
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +11 -4
  75. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +114 -30
  77. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +6 -0
  79. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +12 -0
  81. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  82. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  83. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  84. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  85. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  86. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +48 -0
  87. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  88. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  89. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  90. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  91. package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
  92. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
  93. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
  94. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  95. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  96. package/dist/cli.js +30 -15
  97. package/dist/cli.js.map +1 -1
  98. package/dist/config/ConfigService.d.ts.map +1 -1
  99. package/dist/config/ConfigService.js +28 -2
  100. package/dist/config/ConfigService.js.map +1 -1
  101. package/dist/config/apiKeySignup.d.ts +13 -0
  102. package/dist/config/apiKeySignup.d.ts.map +1 -0
  103. package/dist/config/apiKeySignup.js +32 -0
  104. package/dist/config/apiKeySignup.js.map +1 -0
  105. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  106. package/dist/infrastructure/runlog/failureClass.js +4 -0
  107. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  108. package/dist/management/capability-profile/index.d.ts +7 -0
  109. package/dist/management/capability-profile/index.d.ts.map +1 -1
  110. package/dist/management/capability-profile/index.js +7 -0
  111. package/dist/management/capability-profile/index.js.map +1 -1
  112. package/dist/management/carsi/installer.d.ts +26 -14
  113. package/dist/management/carsi/installer.d.ts.map +1 -1
  114. package/dist/management/carsi/installer.js +118 -74
  115. package/dist/management/carsi/installer.js.map +1 -1
  116. package/dist/management/carsi/runtime.d.ts +12 -1
  117. package/dist/management/carsi/runtime.d.ts.map +1 -1
  118. package/dist/management/carsi/runtime.js +30 -1
  119. package/dist/management/carsi/runtime.js.map +1 -1
  120. package/dist/management/diagnostics/index.d.ts.map +1 -1
  121. package/dist/management/diagnostics/index.js +4 -1
  122. package/dist/management/diagnostics/index.js.map +1 -1
  123. package/dist/management/failures/exportReport.js +3 -3
  124. package/dist/management/reports/index.d.ts.map +1 -1
  125. package/dist/management/reports/index.js +6 -1
  126. package/dist/management/reports/index.js.map +1 -1
  127. package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
  128. package/dist/platforms/SemanticScholarSearcher.js +2 -1
  129. package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
  130. package/package.json +3 -2
  131. package/skills/paper-search/SKILL.md +9 -9
  132. package/skills/paper-search/references/browser-download.md +7 -6
  133. package/skills/paper-search/references/capability-routing.md +3 -3
  134. package/skills/paper-search/references/carsi-setup.md +8 -7
  135. package/skills/paper-search/references/cli-contract.md +6 -6
  136. package/skills/paper-search/references/management-layer.md +3 -3
  137. package/skills/paper-search/references/publisher-support.md +2 -0
  138. package/skills/paper-search/references/troubleshooting.md +1 -2
  139. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  140. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  141. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  142. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -0,0 +1,42 @@
1
+ """One browser window and tab kept for a serial MCP batch, on its Playwright
2
+ worker thread. Used when the backend declares ``batch_window``
3
+ (browser/backend.py); only plain Playwright calls, no backend of its own."""
4
+ from contextvars import ContextVar
5
+
6
+ from .preview import ensure_enabled
7
+
8
+
9
+ class BatchBrowser:
10
+ def __init__(self):
11
+ self.context = None
12
+ self.page = None
13
+ self.info = None
14
+ self.id = ""
15
+
16
+ def open(self, downloader, *, relaunch=""):
17
+ if self.context is not None and not self.context.pages:
18
+ self.close()
19
+ if self.context is None:
20
+ self.context = downloader._launch_context(relaunch=relaunch)
21
+ self.info = downloader.browser
22
+ else:
23
+ downloader.browser = self.info
24
+ ensure_enabled(self.context, downloader.config)
25
+ if self.page is None or self.page.is_closed():
26
+ self.page = self.context.new_page()
27
+ return self.context
28
+
29
+ def finish_item(self):
30
+ # Keep the original tab and its native window. Article/PDF/login
31
+ # popups cannot leak into the next publisher's page detection.
32
+ for page in self.context.pages:
33
+ if page is not self.page and not page.is_closed():
34
+ page.close()
35
+
36
+ def close(self):
37
+ context, self.context, self.page, self.info = self.context, None, None, None
38
+ if context is not None:
39
+ context.close()
40
+
41
+
42
+ active_batch: ContextVar[BatchBrowser | None] = ContextVar("active_browser_batch", default=None)
@@ -28,7 +28,9 @@ _OBSERVE_SCRIPT = """() => {
28
28
 
29
29
  def observe_checkbox(page: Any) -> None:
30
30
  """Observe readiness only; never read or write the verification response."""
31
- page.evaluate(_OBSERVE_SCRIPT)
31
+ from .driver import main_world
32
+
33
+ page.evaluate(_OBSERVE_SCRIPT, **main_world(page)) # where the init script observes
32
34
 
33
35
 
34
36
  def prepare_context(context: Any) -> None:
@@ -65,24 +67,41 @@ def is_turnstile_frame(url: str) -> bool:
65
67
  and "/turnstile/" in parsed.path)
66
68
 
67
69
 
70
+ # A page that navigated away while it was read: the next check reads the new page.
71
+ _NAVIGATED = ("frame was detached", "frame has been detached", "element is not attached",
72
+ "execution context was destroyed")
73
+
74
+
68
75
  def is_image_verification(page: Any) -> bool:
69
76
  """Image puzzles expose controls but may have no readable instructions."""
70
- return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
77
+ from .driver import Error
78
+
79
+ try:
80
+ return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
71
81
  && !document.querySelector('meta[name="citation_doi"]')
72
82
  && [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
73
83
  el.getClientRects().length > 0)""") is True
84
+ except Error as exc:
85
+ # A passed verification navigates while it is being read (Wiley and
86
+ # ScienceDirect on Chrome, 2026-11-07): no puzzle on a page that is gone.
87
+ if any(text in str(exc).lower() for text in _NAVIGATED):
88
+ return False
89
+ raise
74
90
 
75
91
 
76
92
  def needs_manual_verification(page: Any) -> bool:
77
- """A visible reCAPTCHA on an already recognised verification page.
93
+ """A puzzle or reCAPTCHA on an already recognised verification page.
78
94
 
79
95
  Reading a checked box or a response token cannot prove that the enclosing
80
96
  page's confirmation was submitted. Leave both actions to the user.
81
97
  """
82
- from playwright.sync_api import Error
98
+ return is_image_verification(page) or has_visible_recaptcha(page)
99
+
100
+
101
+ def has_visible_recaptcha(page: Any) -> bool:
102
+ """Detect a reCAPTCHA prompt that remains after the outer page changes."""
103
+ from .driver import Error
83
104
 
84
- if is_image_verification(page):
85
- return True # image/puzzle tasks are always left to the user
86
105
  for frame in page.frames:
87
106
  parsed = urlsplit(str(frame.url or ""))
88
107
  if (parsed.scheme != "https" or parsed.hostname not in {
@@ -110,7 +129,7 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
110
129
  compact-height Cloudflare widget with its identifying iframe title can
111
130
  use its standard checkbox position. Expanded puzzles are left alone.
112
131
  """
113
- from playwright.sync_api import Error, TimeoutError
132
+ from .driver import Error, TimeoutError, main_world
114
133
 
115
134
  def note(reason: str) -> None:
116
135
  if observation is not None:
@@ -159,7 +178,7 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
159
178
  continue
160
179
  readiness = element.evaluate("""iframe =>
161
180
  window[Symbol.for('papersearch.turnstile.ready')]?.get(iframe.contentWindow) || 0
162
- """)
181
+ """, **main_world(element))
163
182
  if not readiness:
164
183
  note("waiting_ready_signal")
165
184
  continue # loading/automatic check; no click has been attempted
@@ -181,7 +200,7 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
181
200
  element.evaluate("""(iframe, revision) => {
182
201
  const ready = window[Symbol.for('papersearch.turnstile.ready')];
183
202
  if (ready?.get(iframe.contentWindow) === revision) ready.delete(iframe.contentWindow);
184
- }""", readiness)
203
+ }""", readiness, **main_world(element))
185
204
  except Error as exc:
186
205
  if not any(text in str(exc).lower() for text in (
187
206
  "frame was detached", "frame has been detached", "element is not attached",
@@ -1,6 +1,6 @@
1
- """Extract cookies via Camoufox for publisher access.
1
+ """Extract cookies via the download browser for publisher access.
2
2
 
3
- Opens a visible Camoufox window, lets user log in to their institution,
3
+ Opens a visible browser window, lets user log in to their institution,
4
4
  then captures and saves publisher cookies for automated downloads.
5
5
  """
6
6
 
@@ -114,19 +114,19 @@ def extract_via_browser(
114
114
  Result dict with success, cookies_count, domains, etc.
115
115
  """
116
116
  try:
117
- from .backend import launch
117
+ from .backend import CHROME_MISSING, launch
118
118
  from .backend import is_available as _browser_backend_available
119
- if not _browser_backend_available():
119
+ if not _browser_backend_available(config=config):
120
120
  return {
121
121
  "success": False,
122
122
  "error": "no browser backend available",
123
- "fix": "pip install 'camoufox[geoip]' && python -m camoufox fetch",
123
+ "fix": CHROME_MISSING,
124
124
  }
125
125
  except ImportError:
126
126
  return {
127
127
  "success": False,
128
128
  "error": "no browser backend available",
129
- "fix": "pip install 'camoufox[geoip]' && python -m camoufox fetch",
129
+ "fix": "paper-search carsi update",
130
130
  }
131
131
 
132
132
  from ..config import DATA_DIR
@@ -189,7 +189,7 @@ def extract_via_browser(
189
189
  _save_cookies_json(save_cookies, cookie_file)
190
190
  _save_cookies_netscape(save_cookies, netscape_file)
191
191
 
192
- # Import into Camoufox server if running
192
+ # Import into the shared browser if available
193
193
  browser_imported = 0
194
194
  try:
195
195
  from .engine import import_cookies, is_available
@@ -339,7 +339,7 @@ def publisher_login(
339
339
  Takes a DOI or publisher name, resolves to the article page, and opens
340
340
  a visible stealth browser. User clicks "Access through your institution",
341
341
  completes SSO login, then closes the browser. Cookies are captured and
342
- imported into Camoufox for automated downloads.
342
+ imported into the download browser for automated downloads.
343
343
 
344
344
  Args:
345
345
  identifier: DOI (e.g. 10.1126/science.aec6396) or publisher name
@@ -0,0 +1,29 @@
1
+ """The Playwright API package both browser backends run on: Patchright.
2
+
3
+ Patchright is Playwright's code under another package name, with Chromium's
4
+ automation traces removed. Its errors are its own classes, and ``evaluate``
5
+ runs in an isolated world unless told otherwise.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from patchright.sync_api import Error, TimeoutError # noqa: F401 (``except Error``)
12
+
13
+
14
+ def main_world(_target: Any = None) -> dict[str, Any]:
15
+ """``evaluate`` options for the page's own world, where init scripts run and
16
+ page globals live; Patchright evaluates in an isolated world by default."""
17
+ return {"isolated_context": False}
18
+
19
+
20
+ def is_driver_error(exc: BaseException, name: str = "") -> bool:
21
+ """An error raised by the driver (optionally of class ``name``), not a program bug."""
22
+ return type(exc).__module__.startswith("patchright.") and (not name or type(exc).__name__ == name)
23
+
24
+
25
+ def sync_bases() -> list[type]:
26
+ """The SyncBase classes whose calls the watchdog times."""
27
+ from patchright._impl import _sync_base
28
+
29
+ return [_sync_base.SyncBase]
@@ -1,10 +1,9 @@
1
- """Browser engine: Camoufox-based replacement for the old camofox daemon API.
1
+ """Browser engine: a shared browser for the routes outside the batch downloader.
2
2
 
3
- Provides the same public API as the old camofox.py (is_available, solve_url,
4
- get_cookies, get_html, import_cookies, evaluate_js, create_tab, close_tab,
5
- navigate_tab, get_snapshot, download_pdf_via_browser, fetch_url,
6
- get_captured_responses, close_all_tabs) but uses Camoufox's direct
7
- Playwright API instead of HTTP calls to an external daemon.
3
+ Public API (is_available, solve_url, get_cookies, get_html, import_cookies,
4
+ evaluate_js, create_tab, close_tab, navigate_tab, get_snapshot,
5
+ download_pdf_via_browser, fetch_url, get_captured_responses, close_all_tabs)
6
+ over the configured backend's Playwright API (backend.py).
8
7
 
9
8
  Uses a single shared browser instance with multiple tabs (pages). Cookies,
10
9
  login sessions, and Cloudflare bypass state are shared across all tabs.
@@ -28,14 +27,14 @@ from urllib.parse import urlparse
28
27
  logger = logging.getLogger(__name__)
29
28
 
30
29
  # ---------------------------------------------------------------------------
31
- # Browser backend (Camoufox via Playwright; ego-lite has its own driver)
30
+ # Browser backend (Chrome or ego-lite, both through Patchright)
32
31
  # ---------------------------------------------------------------------------
33
32
  # Everything in this module drives the Playwright sync API, shared by both
34
- # Camoufox and ego-lite. Backend selection lives in backend.py.
33
+ # backends. Backend selection lives in backend.py.
35
34
  # ---------------------------------------------------------------------------
36
35
 
37
36
  from .backend import ( # noqa: E402
38
- BACKEND_CAMOUFOX,
37
+ CHROME_MISSING,
39
38
  launch,
40
39
  launch_persistent_context,
41
40
  resolve_backend,
@@ -48,13 +47,14 @@ from .backend import ( # noqa: E402
48
47
  def _check_browser_backend(config: dict[str, Any] | None = None) -> bool:
49
48
  """True when the resolved backend can serve the Playwright API here.
50
49
 
51
- Camoufox when installed; ego always (whether its remote debugging is on
52
- is checked, with a hint for the user, when the browser is attached).
50
+ Chrome when installed; ego always (whether its remote
51
+ debugging is on is checked, with a hint for the user, when the browser is
52
+ attached).
53
53
  """
54
54
  from .backend import BACKEND_EGO, is_available
55
55
 
56
56
  backend = resolve_backend(config)
57
- return backend == BACKEND_EGO or (backend == BACKEND_CAMOUFOX and is_available(BACKEND_CAMOUFOX))
57
+ return backend == BACKEND_EGO or is_available(backend, config)
58
58
 
59
59
 
60
60
  # ---------------------------------------------------------------------------
@@ -233,10 +233,7 @@ def _get_shared_browser(config: dict[str, Any] | None = None):
233
233
  )
234
234
 
235
235
  if not _check_browser_backend(config):
236
- raise RuntimeError(
237
- "no Playwright browser backend available. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch "
238
- "(browser_backend=ego routes through the ego driver instead)"
239
- )
236
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
240
237
 
241
238
  # scihub_browser_headless overrides browser_headless for THIS shared
242
239
  # browser (the grey-source racing engine). It exists because the racing
@@ -286,10 +283,7 @@ def get_persistent_context(
286
283
  stable identity across multiple download runs.
287
284
  """
288
285
  if not _check_browser_backend(config):
289
- raise RuntimeError(
290
- "no Playwright browser backend available. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch "
291
- "(browser_backend=ego routes through the ego driver instead)"
292
- )
286
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
293
287
 
294
288
  headless = False
295
289
  humanize = True
@@ -352,7 +346,7 @@ def shutdown_shared_browser():
352
346
 
353
347
 
354
348
  # ---------------------------------------------------------------------------
355
- # Public API — drop-in replacements for camofox.py functions
349
+ # Public API
356
350
  # ---------------------------------------------------------------------------
357
351
 
358
352
  def is_available(config: dict[str, Any] | None = None) -> bool:
@@ -414,7 +408,7 @@ def solve_url(
414
408
  *,
415
409
  max_timeout: int = 60000,
416
410
  ) -> dict[str, Any] | None:
417
- """Fetch URL via Camoufox shared browser. Returns dict with status/solution keys."""
411
+ """Fetch URL via the shared browser. Returns dict with status/solution keys."""
418
412
  page = None
419
413
  try:
420
414
  _, context = _get_shared_browser(config)
@@ -582,7 +576,7 @@ def download_pdf_via_browser(
582
576
  *,
583
577
  timeout: float = 60.0,
584
578
  ) -> bool:
585
- """Download a PDF URL via Camoufox shared browser. Returns True on success.
579
+ """Download a PDF URL via the shared browser. Returns True on success.
586
580
 
587
581
  4-strategy cascade:
588
582
  1. Network response capture (from page.on("response"))
@@ -9,6 +9,7 @@ import ctypes
9
9
  import os
10
10
  import subprocess
11
11
  import threading
12
+ from collections.abc import Callable
12
13
  from concurrent.futures import Future
13
14
  from typing import Any
14
15
 
@@ -70,7 +71,7 @@ def _browser_pids(page: Any, config: dict) -> list[int]:
70
71
  return found
71
72
 
72
73
 
73
- def _activate_windows(pids: list[int], title: str = "") -> bool:
74
+ def _activate_windows(pids: list[int], window_title: Callable[[], str]) -> bool:
74
75
  from ctypes import wintypes
75
76
 
76
77
  user = ctypes.WinDLL("user32", use_last_error=True)
@@ -98,14 +99,17 @@ def _activate_windows(pids: list[int], title: str = "") -> bool:
98
99
  user.EnumWindows(visit, 0)
99
100
  if not found:
100
101
  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)
102
+ # The window whose caption starts with the waiting tab's title, else any.
103
+ candidates = []
104
+ title = window_title().casefold()
105
+ if title:
106
+ for hwnd in found:
107
+ caption = ctypes.create_unicode_buffer(1024)
108
+ user.GetWindowTextW(hwnd, caption, len(caption))
109
+ if caption.value.casefold().startswith(title):
110
+ candidates.append(hwnd)
111
+ candidates = candidates or found
107
112
  active = user.GetForegroundWindow()
108
- candidates = matches or found
109
113
  hwnd = active if active in candidates else candidates[0]
110
114
  if user.IsIconic(hwnd):
111
115
  user.ShowWindow(hwnd, 9) # SW_RESTORE, only this browser's minimized window
@@ -145,7 +149,7 @@ def activate_mac(pid: int) -> bool:
145
149
  else:
146
150
  activated = bool(app.activateWithOptions_(AppKit.NSApplicationActivateIgnoringOtherApps
147
151
  | AppKit.NSApplicationActivateAllWindows))
148
- # Activation alone leaves miniaturized Firefox windows in the Dock.
152
+ # Activation alone leaves miniaturized windows in the Dock.
149
153
  # The same reopen event as a Dock click restores them. Address the
150
154
  # existing PID, so a stale request can never launch another browser.
151
155
  return activated and _reopen_mac(pid)
@@ -190,12 +194,14 @@ def show(page: Any, config: dict) -> None:
190
194
  page.bring_to_front() # select this task's tab; macOS activation is done by the capsule
191
195
  if os.name != "nt":
192
196
  return
193
- from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
197
+ from .driver import TimeoutError as PlaywrightTimeoutError
194
198
 
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()):
199
+ def window_title() -> str:
200
+ try:
201
+ return (page.locator('head > title').first.text_content(timeout=1000) or "").strip()
202
+ except PlaywrightTimeoutError:
203
+ return ""
204
+
205
+ if _activate_windows(_browser_pids(page, config), window_title):
200
206
  return
201
207
  raise RuntimeError("the download browser window could not be activated")
@@ -8,14 +8,8 @@ import atexit
8
8
  from pathlib import Path
9
9
  from typing import Any
10
10
 
11
- try:
12
- from .backend import launch
13
- from .backend import BACKEND_CAMOUFOX
14
- from .backend import is_available as _browser_backend_available
15
- _HAS_CLOAKBROWSER = _browser_backend_available(BACKEND_CAMOUFOX)
16
- except ImportError:
17
- launch = None # type: ignore[assignment]
18
- _HAS_CLOAKBROWSER = False
11
+ from .backend import CHROME_MISSING, launch
12
+ from .backend import is_available as _browser_backend_available
19
13
  from ..log import get_logger
20
14
 
21
15
  log = get_logger()
@@ -53,8 +47,8 @@ class PersistentBrowser:
53
47
 
54
48
  def _start(self, config: dict[str, Any] | None = None):
55
49
  """Start a new browser instance. Restores saved state if available."""
56
- if not _HAS_CLOAKBROWSER:
57
- raise RuntimeError("camoufox not installed. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch")
50
+ if not _browser_backend_available(config=config):
51
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
58
52
  log.info(" [browser] Starting persistent browser...")
59
53
  self._browser = launch(
60
54
  headless=False, humanize=True,
@@ -207,23 +201,23 @@ def _save_cookies_json(cookies: list[dict[str, Any]], cookie_file: Path) -> None
207
201
 
208
202
 
209
203
  def _save_cookies_netscape(cookies: list[dict[str, Any]], cookie_file: Path) -> None:
210
- """Save cookies in Netscape format (Camoufox import compatible)."""
204
+ """Save cookies in Netscape format (the shared browser imports this format)."""
211
205
  from .cookies import cookies_to_netscape
212
206
  cookie_file.write_text(cookies_to_netscape(cookies), encoding="utf-8")
213
207
 
214
208
 
215
209
  def _import_to_browser(cookie_file: Path, config: dict[str, Any]) -> int:
216
- """Import cookies into Camoufox. Returns count imported."""
210
+ """Import cookies into the shared browser. Returns count imported."""
217
211
  try:
218
212
  from .engine import import_cookies, is_available
219
213
  if not is_available(config):
220
- log.info(" [browser] Camoufox not running, skipping auto-import")
214
+ log.info(" [browser] no browser backend, skipping auto-import")
221
215
  return 0
222
216
  count = import_cookies(cookie_file, config)
223
- log.info(f" [browser] Imported {count} cookies into Camoufox")
217
+ log.info(f" [browser] Imported {count} cookies into the browser")
224
218
  return count
225
219
  except Exception as exc:
226
- log.info(f" [browser] Could not auto-import to Camoufox: {exc}")
220
+ log.info(f" [browser] Could not auto-import to the browser: {exc}")
227
221
  return 0
228
222
 
229
223
 
@@ -246,7 +240,7 @@ def open_login_browser(
246
240
  cookie_file: Path to save captured cookies (JSON).
247
241
  detect_login: Optional callable(browser_context, page) -> bool for custom login detection.
248
242
  max_wait: Max seconds to wait for login.
249
- auto_import: Whether to auto-import cookies into Camoufox.
243
+ auto_import: Whether to auto-import cookies into the shared browser.
250
244
  keep_alive: If True, return (True, context, page) without closing browser.
251
245
  publisher: Publisher name (unused; kept for callers).
252
246
 
@@ -257,8 +251,8 @@ def open_login_browser(
257
251
  print(f"\n 请在浏览器中登录 ({url})")
258
252
  print(" 程序会自动检测登录完成...\n")
259
253
 
260
- if not _HAS_CLOAKBROWSER:
261
- log.info(" [browser] camoufox not installed")
254
+ if not _browser_backend_available(config=config):
255
+ log.info(f" [browser] {CHROME_MISSING}")
262
256
  return (False, None, None, None) if keep_alive else False
263
257
 
264
258
  try:
@@ -23,7 +23,7 @@ from urllib.parse import urlsplit
23
23
  from uuid import UUID, uuid4
24
24
  from weakref import WeakKeyDictionary
25
25
 
26
- from .watchdog import BrowserUnresponsive
26
+ from .watchdog import BrowserUnresponsive, operation_remaining
27
27
  from ..entitlements import UserMarkedNoEntitlement
28
28
 
29
29
  _OBSERVERS = WeakKeyDictionary()
@@ -32,6 +32,7 @@ _KINDS = {'blank', 'article', 'pdf', 'login', 'other'}
32
32
  OBSERVE_INTERVAL_SEC = 4 # between unforced frames (waits refresh at most this often)
33
33
  MAX_KEPT_FRAMES = 5 # earlier page states kept per download, besides each tab's newest frame
34
34
  JPEG_QUALITY = 60
35
+ SCREENSHOT_TIMEOUT_MS = 1500
35
36
 
36
37
 
37
38
  def _atomic(path: Path, data: bytes) -> None:
@@ -62,6 +63,7 @@ class BrowserPreview:
62
63
  self.observing = False
63
64
  self.paused = 0
64
65
  self._cdp = WeakKeyDictionary()
66
+ self._navigation_listeners = {}
65
67
  context.on('close', self.close)
66
68
  self._write([])
67
69
  context.on('page', self._attach_page)
@@ -74,22 +76,30 @@ class BrowserPreview:
74
76
  # browser calls. Capture at the next workflow observation instead.
75
77
  self.page_revisions[page] = self.page_revisions.get(page, 0) + 1
76
78
  self.last_observed = 0.0
79
+ self._navigation_listeners[page] = changed
77
80
  page.on('domcontentloaded', changed)
78
81
 
79
- def close(self, *_args):
82
+ def close(self, *_args, browser_closed=True):
80
83
  self.closed = True
81
84
  try:
82
85
  if self._is_current():
83
- self._write(self.pages)
86
+ self._write(self.pages, browser_closed=browser_closed)
84
87
  except OSError:
85
88
  logging.getLogger(__name__).warning('browser_preview_unavailable')
86
89
  finally:
90
+ self.context.remove_listener('close', self.close)
91
+ self.context.remove_listener('page', self._attach_page)
92
+ for page, changed in self._navigation_listeners.items():
93
+ page.remove_listener('domcontentloaded', changed)
94
+ self._navigation_listeners.clear()
95
+ if self._is_current():
96
+ _ACTIVE.pop(str(self.directory.resolve()))
87
97
  _OBSERVERS.pop(self.context, None)
88
98
 
89
99
  def _is_current(self):
90
100
  return _ACTIVE.get(str(self.directory.resolve())) == self.context_id
91
101
 
92
- def _write(self, pages):
102
+ def _write(self, pages, *, browser_closed=False):
93
103
  # screenshot() can yield to another context's navigation callback.
94
104
  # Recheck at publication, not only when the observation starts.
95
105
  if not self._is_current():
@@ -99,13 +109,16 @@ class BrowserPreview:
99
109
  packet = {'schema_version': 1, 'run_id': self.run_id, 'identifier': self.identifier,
100
110
  'context_id': self.context_id,
101
111
  'owner_pid': os.getpid(), 'revision': self.revision,
102
- 'observed_at': self.observed_at, 'browser_closed': self.closed, 'pages': pages}
112
+ 'observed_at': self.observed_at, 'browser_closed': browser_closed, 'pages': pages}
103
113
  _atomic(self.directory / 'current.json', json.dumps(packet).encode())
104
114
 
105
115
  def observe(self, *, force=False):
106
116
  if self.closed or not self._is_current() or self.observing or (not force and (
107
117
  self.paused or time.monotonic() - self.last_observed < OBSERVE_INTERVAL_SEC)):
108
118
  return
119
+ remaining = operation_remaining()
120
+ if remaining is not None and remaining * 1000 <= SCREENSHOT_TIMEOUT_MS:
121
+ return # Leave the remaining page time to the download, with the last preview intact.
109
122
  self.observing = True
110
123
  try:
111
124
  self._observe()
@@ -135,7 +148,7 @@ class BrowserPreview:
135
148
  data = session.send("Page.captureScreenshot",
136
149
  {"format": "jpeg", "quality": JPEG_QUALITY, "fromSurface": True})
137
150
  return base64.b64decode(data["data"])
138
- return page.screenshot(timeout=1500, full_page=False, type="jpeg", quality=JPEG_QUALITY)
151
+ return page.screenshot(timeout=SCREENSHOT_TIMEOUT_MS, full_page=False, type="jpeg", quality=JPEG_QUALITY)
139
152
 
140
153
  def _observe(self):
141
154
  self.last_observed = time.monotonic()
@@ -363,13 +376,19 @@ def prune(directory: str | Path, keep: int = DEFAULT_KEEP_RUNS) -> list[str]:
363
376
  def ensure_enabled(context, config: dict | None = None):
364
377
  """Enable the preview for this download context unless turned off; never raises."""
365
378
  config = config or {}
366
- if config.get("browser_preview") is False:
367
- return None
368
- existing = _OBSERVERS.get(context) if context is not None else None
369
- if existing is not None:
370
- return existing
371
- directory = default_directory(config)
372
379
  try:
380
+ existing = _OBSERVERS.get(context) if context is not None else None
381
+ enabled = config.get("browser_preview") is not False
382
+ if existing is not None:
383
+ from .. import progress_reporter
384
+ identity = progress_reporter.read_state() or {}
385
+ if (enabled and existing.run_id == identity.get("run_id")
386
+ and existing.identifier == str(identity.get("current") or "").lower()):
387
+ return existing
388
+ existing.close(browser_closed=False)
389
+ if not enabled:
390
+ return None
391
+ directory = default_directory(config)
373
392
  directory.mkdir(parents=True, mode=0o700, exist_ok=True)
374
393
  try:
375
394
  keep = int(config.get("browser_preview_keep_runs", DEFAULT_KEEP_RUNS))
@@ -24,7 +24,7 @@ SESSION_COOKIES_MAX_AGE_SEC = 12 * 3600
24
24
  def _save_session_cookies(context: Any, profile: Path) -> None:
25
25
  """Keep session cookies (IdP and publisher logins) for the next launch.
26
26
 
27
- Each paper runs in a new backend process and browser; Firefox drops
27
+ Each paper runs in a new backend process and browser; the browser drops
28
28
  cookies without an expiry when it closes, so every paper asked for the
29
29
  school login again. Only session cookies are kept: persistent ones are in
30
30
  the profile already. The file is readable by the user only.
@@ -66,26 +66,20 @@ def _restore_session_cookies(context: Any, profile: Path) -> int:
66
66
 
67
67
 
68
68
  def _profile_owner_pid(user_data_dir: str) -> int | None:
69
- """PID of the browser holding this profile, if any.
70
-
71
- Firefox (Camoufox) leaves a ``lock`` symlink to ``<host>:+<pid>``;
72
- Chromium leaves ``SingletonLock`` to ``<host>-<pid>``.
73
- """
74
- for name in ("lock", "SingletonLock"):
75
- try:
76
- target = os.readlink(Path(user_data_dir) / name)
77
- except OSError:
78
- continue
79
- match = re.search(r"[-+](\d+)$", target)
80
- if match:
81
- return int(match.group(1))
82
- return None
69
+ """PID of the browser holding this profile, if any: Chromium's
70
+ ``SingletonLock`` symlink to ``<host>-<pid>`` (macOS and Linux)."""
71
+ try:
72
+ target = os.readlink(Path(user_data_dir) / "SingletonLock")
73
+ except OSError:
74
+ return None
75
+ match = re.search(r"-(\d+)$", target)
76
+ return int(match.group(1)) if match else None
83
77
 
84
78
 
85
79
  def _lock_file_held(path: Path) -> bool:
86
- """Another process holds this lock file: Firefox's ``.parentlock`` on macOS
87
- and Linux (an fcntl lock; macOS has no ``lock`` symlink), its ``parent.lock``
88
- on Windows (opened without sharing). The lock is tested, never kept."""
80
+ """Another process holds this lock file: Chromium's ``lockfile`` on Windows,
81
+ which the running browser keeps open without write sharing (an fcntl lock
82
+ elsewhere). The lock is tested, never kept."""
89
83
  if not path.exists():
90
84
  return False
91
85
  try:
@@ -110,14 +104,13 @@ def _lock_file_held(path: Path) -> bool:
110
104
 
111
105
 
112
106
  def profile_holder(user_data_dir: str) -> str:
113
- """Who still holds this profile ("" = nobody): a live ``lock`` owner, or a
114
- lock file another process holds."""
107
+ """Who still holds this profile ("" = nobody): a live ``SingletonLock``
108
+ owner, or a ``lockfile`` another process holds (Windows)."""
115
109
  pid = _profile_owner_pid(user_data_dir)
116
110
  if pid is not None and _pid_alive(pid):
117
111
  return f"lock of pid {pid}"
118
- for name in (".parentlock", "parent.lock"):
119
- if _lock_file_held(Path(user_data_dir) / name):
120
- return f"{name} held"
112
+ if _lock_file_held(Path(user_data_dir) / "lockfile"):
113
+ return "lockfile held"
121
114
  return ""
122
115
 
123
116