papersearch 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.en.md +7 -4
  2. package/README.md +7 -4
  3. package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
  4. package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
  5. package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
  6. package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
  7. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
  8. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
  9. package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
  10. package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
  11. package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
  12. package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
  13. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
  14. package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
  15. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
  16. package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
  17. package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
  18. package/carsi/paper_search_carsi/assets/capsule.html +112 -32
  19. package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
  20. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -0
  21. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
  22. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
  23. package/carsi/paper_search_carsi/browser/backend.py +36 -0
  24. package/carsi/paper_search_carsi/browser/background.py +68 -0
  25. package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
  26. package/carsi/paper_search_carsi/browser/challenges.py +10 -0
  27. package/carsi/paper_search_carsi/browser/foreground.py +201 -0
  28. package/carsi/paper_search_carsi/browser/login.py +3 -1
  29. package/carsi/paper_search_carsi/browser/preview.py +3 -1
  30. package/carsi/paper_search_carsi/config.py +4 -1
  31. package/carsi/paper_search_carsi/engine/batch.py +73 -21
  32. package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
  33. package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
  34. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +10 -0
  35. package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
  36. package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
  37. package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
  38. package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
  39. package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
  40. package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
  41. package/carsi/paper_search_carsi/engine/supplement_transfer.py +55 -0
  42. package/carsi/paper_search_carsi/engine/supplements.py +96 -24
  43. package/carsi/paper_search_carsi/entitlements.py +23 -3
  44. package/carsi/paper_search_carsi/progress_capsule.py +246 -30
  45. package/carsi/paper_search_carsi/progress_macos.py +166 -0
  46. package/carsi/paper_search_carsi/progress_reporter.py +22 -1
  47. package/carsi/paper_search_carsi/progress_view.py +1 -0
  48. package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
  49. package/carsi/paper_search_carsi/server.py +17 -1
  50. package/carsi/paper_search_carsi/user_settings.py +4 -4
  51. package/carsi/pyproject.toml +1 -1
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  54. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.js +28 -4
  56. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  57. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  58. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
  59. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  61. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  63. package/dist/infrastructure/runlog/failureClass.js +3 -2
  64. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  65. package/dist/management/carsi/installer.d.ts +2 -1
  66. package/dist/management/carsi/installer.d.ts.map +1 -1
  67. package/dist/management/carsi/installer.js +24 -1
  68. package/dist/management/carsi/installer.js.map +1 -1
  69. package/package.json +1 -1
  70. package/skills/paper-search/references/browser-download.md +11 -7
  71. package/skills/paper-search/references/carsi-setup.md +1 -0
  72. package/skills/paper-search/references/publisher-support.md +42 -41
@@ -3,8 +3,9 @@
3
3
  Collapsed it shows how far the task is ("12/40 正文 · Wiley"). Hovering opens
4
4
  a card with the paper, the counts and every action of the classic window
5
5
  (skip, no access, stop, problem report, settings, output folder). A step that
6
- needs the user (school login, verification) opens the card by itself and
7
- raises one system notification. The page is HTML (``assets/capsule.html``)
6
+ needs the user (school login, verification) turns amber with a breathing glow
7
+ and raises one system notification. Clicking the reminder activates the task's
8
+ browser. The page is HTML (``assets/capsule.html``)
8
9
  drawn by pywebview with the system web engine: WebKit on macOS, WebView2 on
9
10
  Windows. Without pywebview or a usable engine the classic window
10
11
  (``progress_bar``) opens instead.
@@ -72,9 +73,11 @@ class Placement:
72
73
  self.right, self.edge = right, edge
73
74
  return int(right - w), int(edge if self.corner == "top" else edge - h)
74
75
 
75
- def moved(self, x: float, y: float, w: float, h: float) -> None:
76
+ def moved(self, x: float, y: float, w: float, h: float, *, persist: bool = True) -> None:
76
77
  self.right = x + w
77
78
  self.edge = y if self.corner == "top" else y + h
79
+ if not persist:
80
+ return
78
81
  try:
79
82
  self.path.write_text(json.dumps({"corner": self.corner, "right": self.right, "edge": self.edge}),
80
83
  encoding="utf-8")
@@ -82,12 +85,15 @@ class Placement:
82
85
  pass
83
86
 
84
87
 
85
- def notify(title: str, body: str) -> None:
86
- """One system notification; silently nothing where none is available."""
88
+ def notify(title: str, body: str, state: dict[str, Any] | None = None) -> None:
89
+ """One system notification, bound to the current task on macOS."""
90
+ if not user_settings.notify_enabled():
91
+ return
87
92
  try:
88
93
  if sys.platform == "darwin":
89
- script = f"display notification {json.dumps(body)} with title {json.dumps(title)}"
90
- subprocess.run(["osascript", "-e", script], capture_output=True, timeout=5)
94
+ from .progress_macos import notify as native_notify
95
+
96
+ native_notify(title, body, state or {})
91
97
  elif os.name == "nt":
92
98
  # Windows toast through PowerShell's registered app id; the texts go in by
93
99
  # environment so no quoting is needed.
@@ -104,9 +110,11 @@ def notify(title: str, body: str) -> None:
104
110
  )
105
111
  subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
106
112
  env={**os.environ, "PSC_TITLE": title, "PSC_BODY": body},
107
- capture_output=True, timeout=10, creationflags=0x08000000)
108
- except Exception:
109
- pass
113
+ capture_output=True, timeout=10, check=True, creationflags=0x08000000)
114
+ except Exception as exc:
115
+ import logging
116
+
117
+ logging.getLogger(__name__).warning("progress notification failed: %s", type(exc).__name__)
110
118
 
111
119
 
112
120
  class Notifier:
@@ -115,17 +123,31 @@ class Notifier:
115
123
  def __init__(self, send=notify) -> None:
116
124
  self._send = send
117
125
  self._seen: set[str] = set()
126
+ self._task: tuple[str, str] = ("", "")
118
127
 
119
128
  def observe(self, state: dict[str, Any] | None) -> None:
129
+ if not user_settings.notify_enabled():
130
+ self._seen.clear()
131
+ if sys.platform == "darwin":
132
+ from .progress_macos import close
133
+
134
+ close()
135
+ return
136
+ task = (str((state or {}).get("run_id") or ""), str((state or {}).get("current") or ""))
120
137
  attention = state.get("attention") if state and state.get("status") == "running" else None
121
138
  prompts = {f"{key}@{value.get('since', '')}": value for key, value in attention.items()
122
139
  if isinstance(value, dict)} if isinstance(attention, dict) else {}
123
- new = [prompts[key] for key in prompts if key not in self._seen]
140
+ new = [prompts[key] for key in prompts if task != self._task or key not in self._seen]
141
+ if self._seen and (not prompts or task != self._task) and sys.platform == "darwin":
142
+ from .progress_macos import clear_notifications
143
+
144
+ clear_notifications()
124
145
  self._seen = set(prompts)
125
- if not new or not user_settings.notify_enabled():
146
+ self._task = task
147
+ if not new:
126
148
  return
127
149
  message = str(new[-1].get("message") or "需要你在浏览器里处理")
128
- threading.Thread(target=self._send, args=("PaperSearch", message), daemon=True).start()
150
+ threading.Thread(target=self._send, args=("PaperSearch", message, state), daemon=True).start()
129
151
 
130
152
 
131
153
  class Api:
@@ -138,6 +160,10 @@ class Api:
138
160
  self._notifier = notifier
139
161
  self._auto_close = auto_close
140
162
  self._size = START_SIZE
163
+ self._geometry_lock = threading.RLock()
164
+ self._dragging = False
165
+ self._native_geometry = False
166
+ self._drag_origin: tuple[float, float, float, float] | None = None
141
167
  self._hovering = False
142
168
  self._closed = False
143
169
  self._close_requested: float | None = None
@@ -148,7 +174,7 @@ class Api:
148
174
 
149
175
  def state(self, hovering: bool = False) -> dict[str, Any]:
150
176
  """The capsule's view of the progress file; ``hovering`` keeps a finished window open."""
151
- self._hovering = bool(hovering)
177
+ self._hovering = bool(hovering) or self._dragging
152
178
  try:
153
179
  return progress_view.view(read_state(), time.time())
154
180
  except Exception:
@@ -182,10 +208,35 @@ class Api:
182
208
  pass
183
209
 
184
210
  # --- the buttons ------------------------------------------------------
211
+ def activate_on_input(self) -> None:
212
+ """The first real click restores normal Windows focus and keyboard input."""
213
+ activate = getattr(self._window, "_capsule_activate_on_input", None)
214
+ if callable(activate):
215
+ activate()
216
+
185
217
  def act(self, action: str, current: str, run_id: str = "") -> str:
186
- """Skip, no access (journal / publisher) or stop, for the running download."""
218
+ """Control the running download, including showing its browser on request."""
187
219
  try:
188
- from .entitlements import request_action
220
+ from .entitlements import SHOW_BROWSER, request_action
221
+
222
+ if action == SHOW_BROWSER:
223
+ state = read_state() or {}
224
+ if (state.get("status") != "running" or not state.get("attention")
225
+ or str(state.get("current") or "") != current
226
+ or str(state.get("run_id") or "") != run_id):
227
+ return "当前没有等待处理的下载浏览器"
228
+ if sys.platform == "darwin":
229
+ from .browser.foreground import activate_mac
230
+
231
+ pid = state.get("browser_pid")
232
+ if not isinstance(pid, int) or pid <= 0 or not activate_mac(pid):
233
+ return "未能切到下载浏览器,请从程序坞打开"
234
+ if os.name == "nt" and isinstance(state.get("owner_pid"), int) and state["owner_pid"] > 0:
235
+ # The click gives this foreground window permission to let
236
+ # the exact backend process activate its browser on Windows.
237
+ import ctypes
238
+
239
+ ctypes.windll.user32.AllowSetForegroundWindow(state["owner_pid"])
189
240
 
190
241
  request_action(str(current), str(action), str(run_id))
191
242
  return progress_view.ACTION_FEEDBACK[str(action)]
@@ -220,6 +271,17 @@ class Api:
220
271
  "download_dir": download_directory.current(),
221
272
  }
222
273
 
274
+ def set_notifications(self, enabled: bool) -> dict[str, Any]:
275
+ """The notification switch saves immediately, independently of other fields."""
276
+ if not isinstance(enabled, bool):
277
+ return {"ok": False, "error": "通知开关必须为开启或关闭"}
278
+ try:
279
+ user_settings.set_notify(enabled)
280
+ self._notifier.observe(read_state())
281
+ except (OSError, ValueError) as exc:
282
+ return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
283
+ return {"ok": True, "notify": enabled}
284
+
223
285
  def save_settings(self, values: dict[str, Any], notify_on: bool, download_dir: str | None = None) -> dict[str, Any]:
224
286
  """Check every field, then save them all; nothing is saved when one is wrong."""
225
287
  checked, errors = {}, {}
@@ -254,22 +316,54 @@ class Api:
254
316
  return str(selected[0]) if selected else None
255
317
 
256
318
  # --- the window -------------------------------------------------------
319
+ def set_dragging(self, active: bool, screen_x: float = 0, screen_y: float = 0) -> None:
320
+ """Freeze resizing while held, then remember the actual drop position."""
321
+ with self._geometry_lock:
322
+ self._dragging = bool(active)
323
+ if self._dragging:
324
+ self._hovering = True
325
+ x, y, _, _ = _window_geometry(self._window, self._native_geometry)
326
+ self._drag_origin = (screen_x, screen_y, x, y)
327
+ elif self._window is not None:
328
+ self._drag_origin = None
329
+ self._placement.moved(*_window_geometry(self._window, self._native_geometry))
330
+
331
+ def move_drag(self, screen_x: float, screen_y: float) -> None:
332
+ """Use pointer deltas, independent of the web engine's screen origin."""
333
+ with self._geometry_lock:
334
+ if not self._dragging or self._drag_origin is None:
335
+ return
336
+ sx, sy, x, y = self._drag_origin
337
+ x, y = round(x + screen_x - sx), round(y + screen_y - sy)
338
+ if sys.platform == "darwin" and self._native_geometry:
339
+ import AppKit
340
+
341
+ def move():
342
+ top = AppKit.NSScreen.screens()[0].frame().size.height
343
+ self._window.native.setFrameTopLeftPoint_(AppKit.NSPoint(x, top - y))
344
+ _cocoa_call(move)
345
+ else:
346
+ self._window.move(x, y)
347
+
257
348
  def resize(self, width: float, height: float) -> None:
258
349
  """The page's new size; the capsule's anchored corner stays put."""
259
350
  size = (max(MIN_SIZE[0], int(width)), max(MIN_SIZE[1], int(height)))
260
- if size == self._size or self._window is None:
261
- return
262
- self._size = size
263
- try:
264
- from webview.window import FixPoint
351
+ with self._geometry_lock:
352
+ if self._dragging or size == self._size or self._window is None:
353
+ return
354
+ try:
355
+ from webview.window import FixPoint
265
356
 
266
- vertical = FixPoint.NORTH if self._placement.corner == "top" else FixPoint.SOUTH
267
- self._window.resize(size[0], size[1], fix_point=vertical | FixPoint.EAST)
268
- except Exception:
269
- pass
357
+ vertical = FixPoint.NORTH if self._placement.corner == "top" else FixPoint.SOUTH
358
+ self._window.resize(size[0], size[1], fix_point=vertical | FixPoint.EAST)
359
+ self._size = size
360
+ except Exception:
361
+ pass
270
362
 
271
363
  def moved(self, x: float, y: float) -> None:
272
- self._placement.moved(x, y, *self._size)
364
+ if self._native_geometry:
365
+ x, y, _, _ = _window_geometry(self._window, self._native_geometry)
366
+ self._placement.moved(x, y, *self._size, persist=not self._dragging)
273
367
 
274
368
  def request_close(self) -> None:
275
369
  # Let the JS bridge deliver this call's reply before disposing WebView2.
@@ -323,6 +417,63 @@ def _enable_inactive_hover(window: Any) -> None:
323
417
  AppHelper.callAfter(install)
324
418
 
325
419
 
420
+ def _cocoa_call(action):
421
+ """Wait for the one native geometry operation instead of queuing frames."""
422
+ from PyObjCTools import AppHelper
423
+
424
+ complete, cancelled = threading.Event(), threading.Event()
425
+ result, errors = [], []
426
+
427
+ def apply():
428
+ try:
429
+ if not cancelled.is_set():
430
+ result.append(action())
431
+ except Exception as exc:
432
+ errors.append(exc)
433
+ finally:
434
+ complete.set()
435
+
436
+ AppHelper.callAfter(apply)
437
+ if not complete.wait(2):
438
+ cancelled.set()
439
+ raise TimeoutError("capsule native geometry did not complete")
440
+ if errors:
441
+ raise errors[0]
442
+ return result[0]
443
+
444
+
445
+ def _window_geometry(window: Any, native: bool = False) -> tuple[float, float, float, float]:
446
+ if sys.platform == "darwin" and native:
447
+ import AppKit
448
+
449
+ def read():
450
+ frame = window.native.frame()
451
+ top = AppKit.NSScreen.screens()[0].frame().size.height
452
+ return frame.origin.x, top - frame.origin.y - frame.size.height, frame.size.width, frame.size.height
453
+ return _cocoa_call(read)
454
+ return window.x, window.y, window.width, window.height
455
+
456
+
457
+ def _serialize_native_resize(window: Any) -> None:
458
+ """Await actual Cocoa frame changes so queued resizes cannot race a grab."""
459
+ if sys.platform != "darwin":
460
+ return
461
+ from webview.window import FixPoint
462
+
463
+ def resize(width, height, fix_point=None):
464
+ def apply():
465
+ frame = window.native.frame()
466
+ if fix_point and fix_point & FixPoint.EAST:
467
+ frame.origin.x += frame.size.width - width
468
+ if fix_point and fix_point & FixPoint.NORTH:
469
+ frame.origin.y += frame.size.height - height
470
+ frame.size.width, frame.size.height = width, height
471
+ window.native.setFrame_display_(frame, True)
472
+ _cocoa_call(apply)
473
+
474
+ window.resize = resize
475
+
476
+
326
477
  def _windows_taskbar_icon(window: Any) -> None:
327
478
  """PaperSearch's icon on the window's taskbar button (WinForms through pythonnet)."""
328
479
  try:
@@ -365,6 +516,13 @@ def _prepare_nonactivating_start(window: Any) -> None:
365
516
  if sys.platform == "darwin":
366
517
  from webview.platforms import cocoa
367
518
 
519
+ import objc
520
+
521
+ def acceptsFirstMouse_(self, event):
522
+ # Accept the first grab instead of consuming it just for activation.
523
+ return self.pywebview_window is window
524
+
525
+ objc.classAddMethods(cocoa.BrowserView.WebKitHost, [acceptsFirstMouse_])
368
526
  original = cocoa.BrowserView.first_show
369
527
 
370
528
  def first_show(view):
@@ -391,20 +549,59 @@ def _prepare_nonactivating_start(window: Any) -> None:
391
549
  get_style.restype = ctypes.c_ssize_t
392
550
  set_style.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_ssize_t]
393
551
  set_style.restype = ctypes.c_ssize_t
552
+ user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int,
553
+ ctypes.c_int, ctypes.c_int, wintypes.UINT]
554
+ user32.SetForegroundWindow.argtypes = [wintypes.HWND]
394
555
  initial = []
395
556
 
396
557
  def before_show():
397
- hwnd = window.native.Handle.ToInt64()
558
+ from webview.window import FixPoint
559
+
560
+ native = window.native
561
+ hwnd = native.Handle.ToInt64()
398
562
  initial.append((hwnd, get_style(hwnd, -20)))
399
563
  set_style(hwnd, -20, initial[-1][1] | 0x08000000) # WS_EX_NOACTIVATE
400
-
401
- def shown():
564
+ # WinForms' geometry methods omit SWP_NOACTIVATE: even an animated
565
+ # resize can steal focus after the nonactivating initial show.
566
+ # Preserve their logical-pixel geometry, only for this capsule.
567
+ def resize(width, height, fix_point):
568
+ width, height = int(width * native._scale), int(height * native._scale)
569
+ x, y = native.Location.X, native.Location.Y
570
+ if fix_point & FixPoint.EAST:
571
+ x += native.Width - width
572
+ if fix_point & FixPoint.SOUTH:
573
+ y += native.Height - height
574
+ user32.SetWindowPos(hwnd, None, x, y, width, height, 0x0054)
575
+
576
+ def move(x, y):
577
+ user32.SetWindowPos(hwnd, None, int(x * native._scale), int(y * native._scale),
578
+ 0, 0, 0x0055) # NOSIZE | NOZORDER | NOACTIVATE | SHOWWINDOW
579
+
580
+ native.resize, native.move = resize, move
581
+ # pywebview's Shown handler calls WebView2.Focus() after raising
582
+ # events.shown. That explicit focus defeats the initial native
583
+ # style, even if we restore the style later. Suppress just this
584
+ # first Focus call; later user-initiated restores keep normal input.
585
+ original = native.on_shown
586
+
587
+ def first_shown(*_):
588
+ native.Shown -= first_shown
589
+ native.Shown += original
590
+ window.events.shown.set()
591
+
592
+ native.Shown -= original
593
+ native.Shown += first_shown
594
+
595
+ def activate_on_input():
402
596
  if initial:
403
597
  hwnd, style = initial.pop()
404
598
  set_style(hwnd, -20, style)
599
+ user32.SetForegroundWindow(hwnd)
405
600
 
406
601
  window.events.before_show += before_show
407
- window.events.shown += shown
602
+ # Keep the style through the native startup sequence. Restoring it on
603
+ # shown allows Application.Run/WebView2 to focus the just-shown form.
604
+ window._capsule_activate_on_input = activate_on_input
408
605
 
409
606
 
410
607
  def main() -> None:
@@ -427,6 +624,17 @@ def main() -> None:
427
624
  background_color="#202124" if dark else "#FFFFFF",
428
625
  )
429
626
  api._window = window
627
+ if sys.platform == "darwin":
628
+ from .progress_macos import install_notification_handler
629
+
630
+ try:
631
+ install_notification_handler(lambda current, run_id: api.act("show_browser", current, run_id))
632
+ except (OSError, RuntimeError) as exc:
633
+ import logging
634
+
635
+ logging.getLogger(__name__).warning("notification host unavailable: %s", type(exc).__name__)
636
+ api._native_geometry = sys.platform == "darwin"
637
+ _serialize_native_resize(window)
430
638
  _prepare_nonactivating_start(window)
431
639
  window.events.moved += api.moved
432
640
  window.events.loaded += lambda: _enable_inactive_hover(window)
@@ -436,10 +644,18 @@ def main() -> None:
436
644
  # icon: the Dock icon on macOS, instead of a blank one; watch: notifications and closing.
437
645
  webview.start(func=api.watch, icon=str(ICON) if sys.platform == "darwin" else None)
438
646
  except Exception: # no usable web engine (e.g. WebView2 missing): the classic window
647
+ if sys.platform == "darwin":
648
+ from .progress_macos import close
649
+
650
+ close()
439
651
  progress_view.release_window_lock()
440
652
  _classic()
441
653
  return
442
654
  progress_view.release_window_lock()
655
+ if sys.platform == "darwin":
656
+ from .progress_macos import close
657
+
658
+ close()
443
659
  # The window is gone. pywebview answers each page call on a thread of its own,
444
660
  # and one still waiting for the closed page would hold the interpreter's
445
661
  # shutdown forever (the window froze on screen): leave without waiting.
@@ -0,0 +1,166 @@
1
+ """A bundled native notification host; clicks use the capsule's current-task action.
2
+
3
+ No compiler, third-party notifier, system setting changes or global input hooks
4
+ are needed on the user's Mac. Notification permission remains managed by macOS.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import atexit
9
+ import json
10
+ import logging
11
+ from pathlib import Path
12
+ import plistlib
13
+ import struct
14
+ import subprocess
15
+ import threading
16
+ from typing import Any, Callable
17
+
18
+ logger = logging.getLogger(__name__)
19
+ BUNDLE_ID = "com.papersearch.progress"
20
+ _bridge: NotificationBridge | None = None
21
+ _callback: Callable[[str, str], Any] | None = None
22
+ _bridge_lock = threading.RLock()
23
+
24
+
25
+ def _write_if_changed(path: Path, content: bytes, mode: int = 0o644) -> None:
26
+ if path.is_file() and path.read_bytes() == content:
27
+ return
28
+ temporary = path.with_name(path.name + ".tmp")
29
+ temporary.write_bytes(content)
30
+ temporary.chmod(mode)
31
+ temporary.replace(path)
32
+
33
+
34
+ def prepare_app(app_root: Path | None = None) -> Path:
35
+ """Give Notification Center a real executable, stable app identity and icon."""
36
+ assets = Path(__file__).with_name("assets")
37
+ # One identity and bundle for all profiles and upgrades, so users only have
38
+ # one PaperSearch notification preference. Task isolation belongs in messages.
39
+ app_root = app_root or Path.home() / "Library" / "Application Support" / "PaperSearch"
40
+ app = app_root.resolve() / "PaperSearch.app"
41
+ macos, resources = app / "Contents/MacOS", app / "Contents/Resources"
42
+ macos.mkdir(parents=True, exist_ok=True)
43
+ 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
+ chunks = []
52
+ for size, kind in ((32, b"icp5"), (64, b"icp6"), (512, b"ic09")):
53
+ image = (assets / f"icon-{size}.png").read_bytes()
54
+ chunks.append(kind + struct.pack(">I", len(image) + 8) + image)
55
+ body = b"".join(chunks)
56
+ _write_if_changed(resources / "PaperSearch.icns", b"icns" + struct.pack(">I", len(body) + 8) + body)
57
+ executable = macos / "PaperSearch"
58
+ _write_if_changed(executable, (assets / "papersearch-notifier").read_bytes(), 0o755)
59
+ return executable
60
+
61
+
62
+ class NotificationBridge:
63
+ def __init__(self, executable: Path, callback: Callable[[str, str], Any]) -> None:
64
+ self.callback = callback
65
+ self._lock = threading.Lock()
66
+ self._ready = threading.Event()
67
+ self.process = subprocess.Popen(
68
+ [str(executable)], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
69
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1,
70
+ )
71
+ self._reader = threading.Thread(target=self._read, daemon=True)
72
+ self._reader.start()
73
+ if not self._ready.wait(5):
74
+ self.close()
75
+ raise RuntimeError("PaperSearch's notification host did not start")
76
+
77
+ def _read(self) -> None:
78
+ assert self.process.stdout is not None
79
+ try:
80
+ while line := self.process.stdout.readline(65536):
81
+ if not line.endswith("\n"):
82
+ raise ValueError("oversized notification event")
83
+ event = json.loads(line)
84
+ if not isinstance(event, dict):
85
+ continue
86
+ if event.get("event") == "ready":
87
+ self._ready.set()
88
+ elif event.get("event") == "clicked":
89
+ current, run_id = event.get("current"), event.get("run_id")
90
+ if isinstance(current, str) and isinstance(run_id, str) and current and run_id:
91
+ try:
92
+ self.callback(current, run_id)
93
+ except Exception as exc:
94
+ logger.warning("notification click failed: %s", type(exc).__name__)
95
+ except (OSError, ValueError) as exc:
96
+ logger.warning("notification host event failed: %s", type(exc).__name__)
97
+ finally:
98
+ self.process.stdout.close()
99
+
100
+ def send(self, action: str, **values: Any) -> None:
101
+ payload = json.dumps({"action": action, **values}, ensure_ascii=False) + "\n"
102
+ if len(payload.encode("utf-8")) >= 65536:
103
+ raise ValueError("notification is too long")
104
+ with self._lock:
105
+ if self.process.poll() is not None or self.process.stdin is None or self.process.stdin.closed:
106
+ raise RuntimeError("PaperSearch's notification host has exited")
107
+ self.process.stdin.write(payload)
108
+ self.process.stdin.flush()
109
+
110
+ def close(self) -> None:
111
+ with self._lock:
112
+ if self.process.stdin is not None and not self.process.stdin.closed:
113
+ self.process.stdin.close()
114
+ try:
115
+ self.process.wait(timeout=2)
116
+ except subprocess.TimeoutExpired:
117
+ self.process.terminate()
118
+ try:
119
+ self.process.wait(timeout=2)
120
+ except subprocess.TimeoutExpired:
121
+ self.process.kill()
122
+ self.process.wait(timeout=2)
123
+
124
+
125
+ def install_notification_handler(callback: Callable[[str, str], Any]) -> None:
126
+ """Register clicks without installing or starting the optional native host."""
127
+ global _callback
128
+ with _bridge_lock:
129
+ close()
130
+ _callback = callback
131
+
132
+
133
+ def notify(title: str, body: str, state: dict[str, Any]) -> None:
134
+ from .user_settings import notify_enabled
135
+
136
+ global _bridge
137
+ with _bridge_lock:
138
+ # A queued notification must also respect a switch turned off meanwhile.
139
+ if not notify_enabled():
140
+ return
141
+ if _bridge is None:
142
+ if _callback is None:
143
+ raise RuntimeError("PaperSearch's notification click handler is unavailable")
144
+ _bridge = NotificationBridge(prepare_app(), _callback)
145
+ _bridge.send("notify", title=title, body=body, current=str(state.get("current") or ""),
146
+ run_id=str(state.get("run_id") or ""))
147
+
148
+
149
+ def clear_notifications() -> None:
150
+ with _bridge_lock:
151
+ if _bridge is not None:
152
+ try:
153
+ _bridge.send("clear")
154
+ except (OSError, RuntimeError) as exc:
155
+ logger.warning("notification clear failed: %s", type(exc).__name__)
156
+
157
+
158
+ def close() -> None:
159
+ global _bridge
160
+ with _bridge_lock:
161
+ bridge, _bridge = _bridge, None
162
+ if bridge is not None:
163
+ bridge.close()
164
+
165
+
166
+ atexit.register(close)
@@ -147,8 +147,9 @@ def ensure_progress_bar(config: dict[str, Any] | None = None) -> None:
147
147
 
148
148
  kwargs = {"creationflags": 0x08000000} if os.name == "nt" else {}
149
149
  env = {**os.environ, "CARSI_PROGRESS_BAR_CHILD": "1"}
150
+ command = [sys.executable, "-m", "paper_search_carsi.progress_capsule"]
150
151
  subprocess.Popen(
151
- [sys.executable, "-m", "paper_search_carsi.progress_capsule"],
152
+ command,
152
153
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
153
154
  env=env, start_new_session=(os.name != "nt"), **kwargs,
154
155
  )
@@ -457,6 +458,13 @@ def advance(ok: bool, current: str = "", phase: str = "") -> None:
457
458
  _write_state()
458
459
 
459
460
 
461
+ def has_attention(*, current: str = "", excluding: str = "") -> bool:
462
+ """Whether another reminder already asks this paper's user to act."""
463
+ with _LOCK:
464
+ return any(key != excluding and (not current or value.get("current") == current)
465
+ for key, value in _STATE.get("attention", {}).items())
466
+
467
+
460
468
  def set_attention(key: str, message: str, *, current: str = "", phase: str = "",
461
469
  deadline: float | None = None) -> None:
462
470
  """Show a manual-action reminder without stopping other workers; ``deadline``
@@ -479,6 +487,19 @@ def set_attention(key: str, message: str, *, current: str = "", phase: str = "",
479
487
  _write_state()
480
488
 
481
489
 
490
+ def update_attention_deadline(key: str, deadline: float | None) -> None:
491
+ """Change only the countdown, keeping the reminder/notification identity."""
492
+ with _LOCK:
493
+ attention = _STATE.get("attention", {}).get(str(key))
494
+ if attention is None or attention.get("deadline") == deadline:
495
+ return
496
+ if deadline is None:
497
+ attention.pop("deadline", None)
498
+ else:
499
+ attention["deadline"] = float(deadline)
500
+ _write_state()
501
+
502
+
482
503
  def set_output_dir(path) -> None:
483
504
  """Record the actual task folder for diagnostics and the window folder button."""
484
505
  with _LOCK:
@@ -34,6 +34,7 @@ STAGE_STEP = {
34
34
  ATTENTION_SHORT = {"waiting_login": "请登录学校", "waiting_verification": "请完成验证"}
35
35
  # The answer a button gets in the window, before the download confirms it.
36
36
  ACTION_FEEDBACK = {
37
+ "show_browser": "正在切到下载浏览器",
37
38
  "stop_batch": "已终止任务:这一篇结束,剩下的不再下载",
38
39
  "skip_item": "已跳过本篇,进入下一篇",
39
40
  "skip_journal": "已记住:本刊无权限,以后自动跳过(可用 entitlements 撤销)",
@@ -81,9 +81,11 @@ def get_publisher_profile(name: str, *, profiles: Mapping[str, PublisherProfile]
81
81
  return profile
82
82
 
83
83
 
84
- # Journals whose DOIs keep a former publisher's registrant prefix.
85
- _MOVED_JOURNALS = {
84
+ # Journals whose publishing platform differs from their DOI registrant.
85
+ _JOURNAL_PLATFORMS = {
86
86
  "10.1136/ard-": "elsevier", # Annals of the Rheumatic Diseases: BMJ -> Elsevier (2025)
87
+ "10.1182/blood.": "elsevier", # ASH's publishing partner since 2021; also on ScienceDirect.
88
+ "10.1182/bloodadvances.": "elsevier",
87
89
  }
88
90
 
89
91
 
@@ -91,7 +93,7 @@ def infer_publisher_profile(doi: str, *, profiles: Mapping[str, PublisherProfile
91
93
  """Infer a likely publisher profile from stable DOI prefixes."""
92
94
  normalized = doi.strip().lower()
93
95
  catalog = PUBLISHER_PROFILES if profiles is None else profiles
94
- for prefix, key in _MOVED_JOURNALS.items():
96
+ for prefix, key in _JOURNAL_PLATFORMS.items():
95
97
  if normalized.startswith(prefix) and key in catalog:
96
98
  return catalog[key]
97
99
  for profile in catalog.values():