papersearch 0.4.8 → 0.4.10

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 (104) hide show
  1. package/README.en.md +50 -62
  2. package/README.md +50 -62
  3. package/assets/overview.en.png +0 -0
  4. package/assets/overview.png +0 -0
  5. package/assets/progress-capsule.en.png +0 -0
  6. package/assets/progress-capsule.png +0 -0
  7. package/carsi/README.md +5 -6
  8. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  9. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  10. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  11. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  12. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  13. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  14. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  15. package/carsi/paper_search_carsi/assets/capsule.html +199 -24
  16. package/carsi/paper_search_carsi/browser/backend.py +270 -227
  17. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  18. package/carsi/paper_search_carsi/browser/challenge_interaction.py +79 -43
  19. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  20. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  21. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  22. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  23. package/carsi/paper_search_carsi/browser/login.py +12 -18
  24. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  25. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  26. package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
  27. package/carsi/paper_search_carsi/capsule_placement.py +266 -0
  28. package/carsi/paper_search_carsi/cli.py +22 -7
  29. package/carsi/paper_search_carsi/cold_start.py +65 -51
  30. package/carsi/paper_search_carsi/config.py +6 -4
  31. package/carsi/paper_search_carsi/engine/batch.py +9 -5
  32. package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
  33. package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
  34. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  35. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +4 -2
  36. package/carsi/paper_search_carsi/engine/batch_institution.py +146 -17
  37. package/carsi/paper_search_carsi/engine/batch_login.py +79 -26
  38. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  39. package/carsi/paper_search_carsi/engine/batch_waits.py +92 -37
  40. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  41. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  42. package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
  43. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  44. package/carsi/paper_search_carsi/network.py +1 -1
  45. package/carsi/paper_search_carsi/progress_capsule.py +233 -93
  46. package/carsi/paper_search_carsi/progress_reporter.py +88 -7
  47. package/carsi/paper_search_carsi/progress_view.py +61 -0
  48. package/carsi/paper_search_carsi/server.py +47 -10
  49. package/carsi/paper_search_carsi/session_broker.py +1 -1
  50. package/carsi/paper_search_carsi/user_settings.py +1 -1
  51. package/carsi/pyproject.toml +7 -7
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  54. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  56. package/dist/capabilities/pdf-discovery/batch.js +15 -5
  57. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  58. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
  59. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  60. package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
  61. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  62. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  63. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
  65. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
  67. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  68. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
  69. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  75. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  77. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
  79. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  81. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  82. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  83. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  84. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  85. package/dist/cli.js +13 -9
  86. package/dist/cli.js.map +1 -1
  87. package/dist/management/carsi/installer.d.ts +26 -14
  88. package/dist/management/carsi/installer.d.ts.map +1 -1
  89. package/dist/management/carsi/installer.js +113 -69
  90. package/dist/management/carsi/installer.js.map +1 -1
  91. package/dist/management/carsi/runtime.d.ts +12 -1
  92. package/dist/management/carsi/runtime.d.ts.map +1 -1
  93. package/dist/management/carsi/runtime.js +30 -1
  94. package/dist/management/carsi/runtime.js.map +1 -1
  95. package/package.json +1 -1
  96. package/skills/paper-search/SKILL.md +4 -4
  97. package/skills/paper-search/references/browser-download.md +3 -3
  98. package/skills/paper-search/references/carsi-setup.md +7 -6
  99. package/skills/paper-search/references/cli-contract.md +4 -4
  100. package/skills/paper-search/references/management-layer.md +2 -2
  101. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  102. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  103. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  104. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -23,7 +23,7 @@ from urllib.parse import urlsplit
23
23
  from uuid import UUID, uuid4
24
24
  from weakref import WeakKeyDictionary
25
25
 
26
- from .watchdog import BrowserUnresponsive
26
+ from .watchdog import BrowserUnresponsive, operation_remaining
27
27
  from ..entitlements import UserMarkedNoEntitlement
28
28
 
29
29
  _OBSERVERS = WeakKeyDictionary()
@@ -32,6 +32,7 @@ _KINDS = {'blank', 'article', 'pdf', 'login', 'other'}
32
32
  OBSERVE_INTERVAL_SEC = 4 # between unforced frames (waits refresh at most this often)
33
33
  MAX_KEPT_FRAMES = 5 # earlier page states kept per download, besides each tab's newest frame
34
34
  JPEG_QUALITY = 60
35
+ SCREENSHOT_TIMEOUT_MS = 1500
35
36
 
36
37
 
37
38
  def _atomic(path: Path, data: bytes) -> None:
@@ -62,6 +63,7 @@ class BrowserPreview:
62
63
  self.observing = False
63
64
  self.paused = 0
64
65
  self._cdp = WeakKeyDictionary()
66
+ self._navigation_listeners = {}
65
67
  context.on('close', self.close)
66
68
  self._write([])
67
69
  context.on('page', self._attach_page)
@@ -74,22 +76,30 @@ class BrowserPreview:
74
76
  # browser calls. Capture at the next workflow observation instead.
75
77
  self.page_revisions[page] = self.page_revisions.get(page, 0) + 1
76
78
  self.last_observed = 0.0
79
+ self._navigation_listeners[page] = changed
77
80
  page.on('domcontentloaded', changed)
78
81
 
79
- def close(self, *_args):
82
+ def close(self, *_args, browser_closed=True):
80
83
  self.closed = True
81
84
  try:
82
85
  if self._is_current():
83
- self._write(self.pages)
86
+ self._write(self.pages, browser_closed=browser_closed)
84
87
  except OSError:
85
88
  logging.getLogger(__name__).warning('browser_preview_unavailable')
86
89
  finally:
90
+ self.context.remove_listener('close', self.close)
91
+ self.context.remove_listener('page', self._attach_page)
92
+ for page, changed in self._navigation_listeners.items():
93
+ page.remove_listener('domcontentloaded', changed)
94
+ self._navigation_listeners.clear()
95
+ if self._is_current():
96
+ _ACTIVE.pop(str(self.directory.resolve()))
87
97
  _OBSERVERS.pop(self.context, None)
88
98
 
89
99
  def _is_current(self):
90
100
  return _ACTIVE.get(str(self.directory.resolve())) == self.context_id
91
101
 
92
- def _write(self, pages):
102
+ def _write(self, pages, *, browser_closed=False):
93
103
  # screenshot() can yield to another context's navigation callback.
94
104
  # Recheck at publication, not only when the observation starts.
95
105
  if not self._is_current():
@@ -99,13 +109,16 @@ class BrowserPreview:
99
109
  packet = {'schema_version': 1, 'run_id': self.run_id, 'identifier': self.identifier,
100
110
  'context_id': self.context_id,
101
111
  'owner_pid': os.getpid(), 'revision': self.revision,
102
- 'observed_at': self.observed_at, 'browser_closed': self.closed, 'pages': pages}
112
+ 'observed_at': self.observed_at, 'browser_closed': browser_closed, 'pages': pages}
103
113
  _atomic(self.directory / 'current.json', json.dumps(packet).encode())
104
114
 
105
115
  def observe(self, *, force=False):
106
116
  if self.closed or not self._is_current() or self.observing or (not force and (
107
117
  self.paused or time.monotonic() - self.last_observed < OBSERVE_INTERVAL_SEC)):
108
118
  return
119
+ remaining = operation_remaining()
120
+ if remaining is not None and remaining * 1000 <= SCREENSHOT_TIMEOUT_MS:
121
+ return # Leave the remaining page time to the download, with the last preview intact.
109
122
  self.observing = True
110
123
  try:
111
124
  self._observe()
@@ -135,7 +148,7 @@ class BrowserPreview:
135
148
  data = session.send("Page.captureScreenshot",
136
149
  {"format": "jpeg", "quality": JPEG_QUALITY, "fromSurface": True})
137
150
  return base64.b64decode(data["data"])
138
- return page.screenshot(timeout=1500, full_page=False, type="jpeg", quality=JPEG_QUALITY)
151
+ return page.screenshot(timeout=SCREENSHOT_TIMEOUT_MS, full_page=False, type="jpeg", quality=JPEG_QUALITY)
139
152
 
140
153
  def _observe(self):
141
154
  self.last_observed = time.monotonic()
@@ -363,13 +376,19 @@ def prune(directory: str | Path, keep: int = DEFAULT_KEEP_RUNS) -> list[str]:
363
376
  def ensure_enabled(context, config: dict | None = None):
364
377
  """Enable the preview for this download context unless turned off; never raises."""
365
378
  config = config or {}
366
- if config.get("browser_preview") is False:
367
- return None
368
- existing = _OBSERVERS.get(context) if context is not None else None
369
- if existing is not None:
370
- return existing
371
- directory = default_directory(config)
372
379
  try:
380
+ existing = _OBSERVERS.get(context) if context is not None else None
381
+ enabled = config.get("browser_preview") is not False
382
+ if existing is not None:
383
+ from .. import progress_reporter
384
+ identity = progress_reporter.read_state() or {}
385
+ if (enabled and existing.run_id == identity.get("run_id")
386
+ and existing.identifier == str(identity.get("current") or "").lower()):
387
+ return existing
388
+ existing.close(browser_closed=False)
389
+ if not enabled:
390
+ return None
391
+ directory = default_directory(config)
373
392
  directory.mkdir(parents=True, mode=0o700, exist_ok=True)
374
393
  try:
375
394
  keep = int(config.get("browser_preview_keep_runs", DEFAULT_KEEP_RUNS))
@@ -24,7 +24,7 @@ SESSION_COOKIES_MAX_AGE_SEC = 12 * 3600
24
24
  def _save_session_cookies(context: Any, profile: Path) -> None:
25
25
  """Keep session cookies (IdP and publisher logins) for the next launch.
26
26
 
27
- Each paper runs in a new backend process and browser; Firefox drops
27
+ Each paper runs in a new backend process and browser; the browser drops
28
28
  cookies without an expiry when it closes, so every paper asked for the
29
29
  school login again. Only session cookies are kept: persistent ones are in
30
30
  the profile already. The file is readable by the user only.
@@ -66,26 +66,20 @@ def _restore_session_cookies(context: Any, profile: Path) -> int:
66
66
 
67
67
 
68
68
  def _profile_owner_pid(user_data_dir: str) -> int | None:
69
- """PID of the browser holding this profile, if any.
70
-
71
- Firefox (Camoufox) leaves a ``lock`` symlink to ``<host>:+<pid>``;
72
- Chromium leaves ``SingletonLock`` to ``<host>-<pid>``.
73
- """
74
- for name in ("lock", "SingletonLock"):
75
- try:
76
- target = os.readlink(Path(user_data_dir) / name)
77
- except OSError:
78
- continue
79
- match = re.search(r"[-+](\d+)$", target)
80
- if match:
81
- return int(match.group(1))
82
- return None
69
+ """PID of the browser holding this profile, if any: Chromium's
70
+ ``SingletonLock`` symlink to ``<host>-<pid>`` (macOS and Linux)."""
71
+ try:
72
+ target = os.readlink(Path(user_data_dir) / "SingletonLock")
73
+ except OSError:
74
+ return None
75
+ match = re.search(r"-(\d+)$", target)
76
+ return int(match.group(1)) if match else None
83
77
 
84
78
 
85
79
  def _lock_file_held(path: Path) -> bool:
86
- """Another process holds this lock file: Firefox's ``.parentlock`` on macOS
87
- and Linux (an fcntl lock; macOS has no ``lock`` symlink), its ``parent.lock``
88
- on Windows (opened without sharing). The lock is tested, never kept."""
80
+ """Another process holds this lock file: Chromium's ``lockfile`` on Windows,
81
+ which the running browser keeps open without write sharing (an fcntl lock
82
+ elsewhere). The lock is tested, never kept."""
89
83
  if not path.exists():
90
84
  return False
91
85
  try:
@@ -110,14 +104,13 @@ def _lock_file_held(path: Path) -> bool:
110
104
 
111
105
 
112
106
  def profile_holder(user_data_dir: str) -> str:
113
- """Who still holds this profile ("" = nobody): a live ``lock`` owner, or a
114
- lock file another process holds."""
107
+ """Who still holds this profile ("" = nobody): a live ``SingletonLock``
108
+ owner, or a ``lockfile`` another process holds (Windows)."""
115
109
  pid = _profile_owner_pid(user_data_dir)
116
110
  if pid is not None and _pid_alive(pid):
117
111
  return f"lock of pid {pid}"
118
- for name in (".parentlock", "parent.lock"):
119
- if _lock_file_held(Path(user_data_dir) / name):
120
- return f"{name} held"
112
+ if _lock_file_held(Path(user_data_dir) / "lockfile"):
113
+ return "lockfile held"
121
114
  return ""
122
115
 
123
116
 
@@ -1,7 +1,7 @@
1
1
  """End an item whose browser call never returns.
2
2
 
3
- On Camoufox a Playwright call can wait forever for an answer (2026-10-31,
4
- after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
3
+ A driver call can wait forever for an answer (2026-10-31, on the earlier
4
+ Firefox-based browser, after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
5
5
  waits for its 20-minute item timeout. Every sync Playwright call is timed
6
6
  here; one still running after ``LIMIT_SEC`` is logged with its caller and
7
7
  cancelled, and it and every later browser call of this process raise
@@ -66,6 +66,10 @@ class BrowserOperationTimeout(BrowserUnresponsive):
66
66
  """The whole page operation exhausted its budget across browser calls."""
67
67
 
68
68
 
69
+ class BrowserBudgetExhausted(BrowserOperationTimeout):
70
+ """No time remained to send another call; the driver did not stall."""
71
+
72
+
69
73
  @contextmanager
70
74
  def operation(seconds: float, label: str):
71
75
  """One monotonic deadline shared by all calls and retries in this scope."""
@@ -111,65 +115,67 @@ def _timeout_error() -> BrowserUnresponsive:
111
115
 
112
116
 
113
117
  def install(limit_sec: float = LIMIT_SEC) -> None:
114
- """Time every sync Playwright call of this process (once)."""
118
+ """Time every sync driver call of this process (once)."""
115
119
  global _installed
116
120
  if _installed:
117
121
  return
118
- from playwright._impl import _sync_base
119
-
120
- original = _sync_base.SyncBase._sync
121
-
122
- def timed_sync(self: Any, coro: Any) -> Any:
123
- name = getattr(coro, "__qualname__", "") or type(coro).__name__
124
- if fired is not None:
125
- coro.close()
126
- raise _timeout_error()
127
- if interrupted is not None:
128
- coro.close()
129
- raise interrupted
130
- if _soon and not _running_soon:
131
- try:
132
- _run_soon_calls()
133
- except BaseException:
134
- coro.close()
135
- raise
136
- key = id(coro)
137
- started = time.monotonic()
138
- _inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
139
- getattr(self, "_loop", None), coro)
140
- budgets = getattr(_local, "budgets", [])
141
- if budgets:
142
- _call_deadlines[key] = tuple(min(budgets, key=lambda budget: budget[0]))
143
- ended = "returned"
144
- try:
145
- # Refuse to start another candidate after the shared budget expired.
146
- if key in _call_deadlines and started >= _call_deadlines[key][0]:
147
- check(limit_sec)
122
+ from .driver import sync_bases
123
+
124
+ def timing(original: Any) -> Any:
125
+ def timed_sync(self: Any, coro: Any) -> Any:
126
+ name = getattr(coro, "__qualname__", "") or type(coro).__name__
127
+ if fired is not None:
148
128
  coro.close()
149
129
  raise _timeout_error()
150
- return original(self, coro)
151
- except asyncio.CancelledError:
152
- ended = "cancelled"
153
- if fired is not None:
154
- raise _timeout_error() from None
155
130
  if interrupted is not None:
156
- raise interrupted from None
157
- raise
158
- except BaseException as exc:
159
- ended = type(exc).__name__
160
- raise
161
- finally:
162
- _inflight.pop(key, None)
163
- _call_deadlines.pop(key, None)
164
- elapsed = time.monotonic() - started
165
- _period["calls"] += 1
166
- _period["seconds"] += elapsed
167
- if elapsed > _period["slowest_sec"]:
168
- _period["slowest"], _period["slowest_sec"] = name, elapsed
169
- if elapsed > SLOW_CALL_SEC and on_slow_call is not None:
170
- _report_slow(name, elapsed, ended)
171
-
172
- _sync_base.SyncBase._sync = timed_sync
131
+ coro.close()
132
+ raise interrupted
133
+ if _soon and not _running_soon:
134
+ try:
135
+ _run_soon_calls()
136
+ except BaseException:
137
+ coro.close()
138
+ raise
139
+ key = id(coro)
140
+ started = time.monotonic()
141
+ budgets = getattr(_local, "budgets", [])
142
+ if budgets:
143
+ deadline, label = min(budgets, key=lambda budget: budget[0])
144
+ # An unsent call cannot indicate a stalled driver. Keep the browser
145
+ # usable outside this operation, including cleanup and the next item.
146
+ if started >= deadline:
147
+ coro.close()
148
+ raise BrowserBudgetExhausted(f"{label} exhausted its page budget before {name}")
149
+ _call_deadlines[key] = (deadline, label)
150
+ _inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
151
+ getattr(self, "_loop", None), coro)
152
+ ended = "returned"
153
+ try:
154
+ return original(self, coro)
155
+ except asyncio.CancelledError:
156
+ ended = "cancelled"
157
+ if fired is not None:
158
+ raise _timeout_error() from None
159
+ if interrupted is not None:
160
+ raise interrupted from None
161
+ raise
162
+ except BaseException as exc:
163
+ ended = type(exc).__name__
164
+ raise
165
+ finally:
166
+ _inflight.pop(key, None)
167
+ _call_deadlines.pop(key, None)
168
+ elapsed = time.monotonic() - started
169
+ _period["calls"] += 1
170
+ _period["seconds"] += elapsed
171
+ if elapsed > _period["slowest_sec"]:
172
+ _period["slowest"], _period["slowest_sec"] = name, elapsed
173
+ if elapsed > SLOW_CALL_SEC and on_slow_call is not None:
174
+ _report_slow(name, elapsed, ended)
175
+ return timed_sync
176
+
177
+ for base in sync_bases():
178
+ base._sync = timing(base._sync)
173
179
  _installed = True
174
180
  threading.Thread(target=_watch, args=(limit_sec,), name="browser-watchdog", daemon=True).start()
175
181
 
@@ -0,0 +1,266 @@
1
+ """Screen-independent capsule geometry; all coordinates use top-left logical pixels."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import math
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ EDGE, TOP_GAP, BOTTOM_GAP = 20, 44, 56
12
+ SNAP_DISTANCE = 24
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Rect:
17
+ x: float
18
+ y: float
19
+ width: float
20
+ height: float
21
+
22
+ @property
23
+ def right(self) -> float:
24
+ return self.x + self.width
25
+
26
+ @property
27
+ def bottom(self) -> float:
28
+ return self.y + self.height
29
+
30
+ def contains_center(self, other: Rect) -> bool:
31
+ return self.contains(other.x + other.width / 2, other.y + other.height / 2)
32
+
33
+ def contains(self, x: float, y: float) -> bool:
34
+ return self.x <= x < self.right and self.y <= y < self.bottom
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ScreenArea:
39
+ name: str
40
+ bounds: Rect
41
+ work: Rect
42
+
43
+
44
+ def screen_for(rect: Rect, screens: list[ScreenArea]) -> ScreenArea:
45
+ """Prefer the centre's screen, otherwise the nearest screen (unplugged display)."""
46
+ for screen in screens:
47
+ if screen.bounds.contains_center(rect):
48
+ return screen
49
+ x, y = rect.x + rect.width / 2, rect.y + rect.height / 2
50
+ return min(screens, key=lambda s: max(s.bounds.x - x, 0, x - s.bounds.right) ** 2
51
+ + max(s.bounds.y - y, 0, y - s.bounds.bottom) ** 2)
52
+
53
+
54
+ def fit_rect(rect: Rect, work: Rect) -> Rect:
55
+ """Keep a rectangle in the work area; oversized content starts at its top/left."""
56
+ return Rect(max(work.x, min(rect.x, work.right - rect.width)),
57
+ max(work.y, min(rect.y, work.bottom - rect.height)), rect.width, rect.height)
58
+
59
+
60
+ def direction_for(rect: Rect, work: Rect) -> tuple[str, str]:
61
+ return ("down" if rect.y + rect.height / 2 < work.y + work.height / 2 else "up",
62
+ "right" if rect.x + rect.width / 2 < work.x + work.width / 2 else "left")
63
+
64
+
65
+ def _edge(start: float, end: float, low: float, high: float) -> int:
66
+ """Return -1/1 for the nearby edge, or 0 for free placement on this axis."""
67
+ left, right = start - low, high - end
68
+ if min(left, right) > SNAP_DISTANCE:
69
+ return 0
70
+ return -1 if left <= right else 1
71
+
72
+
73
+ class Placement:
74
+ """Persist only the collapsed home. Temporary expansion/clamping never moves it."""
75
+ def __init__(self, path: Path, corner: str) -> None:
76
+ self.path, self.corner = path, corner
77
+ self.home: Rect | None = None
78
+ self._dragged_card: Rect | None = None
79
+ self.screen: ScreenArea | None = None
80
+ self.direction = ("down" if corner == "top" else "up", "left")
81
+ self.edges = (0, 0)
82
+ self.expanded = False
83
+ self.scale = 1.0
84
+ self._saved: dict = {}
85
+ try:
86
+ data = json.loads(path.read_text(encoding="utf-8"))
87
+ if isinstance(data, dict):
88
+ self._saved = data
89
+ except FileNotFoundError:
90
+ pass
91
+ except (OSError, ValueError) as exc:
92
+ logging.getLogger(__name__).warning("Cannot read capsule placement: %s", type(exc).__name__)
93
+
94
+ def start(self, screens: list[ScreenArea], size: tuple[int, int], scale: float = 1.0) -> tuple[int, int]:
95
+ w, h = size
96
+ self.scale = scale
97
+ saved = self._saved
98
+ restored = None
99
+ saved_screen = None
100
+ self.edges = (0, 0)
101
+ try:
102
+ if saved.get("version") == 2:
103
+ values = [float(saved[k]) for k in ("x", "y", "width", "height")]
104
+ if all(math.isfinite(n) for n in values) and values[2] > 0 and values[3] > 0:
105
+ old_scale = float(saved.get("scale", 1))
106
+ if not math.isfinite(old_scale) or old_scale <= 0:
107
+ raise ValueError("Invalid saved DPI")
108
+ ratio = old_scale / scale
109
+ restored = Rect(values[0] * ratio, values[1] * ratio, values[2], values[3])
110
+ screen = next((s for s in screens if s.name == saved.get("screen")), None)
111
+ edges = saved.get("edges")
112
+ if screen and isinstance(edges, list) and len(edges) == 2 and all(
113
+ type(edge) is int and edge in (-1, 0, 1) for edge in edges):
114
+ self.edges = (edges[0], edges[1])
115
+ if any(self.edges):
116
+ saved_screen = screen
117
+ if screen and isinstance(saved.get("work"), list) and len(saved["work"]) == 2:
118
+ old_x, old_y = map(float, saved["work"])
119
+ if math.isfinite(old_x) and math.isfinite(old_y):
120
+ restored = Rect(restored.x + screen.work.x - old_x * ratio,
121
+ restored.y + screen.work.y - old_y * ratio,
122
+ restored.width, restored.height)
123
+ elif saved.get("corner") in ("top", "bottom"):
124
+ right, edge = float(saved["right"]), float(saved["edge"])
125
+ if math.isfinite(right) and math.isfinite(edge):
126
+ restored = Rect(right - w, edge if saved["corner"] == "top" else edge - h, w, h)
127
+ except (KeyError, TypeError, ValueError, OverflowError):
128
+ restored = None
129
+ if restored is not None and (saved_screen or any(s.bounds.contains_center(restored) for s in screens)):
130
+ self.screen = saved_screen or screen_for(restored, screens)
131
+ restored = Rect(restored.x, restored.y, min(restored.width, self.screen.work.width),
132
+ min(restored.height, self.screen.work.height))
133
+ self.home = self._fit(restored)
134
+ else:
135
+ self.edges = (0, 0)
136
+ self.screen = screens[0]
137
+ b = self.screen.bounds
138
+ self.home = fit_rect(Rect(b.right - EDGE - w,
139
+ b.y + TOP_GAP if self.corner == "top" else b.bottom - BOTTOM_GAP - h,
140
+ w, h), self.screen.work)
141
+ self.direction = self._direction(self.home)
142
+ return round(self.home.x), round(self.home.y)
143
+
144
+ def rescale(self, scale: float) -> None:
145
+ """Rebase global coordinates when a Windows drag crosses different DPIs."""
146
+ ratio = self.scale / scale
147
+ if ratio != 1:
148
+ if self.home is not None:
149
+ self.home = self._rescaled(self.home, ratio)
150
+ if self._dragged_card is not None:
151
+ self._dragged_card = self._rescaled(self._dragged_card, ratio)
152
+ self.scale = scale
153
+
154
+ @staticmethod
155
+ def _rescaled(rect: Rect, ratio: float) -> Rect:
156
+ return Rect(rect.x * ratio, rect.y * ratio, rect.width, rect.height)
157
+
158
+ def begin(self, expanded: bool, actual: Rect, screens: list[ScreenArea]) -> None:
159
+ if self.home is None:
160
+ self.home = actual
161
+ if not self.expanded:
162
+ # The first measured pill can differ from START_SIZE.
163
+ self.home = actual
164
+ self.screen = screen_for(self.home, screens)
165
+ if not self.expanded:
166
+ self.direction = self._direction(self.home)
167
+ if expanded:
168
+ self.expanded = True
169
+
170
+ def target(self, width: int, height: int, expanded: bool) -> Rect:
171
+ assert self.home is not None and self.screen is not None
172
+ home, work = self.home, self.screen.work
173
+ width, height = min(width, int(work.width)), min(height, int(work.height))
174
+ if expanded or not self.expanded:
175
+ anchor = (self._dragged_card if expanded else None) or home
176
+ vertical, horizontal = self.direction
177
+ x = anchor.right - width if horizontal == "left" else anchor.x
178
+ y = anchor.bottom - height if vertical == "up" else anchor.y
179
+ else:
180
+ # A different status can change the pill's width while it is open.
181
+ x, y = home.x, home.y
182
+ return self._fit(Rect(x, y, width, height))
183
+
184
+ def finish(self, expanded: bool, actual: Rect) -> None:
185
+ if not expanded:
186
+ self.home = actual
187
+ self._dragged_card = None
188
+ self.expanded = False
189
+ self.save()
190
+
191
+ def _fit(self, rect: Rect) -> Rect:
192
+ work = self.screen.work
193
+ horizontal, vertical = self.edges
194
+ x = work.x if horizontal < 0 else work.right - rect.width if horizontal > 0 else rect.x
195
+ y = work.y if vertical < 0 else work.bottom - rect.height if vertical > 0 else rect.y
196
+ return fit_rect(Rect(x, y, rect.width, rect.height), work)
197
+
198
+ def _direction(self, rect: Rect) -> tuple[str, str]:
199
+ vertical, horizontal = direction_for(rect, self.screen.work)
200
+ x, y = self.edges
201
+ return ("down" if y < 0 else "up" if y > 0 else vertical,
202
+ "right" if x < 0 else "left" if x > 0 else horizontal)
203
+
204
+ def _drop_edges(self, rect: Rect, work: Rect, pointer: tuple[float, float] | None) -> tuple[int, int]:
205
+ x = _edge(rect.x, rect.right, work.x, work.right)
206
+ y = _edge(rect.y, rect.bottom, work.y, work.bottom)
207
+ if pointer is None:
208
+ return x, y
209
+ px, py = pointer
210
+ mouse_x = _edge(px, px, work.x, work.right)
211
+ mouse_y = _edge(py, py, work.y, work.bottom)
212
+ if not self.expanded:
213
+ return mouse_x or x, mouse_y or y
214
+ # A large card can touch a second edge by size alone. Only a release
215
+ # near the corner docks both axes; otherwise keep the closer edge.
216
+ if mouse_x or mouse_y:
217
+ return mouse_x, mouse_y
218
+ if x and y:
219
+ dx = abs(rect.x - work.x if x < 0 else work.right - rect.right)
220
+ dy = abs(rect.y - work.y if y < 0 else work.bottom - rect.bottom)
221
+ if dx != dy:
222
+ return (x, 0) if dx < dy else (0, y)
223
+ px_gap = abs(px - (work.x if x < 0 else work.right))
224
+ py_gap = abs(py - (work.y if y < 0 else work.bottom))
225
+ return (x, 0) if px_gap <= py_gap else (0, y)
226
+ return x, y
227
+
228
+ def dragged(self, after: Rect, screens: list[ScreenArea],
229
+ pointer: tuple[float, float] | None = None) -> Rect:
230
+ # At a display seam the card's centre may still be on the previous
231
+ # display. Prefer the display where the user actually released it.
232
+ self.screen = next((s for s in screens if pointer and s.bounds.contains(*pointer)), None)
233
+ if self.screen is None:
234
+ self.screen = screen_for(after, screens)
235
+ work = self.screen.work
236
+ point = pointer if pointer and self.screen.bounds.contains(*pointer) else None
237
+ self.edges = self._drop_edges(after, work, point)
238
+ after = self._fit(Rect(after.x, after.y, min(after.width, work.width), min(after.height, work.height)))
239
+ self.direction = self._direction(after)
240
+ if self.home is None or not self.expanded:
241
+ self.home = after
242
+ else:
243
+ self._dragged_card = after
244
+ vertical, horizontal = self.direction
245
+ w, h = self.home.width, self.home.height
246
+ if point is not None and any(self.edges):
247
+ # The card's chosen growth corner must not quantize where the
248
+ # much smaller pill lands along the side.
249
+ self.home = Rect(point[0] - w / 2, point[1] - h / 2, w, h)
250
+ else:
251
+ self.home = Rect(after.right - w if horizontal == "left" else after.x,
252
+ after.bottom - h if vertical == "up" else after.y, w, h)
253
+ self.home = self._fit(self.home)
254
+ self.save()
255
+ return after
256
+
257
+ def save(self) -> None:
258
+ if self.home is None or self.screen is None:
259
+ return
260
+ try:
261
+ self.path.write_text(json.dumps({"version": 2, "x": self.home.x, "y": self.home.y,
262
+ "width": self.home.width, "height": self.home.height, "screen": self.screen.name,
263
+ "work": [self.screen.work.x, self.screen.work.y], "scale": self.scale,
264
+ "edges": self.edges}), encoding="utf-8")
265
+ except OSError as exc:
266
+ logging.getLogger(__name__).warning("Cannot save capsule placement: %s", type(exc).__name__)
@@ -53,8 +53,11 @@ def _institutional_summary(cfg: dict[str, Any]) -> dict[str, Any]:
53
53
  }
54
54
 
55
55
 
56
- def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]:
56
+ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]], dict[str, Any]]:
57
+ """(ready, checks, browser): ``browser`` is the chrome backend's browser
58
+ (backend.browser_check) when that backend is configured, else {}."""
57
59
  checks: list[dict[str, str]] = []
60
+ browser: dict[str, Any] = {}
58
61
 
59
62
  def add(item: str, ok: bool, detail: str) -> None:
60
63
  checks.append({"item": item, "status": "ok" if ok else "missing", "detail": detail})
@@ -64,10 +67,16 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
64
67
  add("config_file", (data_dir / "config.json").exists(), str(data_dir / "config.json"))
65
68
 
66
69
  try:
67
- from .browser.backend import is_available, resolve_backend
70
+ from .browser.backend import BACKEND_CHROME, CHROME_MISSING, browser_check, is_available, resolve_backend
68
71
 
69
72
  backend = resolve_backend(cfg)
70
- add("browser_backend", bool(is_available(backend)), backend)
73
+ if backend == BACKEND_CHROME:
74
+ browser = browser_check(cfg)
75
+ found = f"{browser['browser']} {browser['version']} ({browser['path']}), {browser['driver']}"
76
+ add("browser_backend", bool(is_available(backend, cfg)),
77
+ f"chrome: {found}" if browser["browser"] else f"chrome: {CHROME_MISSING}")
78
+ else:
79
+ add("browser_backend", bool(is_available(backend, cfg)), backend)
71
80
  except Exception as exc: # pragma: no cover - import problems are themselves a finding
72
81
  add("browser_backend", False, f"{type(exc).__name__}")
73
82
 
@@ -82,7 +91,7 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
82
91
  for item in ("output_dir", "cache_dir"):
83
92
  value = cfg.get(item) or ""
84
93
  add(item, bool(value), value)
85
- return all(c["status"] == "ok" for c in checks), checks
94
+ return all(c["status"] == "ok" for c in checks), checks, browser
86
95
 
87
96
 
88
97
  def _carsi_school_list(cfg: dict[str, Any]) -> tuple[list[Any], dict[str, Any] | None]:
@@ -168,8 +177,14 @@ def _cmd_setup(args: argparse.Namespace) -> int:
168
177
  save_config(cfg)
169
178
 
170
179
  if args.check:
171
- ready, checks = _environment_check(cfg)
172
- print(json.dumps({"ready": ready, "checks": checks, "settings": _institutional_summary(cfg)}, ensure_ascii=False, indent=2))
180
+ ready, checks, browser = _environment_check(cfg)
181
+ report: dict[str, Any] = {"ready": ready, "checks": checks, "settings": _institutional_summary(cfg)}
182
+ if browser:
183
+ report["browser"] = browser
184
+ if browser.get("outdated"):
185
+ report["warnings"] = [f"Google Chrome {browser['version']} 低于测试过的 {browser['tested']}:"
186
+ "请先更新 Chrome(菜单 → 帮助 → 关于 Google Chrome)"]
187
+ print(json.dumps(report, ensure_ascii=False, indent=2))
173
188
  return 0 if ready else 2
174
189
 
175
190
  print(json.dumps({"updated": changed, "settings": _institutional_summary(cfg)}, ensure_ascii=False, indent=2))
@@ -478,7 +493,7 @@ def main(argv: list[str] | None = None) -> int:
478
493
 
479
494
  cs = sub.add_parser("cold-start", help="forget school sessions in the download browser (lists first)")
480
495
  cs.add_argument("--yes", action="store_true", help="delete without asking")
481
- cs.add_argument("--profile", help="another Camoufox profile directory (default: the download profile)")
496
+ cs.add_argument("--profile", help="another Chrome profile directory (default: the download profile)")
482
497
  cs.add_argument("--cache-dir", help="the cache whose saved cookie files to filter "
483
498
  "(default: the configured one; none with --profile)")
484
499
  cs.set_defaults(func=_cmd_cold_start)