papersearch 0.4.6 → 0.4.7

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.
@@ -120,6 +120,14 @@ svg.i { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-widt
120
120
  .prompt svg.i { width: 22px; height: 22px; }
121
121
  .prompt .t { font-weight: 600; font-size: 14px; }
122
122
  .prompt .s { font-size: 12px; }
123
+ .prompt.attention-target { width: 100%; box-sizing: border-box; padding: 12px; border: 1px solid var(--warn-line); border-radius: 13px; background: var(--warn-bg); }
124
+ .attention-copy { flex: 1; min-width: 0; }
125
+ .prompt.attention-target .t { white-space: nowrap; font-size: 15px; }
126
+ .prompt.attention-target .s { white-space: nowrap; margin-top: 3px; font-size: 11px; }
127
+ .attention-arrow { flex: none; font-size: 19px; }
128
+ .attention-head { display: flex; align-items: center; gap: 6px; margin-bottom: 14px; color: var(--fg); }
129
+ .attention-head b { flex: 1; font-size: 12px; }
130
+ #root.card.warn { background: var(--bg); }
123
131
  </style>
124
132
  </head>
125
133
  <body>
@@ -258,10 +266,14 @@ function runningCard() {
258
266
 
259
267
  function attentionCard() {
260
268
  const a = V.attention;
261
- const sub = [a.remaining ? "剩 " + a.remaining : "", a.login ? "登录后自动继续" : "通过后自动继续",
262
- a.more ? "另有 " + a.more + " 项" : ""].filter(Boolean).join(" · ");
263
- let html = '<div class="card-body"><button type="button" class="prompt attention-target" data-act="show_browser" title="点击切到下载浏览器" aria-label="打开下载浏览器">' + icon(a.login ? "lock" : "shield")
264
- + '<div><div class="t">' + esc(a.message) + '</div><div class="s">' + esc(sub) + "</div></div></button>";
269
+ const title = a.short;
270
+ const detail = [a.message, a.remaining ? "剩 " + a.remaining : "",
271
+ a.more ? "另有 " + a.more + " 项" : ""].filter(Boolean).join(" · ");
272
+ let html = '<div class="card-body"><div class="attention-head capsule-drag-region"><b>PaperSearch</b>'
273
+ + '<button class="iconbtn" data-act="minimize" aria-label="最小化">' + icon("minimize") + '</button>'
274
+ + '<button class="iconbtn" data-act="close" aria-label="关闭">' + icon("close") + '</button></div>'
275
+ + '<button type="button" class="prompt attention-target" data-act="show_browser" title="' + esc(detail) + '" aria-label="打开下载浏览器">' + icon(a.login ? "lock" : "alert")
276
+ + '<div class="attention-copy"><div class="t">' + esc(title) + '</div><div class="s">点击打开浏览器,查看并继续</div></div><span class="attention-arrow" aria-hidden="true">›</span></button>';
265
277
  if (panel === "confirm") return html + actionsBlock() + "</div>";
266
278
  html += '<div class="actions"><button class="iconbtn" data-act="settings" aria-label="设置">' + icon("gear")
267
279
  + '</button><span class="grow"></span>';
@@ -367,13 +379,18 @@ async function tick() {
367
379
 
368
380
  function say(text) { flash = { text: text, until: Date.now() + 6000 }; render(true); }
369
381
 
382
+ let inputActivation = Promise.resolve();
370
383
  async function act(action, target) {
371
384
  const v = V;
372
385
  switch (action) {
373
386
  case "minimize": open = false; panel = ""; render(true); return api().minimize(); // back as a capsule when restored
374
387
  case "close": closing = true; ++fitGeneration; clearInterval(pollTimer); clearTimeout(hoverTimer); clearTimeout(leaveTimer); return api().request_close(); // no call left waiting on a closed page
375
388
  case "folder": return api().open_folder();
376
- case "show_browser": return say(await api().act("show_browser", v.current, v.run_id));
389
+ case "show_browser": {
390
+ try { await inputActivation; }
391
+ catch (error) { return say("未能激活进度窗口,请重试"); }
392
+ return say(await api().act("show_browser", v.current, v.run_id));
393
+ }
377
394
  case "menu": panel = panel === "menu" ? "" : "menu"; return render(true);
378
395
  case "report": if (!kinds.length) kinds = await api().issue_kinds(); panel = "report"; return render(true);
379
396
  case "issue": panel = ""; return say(await api().report(target.dataset.kind, v.current));
@@ -425,7 +442,7 @@ async function act(action, target) {
425
442
 
426
443
  const interactive = (target) => target.closest('button, input, select, textarea, a, [contenteditable="true"], [role="button"]');
427
444
  root.addEventListener("pointerdown", (event) => {
428
- if (event.button === 0 && api().activate_on_input) api().activate_on_input();
445
+ if (event.button === 0 && api().activate_on_input) inputActivation = api().activate_on_input();
429
446
  if (event.button !== 0 || interactive(event.target)) return;
430
447
  dragging = true;
431
448
  ++fitGeneration;
@@ -86,10 +86,29 @@ var papersearchBackground = class extends ExtensionCommon.ExtensionAPI {
86
86
  ctypes.voidptr_t, ctypes.int);
87
87
  const setStyle = user.declare("SetWindowLongPtrW", ctypes.winapi_abi, ctypes.intptr_t,
88
88
  ctypes.voidptr_t, ctypes.int, ctypes.intptr_t);
89
+ const setPosition = user.declare("SetWindowPos", ctypes.winapi_abi, ctypes.int,
90
+ ctypes.voidptr_t, ctypes.voidptr_t, ctypes.int, ctypes.int, ctypes.int, ctypes.int, ctypes.uint32_t);
91
+ const setAlpha = user.declare("SetLayeredWindowAttributes", ctypes.winapi_abi, ctypes.int,
92
+ ctypes.voidptr_t, ctypes.uint32_t, ctypes.unsigned_char, ctypes.uint32_t);
93
+ const getAlpha = user.declare("GetLayeredWindowAttributes", ctypes.winapi_abi, ctypes.int,
94
+ ctypes.voidptr_t, ctypes.uint32_t.ptr, ctypes.unsigned_char.ptr, ctypes.uint32_t.ptr);
89
95
  const native = win.docShell.treeOwner.QueryInterface(Ci.nsIBaseWindow);
90
96
  const hwnd = ctypes.voidptr_t(ctypes.UInt64(native.nativeHandle));
91
97
  const style = Number(getStyle(hwnd, -20).toString());
92
- setStyle(hwnd, -20, style | 0x08000000); // WS_EX_NOACTIVATE, before the first ShowWindow.
98
+ const color = ctypes.uint32_t(), alpha = ctypes.unsigned_char(), alphaFlags = ctypes.uint32_t();
99
+ if ((style & 0x00080000) && !getAlpha(hwnd, color.address(), alpha.address(), alphaFlags.address())) {
100
+ user.close();
101
+ throw new Error("Cannot preserve browser window opacity");
102
+ }
103
+ // NOACTIVATE alone still lets Gecko's first ShowWindow cover another
104
+ // app. Keep only the initial, not-yet-painted window transparent until
105
+ // it can be placed behind existing windows, then restore normal styles.
106
+ setStyle(hwnd, -20, style | 0x08080000); // WS_EX_NOACTIVATE | WS_EX_LAYERED
107
+ if (!setAlpha(hwnd, 0, 0, 2)) {
108
+ setStyle(hwnd, -20, style);
109
+ user.close();
110
+ throw new Error("Cannot prepare the browser's background display");
111
+ }
93
112
  let observer, timer;
94
113
  try {
95
114
  await new Promise((resolve, reject) => {
@@ -103,9 +122,13 @@ var papersearchBackground = class extends ExtensionCommon.ExtensionAPI {
103
122
  } finally {
104
123
  if (observer) Services.obs.removeObserver(observer, "browser-delayed-startup-finished");
105
124
  win.clearTimeout(timer);
125
+ const placed = setPosition(hwnd, ctypes.voidptr_t(1), 0, 0, 0, 0, 0x0013); // HWND_BOTTOM; NOSIZE|NOMOVE|NOACTIVATE
126
+ const opacityRestored = !(style & 0x00080000) || setAlpha(hwnd, color.value, alpha.value, alphaFlags.value);
106
127
  setStyle(hwnd, -20, style);
107
128
  user.close();
108
129
  win.focus = focus;
130
+ if (!placed) throw new Error("Cannot place the browser behind existing windows");
131
+ if (!opacityRestored) throw new Error("Cannot restore the browser window opacity");
109
132
  }
110
133
  }
111
134
  await IOUtils.writeJSON(PathUtils.join(PathUtils.profileDir, "papersearch-background.json"),
@@ -80,20 +80,29 @@ class DiagnosticsMixin:
80
80
  "article_open", "institution_federation_selected", "article_access_ready",
81
81
  "pdf_capture_started", "browser_pdf_response_captured", "pdf_saved",
82
82
  "supplements_found", "supplements_saved", "challenge_resolved",
83
+ # The login steps the program takes itself: while it is still
84
+ # choosing the school the page is not waiting for the user (JBJS on
85
+ # OpenAthens, 2026-11-06: five remembered-school clicks in 25 s, no
86
+ # main-frame navigation, and a "no progress" reminder in between).
87
+ "sso_entry_clicked", "openathens_entry", "seamlessaccess_chooser_opened",
88
+ "auto_remembered_entry", "institution_selected", "auto_institution_search",
89
+ "institution_search_submitted", "institution_search_retyped",
90
+ "institution_list_submitted", "institution_continue",
91
+ "login_round_trip_returned", "redirect_page_passed",
83
92
  }:
84
93
  activity.progress()
85
94
  # Only publish fixed phase text; event details can contain signed URLs.
86
95
  report = {
87
96
  "article_open": ("打开论文页面", "opening_article"),
88
- "sso_start": ("机构登录", "waiting_login"),
89
- "institution_federation_selected": ("已进入所选机构认证联盟", "waiting_login"),
90
- "institution_selection_required": ("请在 CARSI 页面自行选择学校并完成登录", "waiting_login"),
91
- "institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "waiting_login"),
92
- "login_state": ("机构登录", "waiting_login"),
97
+ "sso_start": ("正在查找机构登录入口", "checking_access"),
98
+ "institution_federation_selected": ("已进入所选机构认证联盟", "checking_access"),
99
+ "institution_selection_required": ("检查学校选择入口", "checking_access"),
100
+ "institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "checking_access"),
101
+ "login_state": ("检查机构登录页面", "checking_access"),
93
102
  "idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
94
- "login_attempt_started": ("正在尝试机构登录", "waiting_login"),
95
- "login_retry_wait": ("机构登录暂未完成,准备重试", "waiting_login"),
96
- "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "waiting_login"),
103
+ "login_attempt_started": ("正在尝试机构登录", "checking_access"),
104
+ "login_retry_wait": ("机构登录暂未完成,准备重试", "checking_access"),
105
+ "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "checking_access"),
97
106
  "login_stopped": ("机构登录未完成", "route_failed"),
98
107
  "challenge_manual_wait": ("等待人工安全验证", "waiting_verification"),
99
108
  "challenge_wait": ("正在检查安全验证", "checking_access"),
@@ -106,17 +115,19 @@ class DiagnosticsMixin:
106
115
  "browser_pdf_response_captured": ("PDF 已捕获,正在保存", "pdf_captured"),
107
116
  "pdf_saved": ("PDF 已保存,待内容核验", "saved_pending_verification"),
108
117
  }.get(state)
118
+ if state == "login_state" and getattr(result, "_login_attention", ""):
119
+ report = ("等待在浏览器完成机构登录", "waiting_login")
109
120
  if state == "challenge_wait" and detail.startswith("manual "):
110
121
  report = ("等待人工安全验证", "waiting_verification")
111
122
  if state == "login_attempt_started" and detail in {"1/3", "2/3", "3/3"}:
112
- report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "waiting_login")
123
+ report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "checking_access")
113
124
  if state == "login_observed":
114
125
  if detail == "verification":
115
126
  report = ("正在检查安全验证", "checking_access")
116
127
  elif detail == "human_login":
117
128
  report = ("等待在浏览器完成机构登录", "waiting_login")
118
129
  else:
119
- report = ("检查机构登录页面", "waiting_login")
130
+ report = ("检查机构登录页面", "checking_access")
120
131
  # A click can finish after a synchronous PDF response was captured;
121
132
  # capture_started supplies its stage without moving it backwards.
122
133
  if report:
@@ -1281,12 +1281,16 @@ class LoginMixin:
1281
1281
  and not self._personal_login_box(page, url))
1282
1282
 
1283
1283
  def _personal_login_box(self, page: Any, url: str) -> bool:
1284
- """The password field is a personal account's login box on the publisher's
1285
- own article page, nobody typing in it: BMJ shows one next to "Log in via
1286
- institution", and the article page was waited on for 5 minutes as if it
1287
- were the school's login (2026-11-02)."""
1288
- return (self._on_publisher_host(url) and self._is_success_article_url(url) and not self._is_auth_page(url)
1289
- and not self._has_visible_editable_input(page))
1284
+ """A publisher account form can be on an article, login page or SSO host.
1285
+
1286
+ An untouched form next to a separate institutional entry is not the
1287
+ school's credentials step. Preserve a known IdP and any form the user
1288
+ is already filling; return only field presence/activity, never values.
1289
+ """
1290
+ if self._is_idp_host(urlparse(url).netloc) or self._has_visible_editable_input(page):
1291
+ return False
1292
+ return ((self._on_publisher_host(url) and self._is_success_article_url(url) and not self._is_auth_page(url))
1293
+ or isinstance(page.evaluate(self._INSTITUTION_ENTRY_JS), dict))
1290
1294
 
1291
1295
  def _follow_federated_login_option(self, page: Any, result: DownloadResult) -> bool:
1292
1296
  """The publisher's login page offers an institutional option next to the
@@ -187,12 +187,12 @@ class UserWaitMixin:
187
187
  self._raise_on_publisher_access_blocked(tab)
188
188
  result._attention_page = tab
189
189
  activity.observe(tab)
190
- activity.check()
191
190
  if not automatic:
192
191
  deadline = min(deadline, self._wait_deadline(result))
193
192
  if not manual and self._automatic_challenge_step(tab, result, automatic, deadline):
194
193
  page.wait_for_timeout(min(1000, max(0, (deadline - time.time()) * 1000)))
195
194
  continue
195
+ activity.automatic_for(0)
196
196
  result._attention_page = tab
197
197
  if state != shown:
198
198
  if state in ("verification", "login"):
@@ -236,6 +236,7 @@ class UserWaitMixin:
236
236
  self._event(result, "ip_blocked_response", f"{suspect} | no PDF after waiting ({shown or 'nothing shown'})")
237
237
  return False
238
238
  finally:
239
+ activity.automatic_for(0)
239
240
  result._attention_page = None
240
241
  if activity_owned:
241
242
  activity.close()
@@ -386,6 +387,11 @@ class UserWaitMixin:
386
387
  bound = min(deadline, now + remaining) if remaining is not None else deadline
387
388
  attempt["automatic_end"] = bound - manual_reserve
388
389
  automatic_end = min(deadline - manual_reserve, attempt["automatic_end"])
390
+ activity = getattr(result, "_page_activity", None)
391
+ if activity is not None:
392
+ # The separate request watcher also checks idle time during these
393
+ # RPCs. Use the frozen automatic bound; never renew the wait budget.
394
+ activity.automatic_for(automatic_end - now)
389
395
  if now >= automatic_end or (attempt["attempts"] >= 3 and now >= attempt["retry_at"]):
390
396
  return False
391
397
  if challenge_interaction.needs_manual_verification(page):
@@ -403,6 +409,8 @@ class UserWaitMixin:
403
409
  if outcome != "absent":
404
410
  attempt["attempts"] += 1
405
411
  attempt["retry_at"] = time.time() + 3
412
+ if outcome == "clicked" and activity is not None:
413
+ activity.progress(page)
406
414
  self._event(result, "challenge_interaction",
407
415
  f"checkbox {outcome}; attempt {attempt['attempts']}/3; awaiting verification")
408
416
  return time.time() < automatic_end
@@ -440,8 +448,10 @@ class UserWaitMixin:
440
448
  if time.time() >= deadline:
441
449
  break
442
450
  result._attention_page = page
443
- activity.check()
444
451
  auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
452
+ if not auto_pending:
453
+ activity.automatic_for(0)
454
+ activity.check()
445
455
  if not auto_pending and not manual:
446
456
  result._attention_page = page
447
457
  interaction.enter_context(watchdog.pause_operation())
@@ -478,6 +488,7 @@ class UserWaitMixin:
478
488
  self._wait_ran_out(result)
479
489
  return passed
480
490
  finally:
491
+ activity.automatic_for(0)
481
492
  if verification_wait is not None:
482
493
  excluded = max(0, verification_wait.close() - verification_deadline)
483
494
  outer_wait = getattr(result, "_login_wait", None)
@@ -29,6 +29,7 @@ class PageActivity:
29
29
  self._doi = doi
30
30
  self._shown = False
31
31
  self._transfers = 0
32
+ self._automatic_until = 0.0
32
33
  self.closed = False
33
34
  self.page = None
34
35
  self._pages: dict[int, tuple[Any, dict]] = {}
@@ -48,6 +49,18 @@ class PageActivity:
48
49
  progress_reporter.clear_attention(self._key)
49
50
  self._shown = False
50
51
 
52
+ def automatic_for(self, seconds: float) -> None:
53
+ """Defer idle reminders until the caller's existing automatic deadline.
54
+
55
+ This is a finite lease, not progress: polling must pass only the time
56
+ remaining on the original bound. Zero releases it at manual handoff.
57
+ The watcher can still remind if the browser call never returns.
58
+ """
59
+ with self._lock:
60
+ self._automatic_until = self._clock() + max(0.0, seconds)
61
+ if seconds > 0:
62
+ self._clear()
63
+
51
64
  def check(self) -> None:
52
65
  """Thread safe; never inspect a page or interrupt an in-flight operation."""
53
66
  with self._lock:
@@ -59,6 +72,7 @@ class PageActivity:
59
72
  self._last_progress = self._clock()
60
73
  self._clear()
61
74
  elif (not self._shown and not self._transfers
75
+ and self._clock() >= self._automatic_until
62
76
  and not self._navigation_loading()
63
77
  and self._clock() - self._last_progress >= self.after):
64
78
  progress_reporter.set_attention(
@@ -30,8 +30,6 @@ STAGE_STEP = {
30
30
  "waiting_verification": (1, "等待验证"), "route_failed": (1, "换一条路"),
31
31
  "fetching_pdf": (2, "取 PDF"), "pdf_captured": (3, "核对 PDF"), "saved_pending_verification": (3, "已保存"),
32
32
  }
33
- # What a needs-you prompt asks, short enough for the collapsed capsule.
34
- ATTENTION_SHORT = {"waiting_login": "请登录学校", "waiting_verification": "请完成验证"}
35
33
  # The answer a button gets in the window, before the download confirms it.
36
34
  ACTION_FEEDBACK = {
37
35
  "show_browser": "正在切到下载浏览器",
@@ -201,10 +199,13 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
201
199
  prompt = None
202
200
  if attention:
203
201
  item = attention[-1]
204
- message = str(item.get("message") or "请在浏览器窗口完成安全验证")
205
- stage = str(state.get("stage") or "")
206
- short = ATTENTION_SHORT.get(stage) or (
207
- "请登录学校" if "登录" in message else "请完成验证" if "验证" in message else "需要你处理")
202
+ message = str(item.get("message") or "请查看浏览器,可能需要手动操作")
203
+ # The surrounding SSO/verification stage is not evidence of the action
204
+ # being requested. In particular, an idle page is not a school login.
205
+ short = ("页面暂时无进展" if "无进展" in message or "没有进展" in message else
206
+ "请选择学校" if "选择学校" in message else
207
+ "请登录学校" if "登录" in message else
208
+ "请完成验证" if "验证" in message else "需要你处理")
208
209
  deadline = item.get("deadline")
209
210
  remaining = (max(0, int(deadline - now))
210
211
  if isinstance(deadline, (int, float)) and not isinstance(deadline, bool) else None)
@@ -17,7 +17,7 @@ export const CARSI_DOWNLOAD_TIMEOUT_MS = 1_200_000;
17
17
  export const CARSI_CLEANUP_TIMEOUT_MS = 5_000;
18
18
  const CARSI_BACKEND_SOURCE = "carsi";
19
19
  // MCP clientInfo is informational only; keep in step with package.json on release.
20
- const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.6";
20
+ const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.7";
21
21
  const NO_BATCH_SUPPORT = {
22
22
  downloadFields: false,
23
23
  supplementsField: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "papersearch",
3
- "version": "0.4.6",
3
+ "version": "0.4.7",
4
4
  "description": "PaperSearch: an agent-friendly command for searching and downloading academic papers from multiple sources.",
5
5
  "main": "dist/cli.js",
6
6
  "type": "module",