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
@@ -27,23 +27,32 @@ body {
27
27
  font-variant-numeric: tabular-nums;
28
28
  }
29
29
  body.mac { padding: 10px; } /* room for the shadow around a transparent window */
30
- #root { box-sizing: border-box; overflow: hidden; display: inline-block; background: var(--bg); border: 0.5px solid var(--line); }
30
+ #root { position: relative; box-sizing: border-box; overflow: hidden; display: inline-block; background: var(--bg); border: 0.5px solid var(--line); cursor: default; }
31
+ #root.dragging, #root.dragging * { cursor: default; }
31
32
  body.mac #root { box-shadow: var(--shadow); -webkit-backdrop-filter: blur(20px); }
32
33
  #root.pill { border-radius: 999px; }
33
34
  #root.card { border-radius: 16px; width: 330px; box-sizing: border-box; }
34
35
  body:not(.mac) #root { border-radius: 8px; border: none; }
35
36
  #root.warn { background: var(--warn-bg); border-color: var(--warn-line); color: var(--warn); }
36
- .surface { transform-origin: top right; }
37
+ #root.warn::after {
38
+ content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none;
39
+ background: rgba(245, 158, 11, 0.17); z-index: 0;
40
+ box-shadow: inset 0 0 0 2px var(--warn-dot), inset 0 0 16px rgba(217, 119, 6, 0.2);
41
+ opacity: 0.2; animation: breathe 3.6s ease-in-out infinite;
42
+ }
43
+ .surface { position: relative; z-index: 1; transform-origin: top right; }
37
44
  .fade .surface { animation: fade .22s ease-out; }
38
45
  .folder-setting { margin: 12px 0; }
39
46
  .folder-setting .folder-row { display:flex; gap:8px; margin-top:6px; }
40
47
  .folder-setting input { width:0; min-width:0; flex:1; text-align:left; }
41
48
  .folder-setting .hint { margin-top:5px; font-size:11px; color:var(--dim); }
42
- @media (prefers-reduced-motion: reduce) { .fade .surface { animation:none; } }
49
+ @media (prefers-reduced-motion: reduce) { .fade .surface, #root.warn::after { animation:none; } }
43
50
  @keyframes fade { from { opacity: 0; transform: translateY(-2px); } to { opacity: 1; transform: none; } }
44
- @keyframes breathe { 0%, 100% { box-shadow: var(--shadow); } 50% { box-shadow: var(--shadow), 0 0 0 4px rgba(217, 119, 6, 0.25); } }
45
- body.mac #root.warn.new { animation: breathe 1.6s ease-in-out 2; }
51
+ @keyframes breathe { 0%, 100% { opacity: 0.2; } 50% { opacity: 0.85; } }
46
52
 
53
+ .attention-target { appearance: none; box-sizing: content-box; padding: 0; border: none; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
54
+ .pill-prompt { display: inline-flex; align-items: center; gap: 8px; }
55
+ .attention-target:focus-visible { outline: 2px solid var(--warn-dot); outline-offset: -2px; border-radius: 8px; }
47
56
  .pillrow { display: flex; align-items: center; gap: 8px; padding: 5px 14px 5px 6px; white-space: nowrap; height: 28px; }
48
57
  .pillrow.icon-first { padding-left: 12px; }
49
58
  .count { font-weight: 600; font-size: 14px; }
@@ -114,7 +123,7 @@ svg.i { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-widt
114
123
  </style>
115
124
  </head>
116
125
  <body>
117
- <div id="root" class="pill"></div>
126
+ <div id="root" class="pill capsule-drag-region"></div>
118
127
  <script>
119
128
  "use strict";
120
129
  const ICONS = {
@@ -159,36 +168,37 @@ let open = false; // the card is showing
159
168
  let panel = ""; // "", "menu", "report", "confirm", "settings": kept until the user leaves it
160
169
  let flash = { text: "", until: 0 };
161
170
  let settings = null, settingsErrors = {}, notifyOn = true;
162
- let lastHtml = "", lastPrompt = "", hoverTimer = 0, leaveTimer = 0, pollTimer = 0, kinds = [];
171
+ let lastHtml = "", hoverTimer = 0, leaveTimer = 0, pollTimer = 0, kinds = [];
163
172
  const api = () => window.pywebview.api;
164
173
 
165
174
  function pill() {
166
175
  const v = V;
167
176
  if (v.mode === "attention") {
168
177
  const a = v.attention;
169
- return '<div class="pillrow icon-first pywebview-drag-region">' + icon(a.login ? "lock" : "shield")
170
- + "<b>" + esc(a.short) + "</b>" + (a.remaining ? "<span>" + esc(a.remaining) + "</span>" : "") + "</div>";
178
+ return '<div class="pillrow icon-first capsule-drag-region">' + icon(a.login ? "lock" : "shield")
179
+ + '<button type="button" class="pill-prompt attention-target" data-act="show_browser" title="点击切到下载浏览器" aria-label="打开下载浏览器">'
180
+ + "<b>" + esc(a.short) + "</b>" + (a.remaining ? "<span>" + esc(a.remaining) + "</span>" : "") + "</button></div>";
171
181
  }
172
182
  if (v.mode === "done") {
173
183
  // "完成 38/40 2 篇失败": papers saved out of all; a check unless nothing was saved.
174
184
  const good = v.ok > 0 || !v.total;
175
- return '<div class="pillrow icon-first pywebview-drag-region">'
185
+ return '<div class="pillrow icon-first capsule-drag-region">'
176
186
  + icon(good ? "check" : "alert", ' style="color:var(' + (good ? "--ok" : "--bad") + ')"')
177
187
  + '<span class="count">' + (v.total ? esc(v.finished) + " " + v.ok + "/" + v.total : esc(v.headline)) + "</span>"
178
188
  + (v.bad ? '<span class="dim">' + v.bad + " 篇失败</span>" : "") + "</div>";
179
189
  }
180
190
  if (v.mode === "running") {
181
191
  const where = [v.part, v.publisher].filter(Boolean).join(" · ");
182
- return '<div class="pillrow pywebview-drag-region">' + ring(v.pct, 24, 3)
192
+ return '<div class="pillrow capsule-drag-region">' + ring(v.pct, 24, 3)
183
193
  + '<span class="count">' + (v.total ? v.done + "/" + v.total : v.done) + "</span>"
184
194
  + (where ? '<span class="dim">' + esc(where) + "</span>" : "") + '<span class="dot"></span></div>';
185
195
  }
186
- return '<div class="pillrow icon-first pywebview-drag-region"><b>PaperSearch</b><span class="dim">暂无下载任务</span></div>';
196
+ return '<div class="pillrow icon-first capsule-drag-region"><b>PaperSearch</b><span class="dim">暂无下载任务</span></div>';
187
197
  }
188
198
 
189
199
  function header(title, sub, closable) {
190
200
  // Only the ring and the texts drag the window; the buttons stay clickable.
191
- return '<div class="head"><div class="drag pywebview-drag-region">'
201
+ return '<div class="head"><div class="drag capsule-drag-region">'
192
202
  + (V.mode === "running" || V.mode === "attention" ? ring(V.pct, 40, 4, V.pct + "%") : "")
193
203
  + '<div class="text"><div class="title">' + esc(title) + '</div>' + (sub ? '<div class="sub">' + esc(sub) + "</div>" : "") + "</div></div>"
194
204
  + '<button class="iconbtn" data-act="settings" aria-label="设置">' + icon("gear") + "</button>"
@@ -250,14 +260,16 @@ function attentionCard() {
250
260
  const a = V.attention;
251
261
  const sub = [a.remaining ? "剩 " + a.remaining : "", a.login ? "登录后自动继续" : "通过后自动继续",
252
262
  a.more ? "另有 " + a.more + " 项" : ""].filter(Boolean).join(" · ");
253
- let html = '<div class="card-body"><div class="prompt pywebview-drag-region">' + icon(a.login ? "lock" : "shield")
254
- + '<div><div class="t">' + esc(a.message) + '</div><div class="s">' + esc(sub) + "</div></div></div>";
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>";
255
265
  if (panel === "confirm") return html + actionsBlock() + "</div>";
266
+ html += '<div class="actions"><button class="iconbtn" data-act="settings" aria-label="设置">' + icon("gear")
267
+ + '</button><span class="grow"></span>';
256
268
  if (V.actions) {
257
- html += '<div class="actions"><span class="grow"></span><button class="btn" data-act="skip_item">跳过本篇</button>'
258
- + '<button class="btn" data-act="confirm">终止</button></div>';
269
+ html += '<button class="btn" data-act="skip_item">跳过本篇</button>'
270
+ + '<button class="btn" data-act="confirm">终止</button>';
259
271
  }
260
- return html + "</div>";
272
+ return html + "</div></div>";
261
273
  }
262
274
 
263
275
  function doneCard() {
@@ -275,7 +287,7 @@ function idleCard() {
275
287
 
276
288
  function settingsCard() {
277
289
  let html = '<div class="card-body settings"><div class="head"><button class="iconbtn" data-act="back" aria-label="返回">'
278
- + icon("left") + '</button><div class="drag pywebview-drag-region"><div class="text"><div class="title">设置</div></div></div></div>'
290
+ + icon("left") + '</button><div class="drag capsule-drag-region"><div class="text"><div class="title">设置</div></div></div></div>'
279
291
  + '<div class="folder-setting"><label for="download-dir">默认下载文件夹</label><div class="folder-row">'
280
292
  + '<input id="download-dir" type="text" value="' + esc(settings.download_dir || '') + '" placeholder="输入完整路径">'
281
293
  + '<button class="btn" data-act="choose_folder">选择…</button></div>'
@@ -283,21 +295,23 @@ function settingsCard() {
283
295
  + (settingsErrors.download_dir ? '<div class="err">' + esc(settingsErrors.download_dir) + '</div>' : '') + '</div>';
284
296
  for (const f of settings.fields) {
285
297
  html += '<div class="row"><span>' + esc(f.label) + '</span><span><input data-field="' + esc(f.name) + '" value="' + esc(f.value)
286
- + '" inputmode="numeric"> <span class="dim">' + esc(f.unit) + "</span></span></div>"
298
+ + '" aria-label="' + esc(f.label) + '" inputmode="numeric"> <span class="dim">' + esc(f.unit) + "</span></span></div>"
287
299
  + (settingsErrors[f.name] ? '<div class="err">' + esc(settingsErrors[f.name]) + "</div>" : "");
288
300
  }
289
301
  html += '<div class="row"><span>需要处理时发系统通知</span><button class="switch' + (notifyOn ? " on" : "")
290
- + '" data-act="notify" aria-label="系统通知"></button></div>'
302
+ + '" data-act="notify" role="switch" aria-checked="' + notifyOn + '" aria-label="系统通知"></button></div>'
303
+ + '<div class="err" id="notify-error" role="status"></div>'
291
304
  + (settingsErrors[""] ? '<div class="err">' + esc(settingsErrors[""]) + "</div>" : "")
292
305
  + '<div class="foot"><button class="btn link" style="color:var(--dim)" data-act="defaults">恢复默认</button>'
293
306
  + '<button class="btn primary" data-act="save">保存</button></div></div>';
294
307
  return html;
295
308
  }
296
309
 
297
- let lastCls = "", hovering = false, closing = false;
310
+ let lastCls = "", hovering = false, closing = false, dragging = false, endingDrag = false;
311
+ let dragReady = Promise.resolve();
298
312
 
299
313
  function render(force) {
300
- if (closing) return;
314
+ if (closing || dragging) return;
301
315
  if (panel === "settings" && !force) return; // keep what the user is typing
302
316
  let html, shape = "card";
303
317
  if (panel === "settings") html = settingsCard();
@@ -308,11 +322,9 @@ function render(force) {
308
322
  else html = idleCard();
309
323
  const cls = shape + (V.mode === "attention" && panel !== "settings" ? " warn" : "");
310
324
  if (html === lastHtml && cls === lastCls) return;
311
- const fresh = V.mode === "attention" && V.attention.message !== lastPrompt;
312
- lastPrompt = V.mode === "attention" ? V.attention.message : "";
313
325
  const previous = root.getBoundingClientRect();
314
326
  root.style.width = ""; root.style.height = "";
315
- root.className = cls + (fresh ? " new" : "") + (cls !== lastCls ? " fade" : "");
327
+ root.className = cls + " capsule-drag-region" + (cls !== lastCls ? " fade" : "");
316
328
  root.innerHTML = '<div class="surface">' + html + "</div>";
317
329
  lastHtml = html;
318
330
  lastCls = cls;
@@ -331,7 +343,7 @@ async function fit(previous) {
331
343
  const duration = matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 240;
332
344
  const started = performance.now();
333
345
  // One outstanding native resize at a time; a newer layout cancels this animation.
334
- while (generation === fitGeneration) {
346
+ while (generation === fitGeneration && !dragging && !closing) {
335
347
  const t = duration ? Math.min(1, (performance.now() - started) / duration) : 1;
336
348
  const eased = 1 - Math.pow(1 - t, 3);
337
349
  const width = Math.round(from[0] + (to[0] - from[0]) * eased);
@@ -346,10 +358,10 @@ async function fit(previous) {
346
358
  async function tick() {
347
359
  if (closing) return;
348
360
  const before = V.mode;
349
- try { V = await api().state(hovering); } catch (e) { return; }
361
+ try { V = await api().state(hovering || dragging); } catch (e) { return; }
350
362
  // A prompt only turns the capsule amber (with a system notification); hovering opens it.
351
363
  // Once the prompt is handled an open card folds back unless the pointer is on it.
352
- if (before === "attention" && V.mode !== "attention" && !hovering && !panel) open = false;
364
+ if (before === "attention" && V.mode !== "attention" && !hovering && !dragging && !panel) open = false;
353
365
  render(false);
354
366
  }
355
367
 
@@ -361,6 +373,7 @@ async function act(action, target) {
361
373
  case "minimize": open = false; panel = ""; render(true); return api().minimize(); // back as a capsule when restored
362
374
  case "close": closing = true; ++fitGeneration; clearInterval(pollTimer); clearTimeout(hoverTimer); clearTimeout(leaveTimer); return api().request_close(); // no call left waiting on a closed page
363
375
  case "folder": return api().open_folder();
376
+ case "show_browser": return say(await api().act("show_browser", v.current, v.run_id));
364
377
  case "menu": panel = panel === "menu" ? "" : "menu"; return render(true);
365
378
  case "report": if (!kinds.length) kinds = await api().issue_kinds(); panel = "report"; return render(true);
366
379
  case "issue": panel = ""; return say(await api().report(target.dataset.kind, v.current));
@@ -372,7 +385,21 @@ async function act(action, target) {
372
385
  case "settings":
373
386
  settings = await api().settings(); notifyOn = settings.notify; settingsErrors = {}; panel = "settings"; open = true; return render(true);
374
387
  case "back": panel = ""; return render(true);
375
- case "notify": notifyOn = !notifyOn; target.classList.toggle("on", notifyOn); return;
388
+ case "notify": {
389
+ target.disabled = true;
390
+ try {
391
+ const result = await api().set_notifications(!notifyOn);
392
+ if (!result.ok) throw new Error(result.error || "通知设置保存失败");
393
+ notifyOn = result.notify;
394
+ settings.notify = notifyOn;
395
+ target.classList.toggle("on", notifyOn);
396
+ target.setAttribute("aria-checked", String(notifyOn));
397
+ root.querySelector('#notify-error').textContent = "";
398
+ } catch (error) {
399
+ root.querySelector('#notify-error').textContent = error.message || "通知设置保存失败";
400
+ } finally { target.disabled = false; }
401
+ return;
402
+ }
376
403
  case "choose_folder": {
377
404
  const selected = await api().choose_download_directory();
378
405
  if (selected) { settings.download_dir = selected; root.querySelector('#download-dir').value = selected; }
@@ -396,15 +423,68 @@ async function act(action, target) {
396
423
  }
397
424
  }
398
425
 
426
+ const interactive = (target) => target.closest('button, input, select, textarea, a, [contenteditable="true"], [role="button"]');
427
+ root.addEventListener("pointerdown", (event) => {
428
+ if (event.button === 0 && api().activate_on_input) api().activate_on_input();
429
+ if (event.button !== 0 || interactive(event.target)) return;
430
+ dragging = true;
431
+ ++fitGeneration;
432
+ clearTimeout(hoverTimer); clearTimeout(leaveTimer);
433
+ root.classList.add("dragging");
434
+ root.setPointerCapture(event.pointerId); // Keep the release even outside the window.
435
+ dragReady = api().set_dragging(true, event.screenX, event.screenY);
436
+ });
437
+ root.addEventListener("mousedown", (event) => {
438
+ // One mover owns the drag; do not also start pywebview's body mover.
439
+ event.stopPropagation();
440
+ });
441
+ let dragMove = Promise.resolve(), nextDragPoint = null, movingDrag = false;
442
+ async function flushDragMoves() {
443
+ if (movingDrag) return;
444
+ movingDrag = true;
445
+ try {
446
+ await dragReady;
447
+ while (nextDragPoint && dragging) {
448
+ const point = nextDragPoint; nextDragPoint = null;
449
+ await api().move_drag(...point);
450
+ }
451
+ } finally { movingDrag = false; }
452
+ }
453
+ window.addEventListener("pointermove", event => {
454
+ if (!dragging || endingDrag) return;
455
+ nextDragPoint = [event.screenX, event.screenY];
456
+ if (!movingDrag) dragMove = flushDragMoves();
457
+ });
458
+ async function finishDrag() {
459
+ if (!dragging || endingDrag) return;
460
+ endingDrag = true;
461
+ try {
462
+ await dragReady;
463
+ await dragMove;
464
+ await api().set_dragging(false);
465
+ } finally {
466
+ dragging = false; endingDrag = false;
467
+ root.classList.remove("dragging");
468
+ // Events queued by native tracking during a drag must not fold the card.
469
+ render(true);
470
+ setHover(root.matches(':hover'), true);
471
+ }
472
+ }
473
+ window.addEventListener("pointerup", finishDrag);
474
+ window.addEventListener("pointercancel", finishDrag);
475
+ root.addEventListener("lostpointercapture", finishDrag);
476
+ window.addEventListener("blur", finishDrag);
477
+
399
478
  root.addEventListener("click", (event) => {
400
479
  const target = event.target.closest("[data-act]");
401
480
  if (target) { event.stopPropagation(); act(target.dataset.act, target); }
402
481
  });
403
- function setHover(inside) {
482
+ function setHover(inside, force = false) {
404
483
  // Minimize/task transitions can fold the card while the pointer stays inside.
405
- if (hovering === inside && (!inside || open)) return;
484
+ if (!force && hovering === inside && (!inside || open)) return;
406
485
  hovering = inside;
407
486
  clearTimeout(hoverTimer); clearTimeout(leaveTimer);
487
+ if (dragging) return;
408
488
  if (inside) {
409
489
  hoverTimer = setTimeout(() => { if (!open) { open = true; render(true); } }, 100);
410
490
  } else {
@@ -0,0 +1,119 @@
1
+ /* Only loaded in PaperSearch's owned Camoufox process, never in the user's browser.
2
+ * Camoufox's Juggler restores/focuses a native window for every automated click.
3
+ * Suppress that focus while retaining its tab selection and trusted input path.
4
+ * Explicit Page.bringToFront and native user input retain normal activation.
5
+ */
6
+ var { ExtensionCommon } = ChromeUtils.importESModule("resource://gre/modules/ExtensionCommon.sys.mjs");
7
+ var papersearchBackground = class extends ExtensionCommon.ExtensionAPI {
8
+ onStartup() {
9
+ if (!Services.prefs.getBoolPref("papersearch.background.enabled", false)) return;
10
+ this.start().catch(async error => {
11
+ console.error("PaperSearch background helper:", error);
12
+ await IOUtils.writeJSON(PathUtils.join(PathUtils.profileDir, "papersearch-background.json"),
13
+ {ready: false, session: Services.prefs.getStringPref("papersearch.background.session", ""),
14
+ error: String(error).slice(0, 300)});
15
+ });
16
+ }
17
+ onShutdown() { this.restore?.(); }
18
+ async start() {
19
+ const {PageTarget, TargetRegistry} = ChromeUtils.importESModule("chrome://juggler/content/TargetRegistry.js");
20
+ const {PageHandler} = ChromeUtils.importESModule("chrome://juggler/content/protocol/PageHandler.js");
21
+ const activate = PageTarget.prototype.activateAndRun;
22
+ const bringToFront = PageHandler.prototype["Page.bringToFront"];
23
+ if (typeof activate !== "function" || typeof bringToFront !== "function") {
24
+ throw new Error("Unsupported Camoufox activation API");
25
+ }
26
+ const newPage = TargetRegistry.prototype._newPageInternal;
27
+ if (typeof newPage !== "function") throw new Error("Unsupported Camoufox page API");
28
+ const {Helper} = ChromeUtils.importESModule("chrome://juggler/content/Helper.js");
29
+ const helper = new Helper();
30
+ TargetRegistry.prototype._newPageInternal = async function({browserContextId}) {
31
+ const win = Services.wm.getMostRecentWindow("navigator:browser");
32
+ if (!win?.gBrowser) return await newPage.call(this, {browserContextId});
33
+ const browserContext = this.browserContextForId(browserContextId);
34
+ const tab = win.gBrowser.addTab("about:blank", {
35
+ triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
36
+ userContextId: browserContext.userContextId,
37
+ skipAnimation: true,
38
+ });
39
+ let target = this._browserToTarget.get(tab.linkedBrowser);
40
+ while (!target) {
41
+ await helper.awaitEvent(this, TargetRegistry.Events.TargetCreated);
42
+ target = this._browserToTarget.get(tab.linkedBrowser);
43
+ }
44
+ await target.activateAndRun();
45
+ if (browserContext.crossProcessCookie.settings.timezoneId && await target.hasFailedToOverrideTimezone()) {
46
+ throw new Error("Failed to override timezone");
47
+ }
48
+ return target.id();
49
+ };
50
+ const pending = new WeakMap();
51
+ PageTarget.prototype.activateAndRun = async function(...args) {
52
+ const win = this._window;
53
+ let state = pending.get(win);
54
+ if (!state) {
55
+ state = {focus: win.focus, depth: 0};
56
+ pending.set(win, state);
57
+ win.focus = () => {};
58
+ }
59
+ state.depth++;
60
+ try { return await activate.apply(this, args); }
61
+ finally {
62
+ if (--state.depth === 0) {
63
+ win.focus = state.focus;
64
+ pending.delete(win);
65
+ }
66
+ }
67
+ };
68
+ PageHandler.prototype["Page.bringToFront"] = async function(...args) {
69
+ const win = this._pageTarget._window;
70
+ if (win.windowState === win.STATE_MINIMIZED) win.restore();
71
+ (pending.get(win)?.focus || win.focus).call(win);
72
+ return await bringToFront.apply(this, args);
73
+ };
74
+ if (Services.prefs.getBoolPref("papersearch.background.bootstrap", false) &&
75
+ !Services.wm.getMostRecentWindow("navigator:browser")) {
76
+ const {AppConstants} = ChromeUtils.importESModule("resource://gre/modules/AppConstants.sys.mjs");
77
+ const uri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
78
+ uri.data = "about:blank";
79
+ const win = Services.ww.openWindow(null, AppConstants.BROWSER_CHROME_URL, "_blank",
80
+ "chrome,dialog=no,all", uri);
81
+ const focus = win.focus;
82
+ win.focus = () => {};
83
+ const {ctypes} = ChromeUtils.importESModule("resource://gre/modules/ctypes.sys.mjs");
84
+ const user = ctypes.open("user32.dll");
85
+ const getStyle = user.declare("GetWindowLongPtrW", ctypes.winapi_abi, ctypes.intptr_t,
86
+ ctypes.voidptr_t, ctypes.int);
87
+ const setStyle = user.declare("SetWindowLongPtrW", ctypes.winapi_abi, ctypes.intptr_t,
88
+ ctypes.voidptr_t, ctypes.int, ctypes.intptr_t);
89
+ const native = win.docShell.treeOwner.QueryInterface(Ci.nsIBaseWindow);
90
+ const hwnd = ctypes.voidptr_t(ctypes.UInt64(native.nativeHandle));
91
+ const style = Number(getStyle(hwnd, -20).toString());
92
+ setStyle(hwnd, -20, style | 0x08000000); // WS_EX_NOACTIVATE, before the first ShowWindow.
93
+ let observer, timer;
94
+ try {
95
+ await new Promise((resolve, reject) => {
96
+ timer = win.setTimeout(() => reject(new Error("Browser window initialization timed out")), 10000);
97
+ observer = subject => {
98
+ if (subject !== win) return;
99
+ resolve();
100
+ };
101
+ Services.obs.addObserver(observer, "browser-delayed-startup-finished");
102
+ });
103
+ } finally {
104
+ if (observer) Services.obs.removeObserver(observer, "browser-delayed-startup-finished");
105
+ win.clearTimeout(timer);
106
+ setStyle(hwnd, -20, style);
107
+ user.close();
108
+ win.focus = focus;
109
+ }
110
+ }
111
+ await IOUtils.writeJSON(PathUtils.join(PathUtils.profileDir, "papersearch-background.json"),
112
+ {ready: true, session: Services.prefs.getStringPref("papersearch.background.session", "")});
113
+ this.restore = () => {
114
+ TargetRegistry.prototype._newPageInternal = newPage;
115
+ PageTarget.prototype.activateAndRun = activate;
116
+ PageHandler.prototype["Page.bringToFront"] = bringToFront;
117
+ };
118
+ }
119
+ };
@@ -0,0 +1,24 @@
1
+ {
2
+ "manifest_version": 2,
3
+ "name": "PaperSearch background browser",
4
+ "version": "1.0",
5
+ "browser_specific_settings": {
6
+ "gecko": {
7
+ "id": "background@papersearch.local"
8
+ }
9
+ },
10
+ "experiment_apis": {
11
+ "papersearchBackground": {
12
+ "schema": "schema.json",
13
+ "parent": {
14
+ "scopes": [
15
+ "addon_parent"
16
+ ],
17
+ "events": [
18
+ "startup"
19
+ ],
20
+ "script": "api.js"
21
+ }
22
+ }
23
+ }
24
+ }
@@ -0,0 +1 @@
1
+ [{"namespace": "papersearchBackground"}]
@@ -474,13 +474,20 @@ def _camoufox_options(headless: bool, proxy: Any, args: list[str] | None, humani
474
474
  "focusmanager.testmode": True,
475
475
  "dom.disable_window_flip": True,
476
476
  "browser.tabs.loadDivertedInBackground": True,
477
+ "browser.link.open_newwindow": 3,
478
+ "browser.link.open_newwindow.restriction": 0,
477
479
  **(opts.get("firefox_user_prefs") or {}),
480
+ "papersearch.background.enabled": not headless,
481
+ "papersearch.background.bootstrap": False,
478
482
  }
479
483
  if not headless and opts.get("ignore_default_args") is not True:
480
484
  # Playwright adds -foreground to every headed Firefox launch.
481
485
  opts["ignore_default_args"] = list(dict.fromkeys([
482
486
  *(opts.get("ignore_default_args") or []), "-foreground",
483
487
  ]))
488
+ if not headless:
489
+ from .background import options as background_options
490
+ background_options(opts)
484
491
  opts.update(headless=headless, humanize=humanize, proxy=proxy)
485
492
  pinned = pinned_camoufox_dir()
486
493
  if pinned is not None and "executable_path" not in opts:
@@ -556,6 +563,23 @@ def _launch_camoufox_persistent(user_data_dir: str, headless: bool, proxy: Any,
556
563
  from playwright.sync_api import sync_playwright
557
564
 
558
565
  opts = _camoufox_options(headless, proxy, args, humanize, kwargs)
566
+ if os.name == "nt" and not headless:
567
+ # Let the owned helper create the first window without activation.
568
+ from .background import ADDON_DIR, install_startup_helper
569
+ install_startup_helper(Path(user_data_dir))
570
+ opts["addons"] = [p for p in opts["addons"] if str(p) != str(ADDON_DIR)]
571
+ opts["ignore_default_args"] = [*(opts.get("ignore_default_args") or []), "about:blank"]
572
+ opts["args"] = [*(opts.get("args") or []), "-silent"]
573
+ opts["firefox_user_prefs"].update({
574
+ "papersearch.background.bootstrap": True,
575
+ "xpinstall.signatures.required": False,
576
+ "extensions.autoDisableScopes": 0,
577
+ "extensions.enabledScopes": 1,
578
+ "extensions.startupScanScopes": 1,
579
+ # Gecko's first-profile video self-test opens an offscreen dialog
580
+ # that still steals focus before any download window is created.
581
+ "media.sanity-test.disabled": True,
582
+ })
559
583
  pw = sync_playwright().start()
560
584
  try:
561
585
  context = NewBrowser(pw, persistent_context=True, user_data_dir=user_data_dir, **opts)
@@ -629,11 +653,23 @@ def launch_persistent_context(
629
653
  LAST_LAUNCH.update(holder=holder or "free", waited=round(time.monotonic() - waited_from, 1), released=released)
630
654
  if proxy is None:
631
655
  proxy = _proxy_from_config(config)
656
+ from uuid import uuid4
657
+ background_session = uuid4().hex
658
+ if not headless:
659
+ kwargs["firefox_user_prefs"] = {**(kwargs.get("firefox_user_prefs") or {}),
660
+ "papersearch.background.session": background_session}
632
661
  context = _launch_camoufox_persistent(
633
662
  str(profile), headless=headless, proxy=proxy, args=args, humanize=humanize, **kwargs
634
663
  )
635
664
  if not callable(getattr(context, "close", None)):
636
665
  return context
666
+ if not headless:
667
+ from .background import ready as background_ready
668
+ try:
669
+ background_ready(profile, background_session)
670
+ except Exception:
671
+ context.close()
672
+ raise
637
673
  restored = _restore_session_cookies(context, profile)
638
674
  if restored:
639
675
  logger.info("browser_backend: restored %d session cookie(s) from the previous run", restored)
@@ -0,0 +1,68 @@
1
+ """The owned Camoufox's bundled background helper; no native input or global hooks.
2
+
3
+ The helper is an internal Firefox experiment because window activation belongs
4
+ in browser chrome, outside web pages. It has no network/content permissions and
5
+ is not installed in a user's normal browser. Camoufox's version is pinned.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import hashlib
11
+ import io
12
+ import time
13
+ import zipfile
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ ADDON_ID = "background@papersearch.local"
18
+ ADDON_DIR = Path(__file__).resolve().parents[1] / "assets" / "quiet-browser"
19
+
20
+
21
+ def install_startup_helper(profile: Path) -> None:
22
+ """Load before Windows creates its first window, inside the owned profile only."""
23
+ files = {p.name: p.read_bytes() for p in sorted(ADDON_DIR.iterdir()) if p.is_file()}
24
+ version = int.from_bytes(hashlib.sha256(b"".join(files.values())).digest()[:3], "big")
25
+ manifest = json.loads(files["manifest.json"])
26
+ manifest["version"] = f"1.0.{version}"
27
+ files["manifest.json"] = json.dumps(manifest).encode()
28
+ data = io.BytesIO()
29
+ with zipfile.ZipFile(data, "w", zipfile.ZIP_DEFLATED) as archive:
30
+ for name, content in files.items():
31
+ archive.writestr(zipfile.ZipInfo(name), content)
32
+ target = profile / "extensions" / (ADDON_ID + ".xpi")
33
+ content = data.getvalue()
34
+ if target.is_file() and target.read_bytes() == content:
35
+ return
36
+ target.parent.mkdir(parents=True, exist_ok=True)
37
+ temporary = target.with_suffix(".tmp")
38
+ temporary.write_bytes(content)
39
+ temporary.replace(target)
40
+
41
+
42
+ def options(opts: dict[str, Any]) -> None:
43
+ """Configure only this launch; the shared installed browser is never patched."""
44
+ addons = list(opts.get("addons") or [])
45
+ if str(ADDON_DIR) not in addons:
46
+ addons.append(str(ADDON_DIR))
47
+ opts["addons"] = addons
48
+ prefs = opts["firefox_user_prefs"]
49
+ prefs.update({"extensions.experiments.enabled": True,
50
+ "layout.throttled_frame_rate": 60})
51
+
52
+
53
+ def ready(profile: Path, session: str) -> None:
54
+ """Verify before visiting any site; never claim quiet mode if the helper failed."""
55
+ path = profile / "papersearch-background.json"
56
+ deadline = time.monotonic() + 10
57
+ while time.monotonic() < deadline:
58
+ try:
59
+ if path.stat().st_size <= 4096:
60
+ result = json.loads(path.read_text(encoding="utf-8"))
61
+ if isinstance(result, dict) and result.get("session") == session:
62
+ if result.get("ready") is True:
63
+ return
64
+ raise RuntimeError("Camoufox background helper initialization failed")
65
+ except (OSError, ValueError):
66
+ pass # not written yet, or the atomic write is still being replaced
67
+ time.sleep(.05)
68
+ raise RuntimeError("Camoufox background helper did not initialize within 10 seconds")
@@ -64,6 +64,41 @@ def is_turnstile_frame(url: str) -> bool:
64
64
  and "/turnstile/" in parsed.path)
65
65
 
66
66
 
67
+ def is_image_verification(page: Any) -> bool:
68
+ """Image puzzles expose controls but may have no readable instructions."""
69
+ return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
70
+ && !document.querySelector('meta[name="citation_doi"]')
71
+ && [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
72
+ el.getClientRects().length > 0)""") is True
73
+
74
+
75
+ def needs_manual_verification(page: Any) -> bool:
76
+ """A visible reCAPTCHA on an already recognised verification page.
77
+
78
+ Reading a checked box or a response token cannot prove that the enclosing
79
+ page's confirmation was submitted. Leave both actions to the user.
80
+ """
81
+ from playwright.sync_api import Error
82
+
83
+ if is_image_verification(page):
84
+ return True # image/puzzle tasks are always left to the user
85
+ for frame in page.frames:
86
+ parsed = urlsplit(str(frame.url or ""))
87
+ if (parsed.scheme != "https" or parsed.hostname not in {
88
+ "www.google.com", "www.recaptcha.net", "recaptcha.net"}
89
+ or not parsed.path.startswith(("/recaptcha/api2/", "/recaptcha/enterprise/"))):
90
+ continue
91
+ try:
92
+ if frame.frame_element().is_visible():
93
+ return True
94
+ except Error as exc:
95
+ if not any(text in str(exc).lower() for text in (
96
+ "frame was detached", "frame has been detached", "element is not attached",
97
+ "execution context was destroyed")):
98
+ raise
99
+ return False
100
+
101
+
67
102
  def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]) -> Literal[
68
103
  "absent", "clicked", "unavailable"
69
104
  ]:
@@ -49,11 +49,21 @@ def is_challenge_path(url: str) -> bool:
49
49
  return "/crawlprevention/" in path or path == "/captcha" or path.startswith("/captcha/")
50
50
 
51
51
 
52
+ def continues_manual_challenge(title: str) -> bool:
53
+ """An already recognised image challenge keeps its title between puzzle steps."""
54
+ return str(title or "").strip().lower() == "human verification"
55
+
56
+
52
57
  def has_challenge_text(title: str, text: str) -> bool:
53
58
  """Recognise verification wording after explicit access blocks are excluded."""
54
59
  haystack = f"{title} {text}".lower()
55
60
  if str(title or "").strip().lower() == "human verification":
56
61
  body = " ".join(str(text or "").lower().split())
62
+ # Image-only verification screens can expose no body text until the
63
+ # user presses Begin. Keep the exact interstitial title requirement:
64
+ # an article discussing human verification is not a challenge.
65
+ if body in {"", "begin", "begin english"}:
66
+ return True
57
67
  if "complete the security check" in body and "you are not a bot" in body:
58
68
  return True
59
69
  return (any(marker in haystack for marker in _TEXT_MARKERS)