papersearch 0.4.10 → 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 (103) hide show
  1. package/LICENSE +1 -1
  2. package/README.en.md +128 -226
  3. package/README.md +128 -226
  4. package/assets/carsi-flow.en.png +0 -0
  5. package/assets/carsi-flow.png +0 -0
  6. package/assets/overview.en.png +0 -0
  7. package/assets/overview.png +0 -0
  8. package/carsi/README.md +1 -1
  9. package/carsi/paper_search_carsi/adapters/ams/__init__.py +12 -0
  10. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +5 -2
  11. package/carsi/paper_search_carsi/adapters/elsevier/sciencedirect.py +18 -1
  12. package/carsi/paper_search_carsi/adapters/iop/__init__.py +19 -4
  13. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +24 -14
  14. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
  15. package/carsi/paper_search_carsi/assets/capsule.html +36 -9
  16. package/carsi/paper_search_carsi/browser/preview.py +16 -3
  17. package/carsi/paper_search_carsi/browser/watchdog.py +68 -4
  18. package/carsi/paper_search_carsi/capsule_placement.py +51 -31
  19. package/carsi/paper_search_carsi/download_diagnostics.py +3 -1
  20. package/carsi/paper_search_carsi/engine/access_rules.py +11 -0
  21. package/carsi/paper_search_carsi/engine/batch.py +21 -3
  22. package/carsi/paper_search_carsi/engine/batch_access.py +3 -0
  23. package/carsi/paper_search_carsi/engine/batch_capture.py +61 -11
  24. package/carsi/paper_search_carsi/engine/batch_common.py +4 -0
  25. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
  26. package/carsi/paper_search_carsi/engine/batch_institution.py +59 -40
  27. package/carsi/paper_search_carsi/engine/batch_login.py +121 -16
  28. package/carsi/paper_search_carsi/engine/bridge.py +5 -2
  29. package/carsi/paper_search_carsi/engine/supplements.py +66 -4
  30. package/carsi/paper_search_carsi/progress_capsule.py +93 -11
  31. package/carsi/paper_search_carsi/progress_macos.py +35 -10
  32. package/carsi/paper_search_carsi/progress_reporter.py +42 -18
  33. package/carsi/paper_search_carsi/progress_view.py +35 -13
  34. package/carsi/paper_search_carsi/server.py +7 -1
  35. package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
  36. package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
  37. package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
  38. package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
  39. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  40. package/dist/capabilities/pdf-discovery/batch.js +45 -10
  41. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  42. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +7 -1
  43. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -1
  44. package/dist/capabilities/pdf-discovery/batchSummary.js +24 -0
  45. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -1
  46. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  47. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +6 -0
  48. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  49. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +3 -0
  50. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  51. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +29 -4
  52. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  53. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +2 -0
  54. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  55. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +2 -0
  56. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  57. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +12 -0
  58. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  59. package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
  61. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
  62. package/dist/cli.js +19 -8
  63. package/dist/cli.js.map +1 -1
  64. package/dist/config/ConfigService.d.ts.map +1 -1
  65. package/dist/config/ConfigService.js +28 -2
  66. package/dist/config/ConfigService.js.map +1 -1
  67. package/dist/config/apiKeySignup.d.ts +13 -0
  68. package/dist/config/apiKeySignup.d.ts.map +1 -0
  69. package/dist/config/apiKeySignup.js +32 -0
  70. package/dist/config/apiKeySignup.js.map +1 -0
  71. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  72. package/dist/infrastructure/runlog/failureClass.js +6 -0
  73. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  74. package/dist/management/capability-profile/index.d.ts +7 -0
  75. package/dist/management/capability-profile/index.d.ts.map +1 -1
  76. package/dist/management/capability-profile/index.js +7 -0
  77. package/dist/management/capability-profile/index.js.map +1 -1
  78. package/dist/management/carsi/installer.js +5 -5
  79. package/dist/management/carsi/installer.js.map +1 -1
  80. package/dist/management/diagnostics/index.d.ts.map +1 -1
  81. package/dist/management/diagnostics/index.js +4 -1
  82. package/dist/management/diagnostics/index.js.map +1 -1
  83. package/dist/management/failures/exportReport.js +3 -3
  84. package/dist/management/reports/index.d.ts.map +1 -1
  85. package/dist/management/reports/index.js +6 -1
  86. package/dist/management/reports/index.js.map +1 -1
  87. package/dist/management/updates/index.d.ts +6 -1
  88. package/dist/management/updates/index.d.ts.map +1 -1
  89. package/dist/management/updates/index.js +18 -11
  90. package/dist/management/updates/index.js.map +1 -1
  91. package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
  92. package/dist/platforms/SemanticScholarSearcher.js +2 -1
  93. package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
  94. package/package.json +2 -3
  95. package/skills/paper-search/SKILL.md +8 -14
  96. package/skills/paper-search/references/browser-download.md +7 -6
  97. package/skills/paper-search/references/capability-routing.md +3 -3
  98. package/skills/paper-search/references/carsi-setup.md +1 -1
  99. package/skills/paper-search/references/cli-contract.md +2 -2
  100. package/skills/paper-search/references/management-layer.md +1 -1
  101. package/skills/paper-search/references/publisher-support.md +6 -4
  102. package/skills/paper-search/references/troubleshooting.md +1 -2
  103. package/carsi/NOTICE +0 -5
@@ -117,6 +117,51 @@ def _get(request: Any, url: str, entry: dict[str, Any], sleep) -> Any:
117
117
  return request.get(url, timeout=REQUEST_TIMEOUT_MS)
118
118
 
119
119
 
120
+ # Response headers that name what answered instead of the file (a CDN's or a
121
+ # firewall's challenge, a login service), kept for the record.
122
+ _PAGE_HEADERS = ("server", "x-amzn-waf-action", "cf-mitigated", "location")
123
+
124
+
125
+ def _page_evidence(response: Any) -> dict[str, Any]:
126
+ """What a page received instead of a file was: its status, final address
127
+ (no query), title and telling headers. Figshare's download address answered a
128
+ page and nothing said which (AIP, Royal Society, AACR; 2026-11-08)."""
129
+ evidence: dict[str, Any] = {"http_status": getattr(response, "status", None)}
130
+ url = str(getattr(response, "url", "") or "")
131
+ if url:
132
+ evidence["final_url"] = url.split("?", 1)[0][:300]
133
+ headers = getattr(response, "headers", None) or {}
134
+ named = {key: str(headers.get(key))[:120] for key in _PAGE_HEADERS if headers.get(key)}
135
+ if named:
136
+ evidence["page_headers"] = named
137
+ try:
138
+ text = response.body()[:65536].decode("utf-8", "replace")
139
+ except Exception:
140
+ return evidence
141
+ title = re.search(r"<title[^>]*>(.*?)</title>", text, re.I | re.S)
142
+ if title:
143
+ from html import unescape
144
+
145
+ evidence["page_title"] = " ".join(unescape(title.group(1)).split())[:160]
146
+ return evidence
147
+
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
+
120
165
  def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi: str, *,
121
166
  clock=time.monotonic, sleep=time.sleep,
122
167
  manifest_dir: Path | None = None,
@@ -157,11 +202,23 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
157
202
  response = None
158
203
  response = _get(request, link.url, entry, sleep)
159
204
  _check_interrupted()
160
- 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 {}
161
211
  if callable(getattr(response, "dispose", None)):
162
212
  response.dispose()
163
213
  response = None
164
- 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)
165
222
  entry["via"] = "browser_download"
166
223
  _check_interrupted()
167
224
  content_type = str(response.headers.get("content-type", "") or "")
@@ -171,8 +228,11 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
171
228
  elif length > MAX_FILE_BYTES:
172
229
  entry.update(status="skipped", reason="too_large", size=length)
173
230
  elif "text/html" in content_type.lower():
174
- # A login wall or landing page instead of the file.
175
- entry.update(status="failed", reason="html_page")
231
+ # A login wall or landing page instead of the file: which one, for the record.
232
+ # A firewall's human verification page is told apart (Figshare's AWS WAF,
233
+ # 2026-11-08): the site stopped the request, the file may well exist.
234
+ entry.update(status="failed", reason="verification_page" if _is_verification_page(response)
235
+ else "html_page", **_page_evidence(response))
176
236
  else:
177
237
  name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
178
238
  link.label, content_type)
@@ -211,6 +271,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
211
271
  temporary.unlink(missing_ok=True)
212
272
  except SupplementTooLarge as exc:
213
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)
214
276
  except (BrowserUnresponsive, UserMarkedNoEntitlement) as exc:
215
277
  stopped_reason = ("batch_stopped" if isinstance(exc, UserStoppedBatch) else
216
278
  "user_skipped" if isinstance(exc, UserSkippedArticle) else
@@ -177,11 +177,15 @@ class Api:
177
177
  from .entitlements import SHOW_BROWSER, request_action
178
178
 
179
179
  if action == SHOW_BROWSER:
180
+ # Asked for from a reminder, or from the paper on the card at any
181
+ # time while it has a browser (user request, 2026-11-08).
180
182
  state = read_state() or {}
181
- if (state.get("status") != "running" or not state.get("attention")
183
+ if (state.get("status") != "running"
182
184
  or str(state.get("current") or "") != current
183
185
  or str(state.get("run_id") or "") != run_id):
184
- return "当前没有等待处理的下载浏览器"
186
+ return "当前没有正在下载的浏览器"
187
+ if not state.get("attention") and state.get("channel"):
188
+ return "这一篇在查开放来源,没有打开浏览器"
185
189
  if sys.platform == "darwin":
186
190
  from .browser.foreground import activate_mac
187
191
 
@@ -215,6 +219,21 @@ class Api:
215
219
  except Exception as exc:
216
220
  return f"记录失败:{type(exc).__name__}"
217
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
+
218
237
  def open_folder(self) -> bool:
219
238
  return progress_view.open_folder(str((read_state() or {}).get("output_dir") or ""))
220
239
 
@@ -273,6 +292,13 @@ class Api:
273
292
  return str(selected[0]) if selected else None
274
293
 
275
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
+
276
302
  def _drag_point(self, x: float, y: float) -> tuple[float, float]:
277
303
  if sys.platform == "darwin" and self._native_geometry:
278
304
  return _mac_pointer()
@@ -318,6 +344,10 @@ class Api:
318
344
  if not self._dragging or self._drag_origin is None:
319
345
  return
320
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
321
351
  # WebView coordinates can rebase across monitors. Native pointer
322
352
  # deltas stay global; on Windows they are physical until the move.
323
353
  screen_x, screen_y = self._drag_point(screen_x, screen_y)
@@ -489,6 +519,22 @@ def _mac_pointer() -> tuple[float, float]:
489
519
  return _cocoa_call(read)
490
520
 
491
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
+
492
538
  def _windows_pointer() -> tuple[float, float]:
493
539
  import ctypes
494
540
  from ctypes import wintypes
@@ -578,16 +624,29 @@ def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
578
624
  return [s for _, s in sorted(areas, key=lambda item: not item[0])]
579
625
 
580
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
+
581
646
  def _set_window_frame(window: Any, frame: Rect) -> None:
582
647
  """Move and resize in one native operation, without activating the window."""
583
648
  if sys.platform == "darwin":
584
- import AppKit
585
-
586
- def apply():
587
- top = AppKit.NSScreen.screens()[0].frame().size.height
588
- window.native.setFrame_display_(AppKit.NSMakeRect(
589
- frame.x, top - frame.y - frame.height, frame.width, frame.height), True)
590
- _cocoa_call(apply)
649
+ _cocoa_call(lambda: window.native.setFrame_display_(_cocoa_rect(frame), True))
591
650
  elif sys.platform == "win32":
592
651
  window._capsule_set_frame(frame)
593
652
  else:
@@ -624,7 +683,14 @@ def _round_windows_corners(window: Any) -> None:
624
683
  pass
625
684
 
626
685
 
627
- 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
628
694
  from .progress_bar import main as classic_window
629
695
 
630
696
  classic_window()
@@ -646,11 +712,24 @@ def _prepare_nonactivating_start(window: Any) -> None:
646
712
  return self.pywebview_window is window
647
713
 
648
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_])
649
722
  original = cocoa.BrowserView.first_show
650
723
 
651
724
  def first_show(view):
652
725
  if view.pywebview_window is not window:
653
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)
654
733
  if not view.hidden:
655
734
  view.window.orderFrontRegardless()
656
735
  view.shown.set()
@@ -750,6 +829,8 @@ def main() -> None:
750
829
  size = (round(placement.home.width), round(placement.home.height))
751
830
  api = Api(placement, Notifier(), progress_view.AutoClose.from_env())
752
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)
753
834
  window = webview.create_window(
754
835
  "PaperSearch", html=page, js_api=api, width=size[0], height=size[1], x=x, y=y,
755
836
  min_size=MIN_SIZE, resizable=False, frameless=True, easy_drag=False, on_top=True, focus=True,
@@ -757,6 +838,7 @@ def main() -> None:
757
838
  background_color="#202124" if dark else "#FFFFFF",
758
839
  )
759
840
  api._window = window
841
+ window._capsule_home = placement.home if sys.platform == "darwin" else None
760
842
  if sys.platform == "darwin":
761
843
  from .progress_macos import install_notification_handler
762
844
 
@@ -789,7 +871,7 @@ def main() -> None:
789
871
 
790
872
  close()
791
873
  progress_view.release_window_lock()
792
- _classic()
874
+ _classic(separate=sys.platform == "darwin")
793
875
  return
794
876
  progress_view.release_window_lock()
795
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
 
@@ -250,12 +250,16 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
250
250
 
251
251
 
252
252
  def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int, *,
253
- current: str = "", finished: bool = False, results: Any = None) -> bool:
253
+ current: str = "", finished: bool = False, results: Any = None,
254
+ phase: str = "", channel: str = "") -> bool:
254
255
  """Record batch totals for items finished without the backend, or the batch end.
255
256
 
256
257
  ``results`` (the batch end only) is the caller's summary of every item,
257
258
  for the finished window: see ``_batch_results``. It updates an existing
258
- report and never opens a window for a batch the backend did not show."""
259
+ report and never opens a window for a batch the backend did not show.
260
+ ``phase`` replaces the waiting line and ``channel`` names where the caller
261
+ fetches from (its open-access stretch, before any publisher); both are
262
+ short single lines and are dropped at the batch end."""
259
263
  ctx = BatchContext.from_args(batch_id, max(1, min(done, total)), total, done, succeeded, failed)
260
264
  if ctx is None or done > total:
261
265
  return False
@@ -263,11 +267,13 @@ def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int
263
267
  previous = _batch_state(ctx.batch_id)
264
268
  if finished and previous is None and (done == 0 or summary is not None):
265
269
  return False
270
+ phase, channel = _short_line(phase), _short_line(channel)
266
271
  _adopt_batch(ctx.batch_id, total, (done, succeeded, failed),
267
272
  **({"current": current} if current else {}),
268
273
  stage="saved_pending_verification" if finished else "starting",
274
+ channel="" if finished else channel,
269
275
  phase=(f"批量下载结束:成功 {succeeded},失败 {failed}" if finished
270
- else f"已完成 {done}/{total} 篇,等待下一篇"))
276
+ else phase or f"已完成 {done}/{total} 篇,等待下一篇"))
271
277
  with _LOCK:
272
278
  if finished:
273
279
  _STATE.update(status="done", awaiting_next=False,
@@ -288,6 +294,13 @@ def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int
288
294
  return True
289
295
 
290
296
 
297
+ def _short_line(value: Any, limit: int = 80) -> str:
298
+ """A caller's display text as one short line (empty when it is not text)."""
299
+ if not isinstance(value, str):
300
+ return ""
301
+ return " ".join(value.split())[:limit]
302
+
303
+
291
304
  FAILURE_CLASSES = ("no_access", "user_or_external", "unsupported", "unexplained")
292
305
  _RESULT_CONTENTS = ("main", "supplements", "both")
293
306
  _MAX_RESULT_FAILURES = 1000 # the caller's batch limit
@@ -303,7 +316,9 @@ def _batch_results(raw: Any) -> dict[str, Any] | None:
303
316
  ``main`` (main texts saved), ``supplements`` (attachment files saved),
304
317
  ``no_supplements`` (pages that listed none); ``sources`` ([label, count]);
305
318
  ``failures`` ([{cls, reason, title, journal, doi, note}]) with ``cls`` one
306
- of FAILURE_CLASSES and a short ``reason`` text. Anything else is dropped.
319
+ of FAILURE_CLASSES and a short ``reason`` text; ``supplement_failures``, the
320
+ same for papers whose main text was saved but not every supplementary file
321
+ (content "both"). Anything else is dropped.
307
322
  """
308
323
  if not isinstance(raw, dict):
309
324
  return None
@@ -327,16 +342,18 @@ def _batch_results(raw: Any) -> dict[str, Any] | None:
327
342
  if isinstance(s, list) and len(s) == 2 and text(s[0]) and count(s[1])]
328
343
  if isinstance(raw.get("sources"), list) else [],
329
344
  "failures": [],
345
+ "supplement_failures": [],
330
346
  "stopped": raw.get("stopped") is True,
331
347
  }
332
- failures = raw.get("failures")
333
- for item in (failures if isinstance(failures, list) else [])[:_MAX_RESULT_FAILURES]:
334
- if not isinstance(item, dict) or not text(item.get("reason")):
335
- continue
336
- summary["failures"].append({
337
- "cls": item.get("cls") if item.get("cls") in FAILURE_CLASSES else "unexplained",
338
- **{key: text(item.get(key)) for key in ("reason", "title", "journal", "doi", "note")},
339
- })
348
+ for key in ("failures", "supplement_failures"):
349
+ listed = raw.get(key)
350
+ for item in (listed if isinstance(listed, list) else [])[:_MAX_RESULT_FAILURES]:
351
+ if not isinstance(item, dict) or not text(item.get("reason")):
352
+ continue
353
+ summary[key].append({
354
+ "cls": item.get("cls") if item.get("cls") in FAILURE_CLASSES else "unexplained",
355
+ **{field: text(item.get(field)) for field in ("reason", "title", "journal", "doi", "note")},
356
+ })
340
357
  folder = raw.get("folder")
341
358
  if isinstance(folder, str) and 0 < len(folder) <= 4096 and os.path.isabs(folder):
342
359
  summary["folder"] = folder
@@ -366,7 +383,7 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
366
383
  else:
367
384
  done = batch.done if batch.done is not None else (None if _batch_state(batch.batch_id) else batch.index - 1)
368
385
  _adopt_batch(batch.batch_id, batch.total, (done, batch.succeeded, batch.failed),
369
- current=current, stage="starting",
386
+ current=current, stage="starting", channel="",
370
387
  phase=f"第 {batch.index}/{batch.total} 篇:进入机构访问" if batch.total > 1 else "进入机构访问")
371
388
  _notify_stage("starting", current)
372
389
  update(content=content if content in ("main", "supplements", "both") else "main")
@@ -400,7 +417,12 @@ def _finish_download(outcome: dict[str, Any], current: str, batch: BatchContext
400
417
  stage = "supplements_checked"
401
418
  phase = f"补充材料已保存 {len(files)} 个" if files else "已检查,页面未列出补充材料"
402
419
  report_stage(stage, current=current)
403
- 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)
404
426
  if batch is not None and batch.index < batch.total:
405
427
  with _LOCK:
406
428
  if _STATE:
@@ -524,14 +546,16 @@ def update(**kw: Any) -> None:
524
546
  _write_state()
525
547
 
526
548
 
527
- def advance(ok: bool, current: str = "", phase: str = "") -> None:
528
- """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."""
529
552
  with _LOCK:
530
553
  if not _STATE:
531
554
  return
532
555
  _STATE["done"] = int(_STATE.get("done", 0)) + 1
533
- _STATE["success"] = int(_STATE.get("success", 0)) + (1 if ok else 0)
534
- _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)
535
559
  if current:
536
560
  _STATE["current"] = current
537
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] = {}
@@ -159,15 +163,9 @@ def _journals(failures: list[dict[str, Any]]) -> str:
159
163
  return " · ".join(f"{name} {n}" for name, n in ranked[:2]) + (" 等" if len(ranked) > 2 else "")
160
164
 
161
165
 
162
- def summary_view(results: Any) -> dict[str, Any] | None:
163
- """The finished card's lists, from the caller's end-of-batch summary.
164
-
165
- ``groups``: one row per failure reason, most papers first, each with its
166
- papers and whether it starts open; ``saved``: up to two short lines on what
167
- was saved and where it came from (no line wraps in the narrow card)."""
168
- if not isinstance(results, dict):
169
- return None
170
- failures = [f for f in results.get("failures") or [] if isinstance(f, dict)]
166
+ def _reason_groups(failures: list[dict[str, Any]], open_up_to: int) -> list[dict[str, Any]]:
167
+ """One row per failure reason, most papers first, each with its papers and
168
+ whether it starts open (all of them while there are ``open_up_to`` or fewer)."""
171
169
  by_reason: dict[tuple[str, str], list[dict[str, Any]]] = {}
172
170
  for item in failures:
173
171
  by_reason.setdefault((str(item.get("cls")), str(item.get("reason"))), []).append(item)
@@ -180,11 +178,30 @@ def summary_view(results: Any) -> dict[str, Any] | None:
180
178
  for (cls, reason), items in rows:
181
179
  papers = [{"title": str(item.get("title") or item.get("doi") or "未知论文"),
182
180
  "where": " · ".join(str(v) for v in (
183
- 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 ""}
184
184
  for item in items[:MAX_LISTED_PAPERS]]
185
185
  groups.append({"cls": cls, "reason": reason, "count": len(items), "where": _journals(items),
186
186
  "papers": papers, "more": len(items) - len(papers),
187
- "open": len(failures) <= OPEN_FAILURES_UP_TO})
187
+ "open": len(failures) <= open_up_to})
188
+ return groups
189
+
190
+
191
+ def summary_view(results: Any) -> dict[str, Any] | None:
192
+ """The finished card's lists, from the caller's end-of-batch summary.
193
+
194
+ ``groups``: the papers without their main text, by reason (supplements-only
195
+ batches: without their files); ``supplement_groups``: papers whose main text
196
+ was saved but not every supplementary file (content "both"), by reason, all
197
+ closed to keep the card short (user, 2026-11-08); ``saved``: up to two short
198
+ lines on what was saved and where it came from (no line wraps in the narrow card)."""
199
+ if not isinstance(results, dict):
200
+ return None
201
+ failures = [f for f in results.get("failures") or [] if isinstance(f, dict)]
202
+ shortfalls = [f for f in results.get("supplement_failures") or [] if isinstance(f, dict)]
203
+ groups = _reason_groups(failures, OPEN_FAILURES_UP_TO)
204
+ supplement_groups = _reason_groups(shortfalls, 0)
188
205
 
189
206
  content = results.get("content")
190
207
  main, files = _count(results.get("main")), _count(results.get("supplements"))
@@ -198,7 +215,8 @@ def summary_view(results: Any) -> dict[str, Any] | None:
198
215
  sources = [f"{s[0]} {_count(s[1])}" for s in results.get("sources") or []
199
216
  if isinstance(s, list) and len(s) == 2 and _count(s[1])]
200
217
  saved = [" · ".join(first)] + ([" · ".join(sources)] if sources and content != "supplements" else [])
201
- return {"groups": groups, "saved": saved}
218
+ return {"groups": groups, "supplement_groups": supplement_groups, "supplement_missing": len(shortfalls),
219
+ "saved": saved}
202
220
 
203
221
 
204
222
  def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
@@ -237,7 +255,8 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
237
255
  part = CONTENT_LABELS[part_key]
238
256
  else:
239
257
  part = CONTENT_LABELS.get(str(state.get("content") or "main"), CONTENT_LABELS["main"])
240
- publisher = str(state.get("publisher") or "")
258
+ # Before any publisher (the caller's open-access stretch), the channel stands in.
259
+ publisher = str(state.get("publisher") or "") or str(state.get("channel") or "")
241
260
  journal = str(state.get("journal") or "")
242
261
  current = str((attention[-1].get("current") if attention else "") or state.get("current") or "")
243
262
 
@@ -298,6 +317,9 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
298
317
  if not running and state.get("stage") == "supplements_checked" else "",
299
318
  "summary": summary_view(state.get("results")) if mode == "done" else None,
300
319
  "actions": running and bool(current) and not awaiting,
320
+ # This paper has a download browser to show: not between papers, not in
321
+ # the caller's open-access stretch (its channel), which opens none.
322
+ "browser": running and bool(current) and not awaiting and not state.get("channel"),
301
323
  "stop_left": max(0, total - done - 1),
302
324
  "folder": bool(state.get("output_dir")),
303
325
  }
@@ -203,6 +203,8 @@ def carsi_batch_progress(
203
203
  current: str = "",
204
204
  finished: bool = False,
205
205
  results: dict[str, Any] | None = None,
206
+ phase: str = "",
207
+ channel: str = "",
206
208
  ) -> str:
207
209
  """Update the progress window of a serial batch without downloading.
208
210
 
@@ -212,12 +214,16 @@ def carsi_batch_progress(
212
214
  results: with finished=true, the whole batch's outcome for the finished window: content,
213
215
  started (epoch seconds), stopped, main/supplements/no_supplements counts, sources
214
216
  ([label, count]) and failures ([{cls, reason, title, journal, doi, note}]).
217
+
218
+ phase: the status line while the batch waits for its next item, e.g. "开放获取:已查 15/40 篇".
219
+ channel: where the caller is fetching from, shown in place of a publisher, e.g. "开放获取".
215
220
  """
216
221
  from . import progress_reporter
217
222
 
218
223
  label = current if _DOI_RE.fullmatch(current or "") else ""
219
224
  updated = progress_reporter.sync_batch(batch_id, total, done, succeeded, failed,
220
- current=label, finished=finished, results=results)
225
+ current=label, finished=finished, results=results,
226
+ phase=phase, channel=channel)
221
227
  return json.dumps({"updated": updated})
222
228
 
223
229
 
@@ -1 +1 @@
1
- {"version":3,"file":"JournalMetricsService.d.ts","sourceRoot":"","sources":["../../../src/capabilities/journal-metrics/JournalMetricsService.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AA0IhF,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAuC3G"}
1
+ {"version":3,"file":"JournalMetricsService.d.ts","sourceRoot":"","sources":["../../../src/capabilities/journal-metrics/JournalMetricsService.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AA0IhF,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAuC3G"}
@@ -1,10 +1,11 @@
1
1
  import axios from 'axios';
2
+ import { apiKeyHint } from '../../config/apiKeySignup.js';
2
3
  const EASYSCHOLAR_URL = 'https://www.easyscholar.cc/open/getPublicationRank';
3
4
  const REQUEST_DELAY_MS = 500;
4
5
  function easyScholarKey() {
5
6
  const key = process.env.EASYSCHOLAR_KEY || '';
6
7
  if (!key.trim()) {
7
- throw new Error('EasyScholar API key not configured. Set EASYSCHOLAR_KEY with `paper-search setup EASYSCHOLAR_KEY`.');
8
+ throw new Error(`EasyScholar API key not configured. ${apiKeyHint('EASYSCHOLAR_KEY')}`);
8
9
  }
9
10
  return key.trim();
10
11
  }