papersearch 0.4.11 → 0.4.12

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 (43) hide show
  1. package/README.en.md +3 -3
  2. package/README.md +3 -3
  3. package/carsi/paper_search_carsi/adapters/ams/__init__.py +12 -0
  4. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +5 -2
  5. package/carsi/paper_search_carsi/adapters/elsevier/sciencedirect.py +18 -1
  6. package/carsi/paper_search_carsi/adapters/iop/__init__.py +11 -2
  7. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +24 -14
  8. package/carsi/paper_search_carsi/assets/capsule.html +11 -1
  9. package/carsi/paper_search_carsi/browser/preview.py +16 -3
  10. package/carsi/paper_search_carsi/browser/watchdog.py +15 -0
  11. package/carsi/paper_search_carsi/capsule_placement.py +51 -31
  12. package/carsi/paper_search_carsi/download_diagnostics.py +1 -0
  13. package/carsi/paper_search_carsi/engine/access_rules.py +11 -0
  14. package/carsi/paper_search_carsi/engine/batch.py +13 -1
  15. package/carsi/paper_search_carsi/engine/batch_access.py +3 -0
  16. package/carsi/paper_search_carsi/engine/batch_capture.py +20 -0
  17. package/carsi/paper_search_carsi/engine/batch_common.py +4 -0
  18. package/carsi/paper_search_carsi/engine/batch_institution.py +27 -18
  19. package/carsi/paper_search_carsi/engine/bridge.py +5 -2
  20. package/carsi/paper_search_carsi/engine/supplements.py +34 -6
  21. package/carsi/paper_search_carsi/progress_capsule.py +87 -9
  22. package/carsi/paper_search_carsi/progress_macos.py +35 -10
  23. package/carsi/paper_search_carsi/progress_reporter.py +12 -5
  24. package/carsi/paper_search_carsi/progress_view.py +7 -1
  25. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  26. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +2 -0
  27. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  28. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  29. package/dist/cli.js +1 -1
  30. package/dist/cli.js.map +1 -1
  31. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  32. package/dist/infrastructure/runlog/failureClass.js +2 -0
  33. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  34. package/dist/management/updates/index.d.ts +6 -1
  35. package/dist/management/updates/index.d.ts.map +1 -1
  36. package/dist/management/updates/index.js +18 -11
  37. package/dist/management/updates/index.js.map +1 -1
  38. package/package.json +1 -3
  39. package/skills/paper-search/SKILL.md +4 -10
  40. package/skills/paper-search/references/browser-download.md +1 -1
  41. package/skills/paper-search/references/publisher-support.md +4 -4
  42. package/NOTICE +0 -23
  43. package/carsi/NOTICE +0 -5
@@ -9,7 +9,8 @@ import time
9
9
  from typing import Any
10
10
  from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
11
11
 
12
- from .batch_common import DownloadResult, _is_browser_error, logger, open_page, pump_until, settle
12
+ from .batch_common import (DownloadResult, _is_browser_error, _is_navigation_cut, logger, open_page,
13
+ pump_until, settle)
13
14
 
14
15
 
15
16
  def _school_auth_patterns(config: dict[str, Any]) -> tuple[str, ...]:
@@ -752,24 +753,32 @@ class InstitutionMixin:
752
753
  # A widget's accessible name can differ from its visible school
753
754
  # text, or it can be a clickable div/span without a role. Use
754
755
  # the visible control text, still requiring a click affordance.
755
- candidates = page.evaluate("""() => {
756
- document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
757
- e.removeAttribute('data-paper-search-remembered'));
758
- const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
759
- const native = el.matches('a[href],button,[role="button"]');
760
- if (!native && el.closest('a,button,[role="button"]')) return false;
761
- const text = (el.textContent || '').trim();
762
- return text.length <= 160 && /^access through\\s*\\S/i.test(text)
763
- && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
764
- && !el.disabled && el.getAttribute('aria-disabled') !== 'true'
765
- && (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
766
- });
767
- return items.filter(el => !items.some(other => other !== el && el.contains(other)))
768
- .slice(0,10).map((el,i) => {
769
- el.setAttribute('data-paper-search-remembered', String(i));
770
- return {i, text:(el.textContent || '').trim()};
756
+ try:
757
+ candidates = page.evaluate("""() => {
758
+ document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
759
+ e.removeAttribute('data-paper-search-remembered'));
760
+ const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
761
+ const native = el.matches('a[href],button,[role="button"]');
762
+ if (!native && el.closest('a,button,[role="button"]')) return false;
763
+ const text = (el.textContent || '').trim();
764
+ return text.length <= 160 && /^access through\\s*\\S/i.test(text)
765
+ && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
766
+ && !el.disabled && el.getAttribute('aria-disabled') !== 'true'
767
+ && (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
771
768
  });
772
- }""")
769
+ return items.filter(el => !items.some(other => other !== el && el.contains(other)))
770
+ .slice(0,10).map((el,i) => {
771
+ el.setAttribute('data-paper-search-remembered', String(i));
772
+ return {i, text:(el.textContent || '').trim()};
773
+ });
774
+ }""")
775
+ except Exception as exc:
776
+ if not _is_navigation_cut(exc):
777
+ raise
778
+ # The page navigated while it was read, e.g. the user chose
779
+ # a school (Karger's wayfinder): looked at again next pass.
780
+ self._event(result, "login_navigation_interrupted", "institution-entry")
781
+ return False
773
782
  if isinstance(candidates, list):
774
783
  for candidate in candidates:
775
784
  label = re.sub(r"^\s*access through\s*", "", candidate["text"], flags=re.I)
@@ -35,6 +35,7 @@ _LOGIN_FAILURE_CODES = (
35
35
  _FAILURE_KINDS = {
36
36
  "publisher_content_error": ("publisher_content_error", "review_publisher_error"),
37
37
  "unsupported_platform": ("unsupported_platform", "review_publisher_error"),
38
+ "article_not_yet_published": ("article_not_yet_published", "review_publisher_error"),
38
39
  "browser_unresponsive": ("browser_unresponsive", "review_browser"),
39
40
  "browser_operation_timeout": ("browser_operation_timeout", "review_browser"),
40
41
  "publisher_access_blocked": ("access_blocked", "review_access"),
@@ -348,7 +349,8 @@ def _try_builtin_institutional(
348
349
  # survives in source_failures. Neither is hidden by a later plain miss.
349
350
  denial = next((f for f in failures if f.get("reason_code") ==
350
351
  "institution_pdf_entitlement_missing"), None)
351
- primary = next((f for code in ("source_exception", "unsupported_platform", "generic_institution_entry_missing",
352
+ primary = next((f for code in ("source_exception", "unsupported_platform", "article_not_yet_published",
353
+ "generic_institution_entry_missing",
352
354
  "publisher_content_error", "access_blocked", *_LOGIN_FAILURE_CODES,
353
355
  "download_timeout")
354
356
  for f in failures if f["error_type"] == code), denial or failures[-1])
@@ -556,7 +558,8 @@ def _try_browser_batch_download(
556
558
  # page is unreachable, so do not wait on it a second time.
557
559
  result.supplements = [{"status": "skipped", "reason": "challenge_timeout",
558
560
  "url": "", "label": ""}]
559
- elif result.state in ("unsupported_platform", "publisher_access_blocked", "publisher_unreachable",
561
+ elif result.state in ("unsupported_platform", "article_not_yet_published",
562
+ "publisher_access_blocked", "publisher_unreachable",
560
563
  "login_page_closed", "user_skipped", "batch_stopped",
561
564
  "user_marked_no_entitlement"):
562
565
  # Nothing more to fetch there now.
@@ -146,6 +146,22 @@ def _page_evidence(response: Any) -> dict[str, Any]:
146
146
  return evidence
147
147
 
148
148
 
149
+ def _is_verification_page(response: Any) -> bool:
150
+ """A firewall's human verification page instead of the file (Figshare's AWS WAF,
151
+ Cloudflare): the site stopped a scripted request, the file may well exist."""
152
+ headers = getattr(response, "headers", None) or {}
153
+ return ("text/html" in str(headers.get("content-type") or "").lower()
154
+ and "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated")))
155
+
156
+
157
+ class _StillVerifying(Exception):
158
+ """The browser, too, did not get the file past a site's verification page."""
159
+
160
+ def __init__(self, evidence: dict[str, Any]):
161
+ super().__init__("verification_page")
162
+ self.evidence = evidence
163
+
164
+
149
165
  def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi: str, *,
150
166
  clock=time.monotonic, sleep=time.sleep,
151
167
  manifest_dir: Path | None = None,
@@ -186,11 +202,23 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
186
202
  response = None
187
203
  response = _get(request, link.url, entry, sleep)
188
204
  _check_interrupted()
189
- if response.status == 403 and download is not None:
205
+ # A firewall's verification page goes to the browser as a 403 does: it
206
+ # opens the link as a reader would and runs the page's own check
207
+ # (Figshare's AWS WAF answered every scripted request, 2026-11-08).
208
+ challenged = download is not None and _is_verification_page(response)
209
+ if (response.status == 403 and download is not None) or challenged:
210
+ evidence = _page_evidence(response) if challenged else {}
190
211
  if callable(getattr(response, "dispose", None)):
191
212
  response.dispose()
192
213
  response = None
193
- response = _Downloaded(*download(link.url))
214
+ try:
215
+ response = _Downloaded(*download(link.url))
216
+ except (BrowserUnresponsive, UserMarkedNoEntitlement):
217
+ raise
218
+ except Exception:
219
+ if not challenged:
220
+ raise
221
+ raise _StillVerifying(evidence)
194
222
  entry["via"] = "browser_download"
195
223
  _check_interrupted()
196
224
  content_type = str(response.headers.get("content-type", "") or "")
@@ -203,10 +231,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
203
231
  # A login wall or landing page instead of the file: which one, for the record.
204
232
  # A firewall's human verification page is told apart (Figshare's AWS WAF,
205
233
  # 2026-11-08): the site stopped the request, the file may well exist.
206
- evidence = _page_evidence(response)
207
- headers = evidence.get("page_headers") or {}
208
- challenged = "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated"))
209
- entry.update(status="failed", reason="verification_page" if challenged else "html_page", **evidence)
234
+ entry.update(status="failed", reason="verification_page" if _is_verification_page(response)
235
+ else "html_page", **_page_evidence(response))
210
236
  else:
211
237
  name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
212
238
  link.label, content_type)
@@ -245,6 +271,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
245
271
  temporary.unlink(missing_ok=True)
246
272
  except SupplementTooLarge as exc:
247
273
  entry.update(status="skipped", reason="too_large", size=exc.size)
274
+ except _StillVerifying as exc:
275
+ entry.update(status="failed", reason="verification_page", via="browser_download", **exc.evidence)
248
276
  except (BrowserUnresponsive, UserMarkedNoEntitlement) as exc:
249
277
  stopped_reason = ("batch_stopped" if isinstance(exc, UserStoppedBatch) else
250
278
  "user_skipped" if isinstance(exc, UserSkippedArticle) else
@@ -219,6 +219,21 @@ class Api:
219
219
  except Exception as exc:
220
220
  return f"记录失败:{type(exc).__name__}"
221
221
 
222
+ def open_article(self, doi: str) -> str:
223
+ """The article's page (doi.org) in the user's own browser, to fetch what the
224
+ batch could not; only a DOI is opened, never another address."""
225
+ doi = str(doi or "").strip()
226
+ if not progress_view.DOI.fullmatch(doi):
227
+ return "打开失败:不是有效的 DOI"
228
+ import webbrowser
229
+ from urllib.parse import quote
230
+
231
+ try:
232
+ opened = webbrowser.open("https://doi.org/" + quote(doi, safe="/:;()._-"))
233
+ except Exception as exc:
234
+ return f"打开失败:{type(exc).__name__}"
235
+ return "已在浏览器打开这篇文章" if opened else "打开失败:没有找到默认浏览器"
236
+
222
237
  def open_folder(self) -> bool:
223
238
  return progress_view.open_folder(str((read_state() or {}).get("output_dir") or ""))
224
239
 
@@ -277,6 +292,13 @@ class Api:
277
292
  return str(selected[0]) if selected else None
278
293
 
279
294
  # --- the window -------------------------------------------------------
295
+ def _button_held(self) -> bool:
296
+ if sys.platform == "darwin" and self._native_geometry:
297
+ return _mac_button_held()
298
+ if sys.platform == "win32":
299
+ return _windows_button_held()
300
+ return True
301
+
280
302
  def _drag_point(self, x: float, y: float) -> tuple[float, float]:
281
303
  if sys.platform == "darwin" and self._native_geometry:
282
304
  return _mac_pointer()
@@ -322,6 +344,10 @@ class Api:
322
344
  if not self._dragging or self._drag_origin is None:
323
345
  return
324
346
  sx, sy, x, y = self._drag_origin
347
+ if not self._button_held():
348
+ # The page reports the release late, and the pointer may have
349
+ # moved on since: the window stays where it was let go.
350
+ return
325
351
  # WebView coordinates can rebase across monitors. Native pointer
326
352
  # deltas stay global; on Windows they are physical until the move.
327
353
  screen_x, screen_y = self._drag_point(screen_x, screen_y)
@@ -493,6 +519,22 @@ def _mac_pointer() -> tuple[float, float]:
493
519
  return _cocoa_call(read)
494
520
 
495
521
 
522
+ def _mac_button_held() -> bool:
523
+ import AppKit
524
+
525
+ return bool(_cocoa_call(lambda: AppKit.NSEvent.pressedMouseButtons() & 1))
526
+
527
+
528
+ def _windows_button_held() -> bool:
529
+ import ctypes
530
+
531
+ user32 = ctypes.windll.user32
532
+ # The physical button state: the primary one is the right button when the
533
+ # user swapped them (SM_SWAPBUTTON).
534
+ button = 0x02 if user32.GetSystemMetrics(23) else 0x01
535
+ return bool(user32.GetAsyncKeyState(button) & 0x8000)
536
+
537
+
496
538
  def _windows_pointer() -> tuple[float, float]:
497
539
  import ctypes
498
540
  from ctypes import wintypes
@@ -582,16 +624,29 @@ def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
582
624
  return [s for _, s in sorted(areas, key=lambda item: not item[0])]
583
625
 
584
626
 
627
+ def _cocoa_rect(frame: Rect) -> Any:
628
+ """``frame`` (top-left coordinates from the primary screen's top) as a Cocoa rect."""
629
+ import AppKit
630
+
631
+ top = AppKit.NSScreen.screens()[0].frame().size.height
632
+ return AppKit.NSMakeRect(frame.x, top - frame.y - frame.height, frame.width, frame.height)
633
+
634
+
635
+ def _moved_origin(ns_window: Any) -> tuple[float, float]:
636
+ """pywebview's moved-event origin, also for a window not yet on any screen: it read
637
+ that window's screen, found none, and the capsule remembered on a second display
638
+ never opened (2026-11-07). The primary screen stands in."""
639
+ import AppKit
640
+
641
+ frame = ns_window.frame()
642
+ screen = (ns_window.screen() or AppKit.NSScreen.screens()[0]).frame()
643
+ return frame.origin.x, screen.size.height - frame.size.height - frame.origin.y
644
+
645
+
585
646
  def _set_window_frame(window: Any, frame: Rect) -> None:
586
647
  """Move and resize in one native operation, without activating the window."""
587
648
  if sys.platform == "darwin":
588
- import AppKit
589
-
590
- def apply():
591
- top = AppKit.NSScreen.screens()[0].frame().size.height
592
- window.native.setFrame_display_(AppKit.NSMakeRect(
593
- frame.x, top - frame.y - frame.height, frame.width, frame.height), True)
594
- _cocoa_call(apply)
649
+ _cocoa_call(lambda: window.native.setFrame_display_(_cocoa_rect(frame), True))
595
650
  elif sys.platform == "win32":
596
651
  window._capsule_set_frame(frame)
597
652
  else:
@@ -628,7 +683,14 @@ def _round_windows_corners(window: Any) -> None:
628
683
  pass
629
684
 
630
685
 
631
- def _classic() -> None:
686
+ def _classic(separate: bool = False) -> None:
687
+ """The classic window. ``separate``: in a process of its own, where pywebview has
688
+ already set up Cocoa in this one; Tk's own setup then crashed (2026-11-07)."""
689
+ if separate:
690
+ import subprocess
691
+
692
+ subprocess.run([sys.executable, "-m", "paper_search_carsi.progress_bar"], check=False)
693
+ return
632
694
  from .progress_bar import main as classic_window
633
695
 
634
696
  classic_window()
@@ -650,11 +712,24 @@ def _prepare_nonactivating_start(window: Any) -> None:
650
712
  return self.pywebview_window is window
651
713
 
652
714
  objc.classAddMethods(cocoa.BrowserView.WebKitHost, [acceptsFirstMouse_])
715
+
716
+ def windowDidMove_(self, notification):
717
+ i = cocoa.BrowserView.get_instance('window', notification.object())
718
+ if i:
719
+ i.pywebview_window.events.moved.set(*_moved_origin(i.window))
720
+
721
+ objc.classAddMethods(cocoa.BrowserView.WindowDelegate, [windowDidMove_])
653
722
  original = cocoa.BrowserView.first_show
654
723
 
655
724
  def first_show(view):
656
725
  if view.pywebview_window is not window:
657
726
  return original(view)
727
+ home = getattr(window, "_capsule_home", None)
728
+ if home is not None:
729
+ # The remembered place, from the primary screen's top like every
730
+ # other capsule move: pywebview's own x/y count from the screen
731
+ # with the active window, another display when one is in use.
732
+ view.window.setFrame_display_(_cocoa_rect(home), False)
658
733
  if not view.hidden:
659
734
  view.window.orderFrontRegardless()
660
735
  view.shown.set()
@@ -754,6 +829,8 @@ def main() -> None:
754
829
  size = (round(placement.home.width), round(placement.home.height))
755
830
  api = Api(placement, Notifier(), progress_view.AutoClose.from_env())
756
831
  dark = progress_view.dark_mode()
832
+ if sys.platform == "darwin":
833
+ x = y = None # placed at placement.home on its first show (_prepare_nonactivating_start)
757
834
  window = webview.create_window(
758
835
  "PaperSearch", html=page, js_api=api, width=size[0], height=size[1], x=x, y=y,
759
836
  min_size=MIN_SIZE, resizable=False, frameless=True, easy_drag=False, on_top=True, focus=True,
@@ -761,6 +838,7 @@ def main() -> None:
761
838
  background_color="#202124" if dark else "#FFFFFF",
762
839
  )
763
840
  api._window = window
841
+ window._capsule_home = placement.home if sys.platform == "darwin" else None
764
842
  if sys.platform == "darwin":
765
843
  from .progress_macos import install_notification_handler
766
844
 
@@ -793,7 +871,7 @@ def main() -> None:
793
871
 
794
872
  close()
795
873
  progress_view.release_window_lock()
796
- _classic()
874
+ _classic(separate=sys.platform == "darwin")
797
875
  return
798
876
  progress_view.release_window_lock()
799
877
  if sys.platform == "darwin":
@@ -8,11 +8,13 @@ from __future__ import annotations
8
8
  import atexit
9
9
  import json
10
10
  import logging
11
+ import os
11
12
  from pathlib import Path
12
13
  import plistlib
13
14
  import struct
14
15
  import subprocess
15
16
  import threading
17
+ import zlib
16
18
  from typing import Any, Callable
17
19
 
18
20
  logger = logging.getLogger(__name__)
@@ -22,13 +24,29 @@ _callback: Callable[[str, str], Any] | None = None
22
24
  _bridge_lock = threading.RLock()
23
25
 
24
26
 
25
- def _write_if_changed(path: Path, content: bytes, mode: int = 0o644) -> None:
27
+ LSREGISTER = ("/System/Library/Frameworks/CoreServices.framework/Frameworks/"
28
+ "LaunchServices.framework/Support/lsregister")
29
+
30
+
31
+ def _write_if_changed(path: Path, content: bytes, mode: int = 0o644) -> bool:
32
+ """Write ``content`` unless the file already holds it; True when written."""
26
33
  if path.is_file() and path.read_bytes() == content:
27
- return
34
+ return False
28
35
  temporary = path.with_name(path.name + ".tmp")
29
36
  temporary.write_bytes(content)
30
37
  temporary.chmod(mode)
31
38
  temporary.replace(path)
39
+ return True
40
+
41
+
42
+ def _register(app: Path) -> None:
43
+ """Have Launch Services read the bundle again, its icon included; best effort."""
44
+ try:
45
+ os.utime(app)
46
+ subprocess.run([LSREGISTER, "-f", str(app)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
47
+ timeout=10, check=False)
48
+ except (OSError, subprocess.SubprocessError):
49
+ pass
32
50
 
33
51
 
34
52
  def prepare_app(app_root: Path | None = None) -> Path:
@@ -41,21 +59,28 @@ def prepare_app(app_root: Path | None = None) -> Path:
41
59
  macos, resources = app / "Contents/MacOS", app / "Contents/Resources"
42
60
  macos.mkdir(parents=True, exist_ok=True)
43
61
  resources.mkdir(parents=True, exist_ok=True)
44
- _write_if_changed(app / "Contents/Info.plist", plistlib.dumps({
45
- "CFBundleIdentifier": BUNDLE_ID,
46
- "CFBundleName": "PaperSearch", "CFBundleDisplayName": "PaperSearch",
47
- "CFBundleExecutable": "PaperSearch", "CFBundlePackageType": "APPL",
48
- "CFBundleInfoDictionaryVersion": "6.0", "CFBundleVersion": "1",
49
- "CFBundleIconFile": "PaperSearch.icns", "LSUIElement": True,
50
- }))
51
62
  chunks = []
52
63
  for size, kind in ((32, b"icp5"), (64, b"icp6"), (512, b"ic09")):
53
64
  image = (assets / f"icon-{size}.png").read_bytes()
54
65
  chunks.append(kind + struct.pack(">I", len(image) + 8) + image)
55
66
  body = b"".join(chunks)
56
- _write_if_changed(resources / "PaperSearch.icns", b"icns" + struct.pack(">I", len(body) + 8) + body)
67
+ icns = b"icns" + struct.pack(">I", len(body) + 8) + body
68
+ # macOS keeps a bundle's icon from its cache while the bundle seems unchanged:
69
+ # notifications still showed the old icon after the new one was written into
70
+ # the bundle (2026-11-08). The version follows the icon, and a changed bundle
71
+ # is registered again.
72
+ changed = _write_if_changed(app / "Contents/Info.plist", plistlib.dumps({
73
+ "CFBundleIdentifier": BUNDLE_ID,
74
+ "CFBundleName": "PaperSearch", "CFBundleDisplayName": "PaperSearch",
75
+ "CFBundleExecutable": "PaperSearch", "CFBundlePackageType": "APPL",
76
+ "CFBundleInfoDictionaryVersion": "6.0", "CFBundleVersion": str(zlib.crc32(icns)),
77
+ "CFBundleIconFile": "PaperSearch.icns", "LSUIElement": True,
78
+ }))
79
+ changed = _write_if_changed(resources / "PaperSearch.icns", icns) or changed
57
80
  executable = macos / "PaperSearch"
58
81
  _write_if_changed(executable, (assets / "papersearch-notifier").read_bytes(), 0o755)
82
+ if changed:
83
+ _register(app)
59
84
  return executable
60
85
 
61
86
 
@@ -417,7 +417,12 @@ def _finish_download(outcome: dict[str, Any], current: str, batch: BatchContext
417
417
  stage = "supplements_checked"
418
418
  phase = f"补充材料已保存 {len(files)} 个" if files else "已检查,页面未列出补充材料"
419
419
  report_stage(stage, current=current)
420
- advance(succeeded, current=current, phase=phase)
420
+ # A saved PDF is the caller's to count once it has checked the article's
421
+ # identity; its totals come with the next item. Counted here, an article
422
+ # left for review showed as a success, then a failure (RSC, Windows 2026-11-08).
423
+ pending = (stage == "saved_pending_verification" and batch is not None
424
+ and batch.succeeded is not None and batch.index < batch.total)
425
+ advance(succeeded, current=current, phase=phase, pending=pending)
421
426
  if batch is not None and batch.index < batch.total:
422
427
  with _LOCK:
423
428
  if _STATE:
@@ -541,14 +546,16 @@ def update(**kw: Any) -> None:
541
546
  _write_state()
542
547
 
543
548
 
544
- def advance(ok: bool, current: str = "", phase: str = "") -> None:
545
- """Record one finished item (the hot path for per-paper lanes)."""
549
+ def advance(ok: bool, current: str = "", phase: str = "", *, pending: bool = False) -> None:
550
+ """Record one finished item (the hot path for per-paper lanes); ``pending``:
551
+ finished, but whether it succeeded is the caller's to count."""
546
552
  with _LOCK:
547
553
  if not _STATE:
548
554
  return
549
555
  _STATE["done"] = int(_STATE.get("done", 0)) + 1
550
- _STATE["success"] = int(_STATE.get("success", 0)) + (1 if ok else 0)
551
- _STATE["failed"] = int(_STATE.get("failed", 0)) + (0 if ok else 1)
556
+ if not pending:
557
+ _STATE["success"] = int(_STATE.get("success", 0)) + (1 if ok else 0)
558
+ _STATE["failed"] = int(_STATE.get("failed", 0)) + (0 if ok else 1)
552
559
  if current:
553
560
  _STATE["current"] = current
554
561
  if phase:
@@ -9,6 +9,7 @@ so tests cover every state without opening a window.
9
9
  from __future__ import annotations
10
10
 
11
11
  import os
12
+ import re
12
13
  import sys
13
14
  from datetime import datetime
14
15
  from typing import Any
@@ -149,6 +150,9 @@ def _time(value: Any) -> float | None:
149
150
  return None
150
151
 
151
152
 
153
+ # A DOI the article's page can be opened from (doi.org), nothing else.
154
+ DOI = re.compile(r"10\.\d{4,9}/\S{1,280}")
155
+
152
156
  def _journals(failures: list[dict[str, Any]]) -> str:
153
157
  """The journals of a reason row, most papers first: "Spine 8 · JBJS 4 等"."""
154
158
  counts: dict[str, int] = {}
@@ -174,7 +178,9 @@ def _reason_groups(failures: list[dict[str, Any]], open_up_to: int) -> list[dict
174
178
  for (cls, reason), items in rows:
175
179
  papers = [{"title": str(item.get("title") or item.get("doi") or "未知论文"),
176
180
  "where": " · ".join(str(v) for v in (
177
- item.get("journal"), item.get("reason") if cls == "other" else "", item.get("note")) if v)}
181
+ item.get("journal"), item.get("reason") if cls == "other" else "", item.get("note")) if v),
182
+ # The page opens in the user's browser from the list (user, 2026-11-08).
183
+ "doi": str(item.get("doi") or "").strip() if DOI.fullmatch(str(item.get("doi") or "").strip()) else ""}
178
184
  for item in items[:MAX_LISTED_PAPERS]]
179
185
  groups.append({"cls": cls, "reason": reason, "count": len(items), "where": _journals(items),
180
186
  "papers": papers, "more": len(items) - len(papers),
@@ -1 +1 @@
1
- {"version":3,"file":"CarsiAttempt.d.ts","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AA+HA,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,SAAgC,GAAG,MAAM,CAE1G;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IACnF,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAIA"}
1
+ {"version":3,"file":"CarsiAttempt.d.ts","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AAkIA,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,SAAgC,GAAG,MAAM,CAE1G;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IACnF,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAIA"}
@@ -30,6 +30,7 @@ const MESSAGES = {
30
30
  browser_operation_timeout: "页面处理超过设定的等待时间,已停止这一篇的浏览器步骤;这不代表没有全文权限。可在下载窗口设置中调整其他页面等待时间后重试。",
31
31
  browser_unresponsive: "下载浏览器长时间没有响应,已结束这一篇,批量中的其他文章照常继续;可稍后单独重试这一篇。",
32
32
  unsupported_platform: "这篇文章只在出版社的另一个平台(如 ClinicalKey)提供,需单独订阅,PaperSearch 暂不支持在该平台登录和下载;本次未取得 PDF。",
33
+ article_not_yet_published: "这篇论文已录用,但出版社还没有上线全文(页面写明正式发表后才能阅读);本次未取得 PDF,正式发表后再下载。这不代表没有权限。",
33
34
  unsupported_publisher: "这篇文章的 DOI 没有指向 PaperSearch 能登录的出版社网站(DOI 解析失败、直接指向 PDF 文件,或是暂不支持的平台),没有打开浏览器,本次未取得 PDF;这不代表没有权限,可在校园网下到出版社页面自己下载。",
34
35
  generic_institution_entry_missing: "这家出版社还没有专门的规则,按通用规则没有找到机构登录入口;可以把这篇报告给我们补规则,或在校园网下下载。",
35
36
  access_blocked: "出版社网站拦截了当前网络(可能是当前网络被网站防护拦截,也可能是下载过多被暂停);本次未取得 PDF,同一期刊本批后续文章直接跳过。可换网络或稍后再试。",
@@ -75,6 +76,7 @@ const SHORT_REASONS = {
75
76
  browser_operation_timeout: "页面处理超时",
76
77
  browser_unresponsive: "浏览器没有响应",
77
78
  unsupported_platform: "只在其他平台提供",
79
+ article_not_yet_published: "全文尚未发布",
78
80
  unsupported_publisher: "DOI 没指向能登录的网站",
79
81
  generic_institution_entry_missing: "找不到机构登录入口",
80
82
  access_blocked: "网站拦截了当前网络",
@@ -1 +1 @@
1
- {"version":3,"file":"CarsiAttempt.js","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,MAAM,QAAQ,GAA2B;IACvC,cAAc,EACZ,sCAAsC;IACxC,aAAa,EACX,wCAAwC;IAC1C,iBAAiB,EACf,6CAA6C;IAC/C,iBAAiB,EAAE,0BAA0B;IAC7C,0BAA0B,EACxB,uCAAuC;IACzC,uBAAuB,EACrB,iCAAiC;IACnC,eAAe,EACb,yEAAyE;IAC3E,kBAAkB,EAChB,2CAA2C;IAC7C,0BAA0B,EACxB,mFAAmF;IACrF,oBAAoB,EAClB,uCAAuC;IACzC,YAAY,EACV,6BAA6B;IAC/B,aAAa,EACX,+BAA+B;IACjC,cAAc,EACZ,wEAAwE;IAC1E,kCAAkC,EAChC,2DAA2D;IAC7D,0BAA0B,EACxB,+CAA+C;IACjD,OAAO,EACL,2CAA2C;IAC7C,mBAAmB,EACjB,sEAAsE;IACxE,kBAAkB,EAChB,4BAA4B;IAC9B,gBAAgB,EAAE,4BAA4B;IAC9C,gBAAgB,EACd,kCAAkC;IACpC,OAAO,EACL,kCAAkC;IACpC,SAAS,EAAE,QAAQ;IACnB,YAAY,EACV,gDAAgD;IAClD,mBAAmB,EAAE,uBAAuB;IAC5C,SAAS,EAAE,iBAAiB;IAC5B,uBAAuB,EACrB,sDAAsD;IACxD,qBAAqB,EACnB,uDAAu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,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAAE,KAAgC;IAIhF,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC;IAC3E,yFAAyF;IACzF,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,IAAI,OAAO,CAAC,EAAE,CAAC;AAC5G,CAAC"}
@@ -17,7 +17,7 @@ export const CARSI_DOWNLOAD_TIMEOUT_MS = 1_200_000;
17
17
  export const CARSI_CLEANUP_TIMEOUT_MS = 5_000;
18
18
  const CARSI_BACKEND_SOURCE = "carsi";
19
19
  // MCP clientInfo is informational only; keep in step with package.json on release.
20
- const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.11";
20
+ const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.12";
21
21
  const NO_BATCH_SUPPORT = {
22
22
  downloadFields: false,
23
23
  supplementsField: false,
package/dist/cli.js CHANGED
@@ -1200,7 +1200,7 @@ async function main() {
1200
1200
  process.exitCode = error?.exitCode || 1;
1201
1201
  }
1202
1202
  finally {
1203
- update?.stop();
1203
+ await update?.finish();
1204
1204
  }
1205
1205
  }
1206
1206
  function maybePrintSetupHint(parsed) {