Peach: Local-first video metadata scraper and media manager.
fix: stop remote hover streams and preserve entity context
Peach local maintenance035df0ac74d7
diff --git a/.claude/settings.json b/.claude/settings.jsonindex c29d7fa78..602e46b95 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -1,7 +1,7 @@{"hooks": {- "Stop": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],- "StopFailure": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],- "SessionEnd": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}]+ "Stop": [{"hooks": [{"type": "command", "command": "python", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],+ "StopFailure": [{"hooks": [{"type": "command", "command": "python", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],+ "SessionEnd": [{"hooks": [{"type": "command", "command": "python", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}]}}diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 8a63b195f..63c46fa86 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -171,7 +171,7 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo- 实体页的总数只用于标题和首批分页判断,第二页起请求使用 `count=0`,通过多取一条判断是否还有下一页,不得重复执行全量 `COUNT(*)`。首页无限滚动同样只在首批计算总数。- `q_tops`、艺人索引和实体关联艺人的代表图必须使用单条相关子查询取得,禁止按每个人物再发一次 SQL 的 N+1 实现。- 首页聚合数据在浏览器会话中合并并缓存 30 秒;相邻筛选复用同一进行中的请求。首页、顶部聚合、索引和实体页都有请求序号,迟到的旧响应不得覆盖新状态或再次重建 DOM。-- 无限滚动同一时间只允许一个追加请求;先判断加载锁再递增 offset,避免快速触发时跳页。图片继续使用原生 `loading=lazy`,hover 视频在滚动中必须立即停止并释放 `src`。+- 无限滚动同一时间只允许一个追加请求;先判断加载锁再递增 offset,避免快速触发时跳页。图片继续使用原生 `loading=lazy`。只有本地资源可使用真视频 hover;115/PikPak 等远端源必须使用本地接触印相。滚动、换页、隐藏页面或替换卡片 DOM 时,统一停止 hover 并释放 `src`。- 2026-08-15 实测:Prestige 显示 248 个总结果时首屏只构建 48 张卡片,点击“载入更多”后为 96;艺人索引 120 条约 311 ms,Prestige 第二页 48 条且跳过总数统计约 94 ms。具体耗时随 ledger 和磁盘状态变化,只把批量边界作为稳定契约。- 0.5.4 起,标签筛选行与排序/换批行都常驻顶栏下方,不再按滚动方向隐藏;两行使用半透明黑色磨砂底,分别占位,不能盖住卡片内容。- 首页、女优、厂牌等普通卡片统一由 `wireCards` 调用 `openItem`。只有沉浸/短片等显式传入 `onClick` 的场景允许覆盖。隐藏的 hover 工具必须 `pointer-events:none`,只在实际显示时恢复命中,避免截走海报详情点击。diff --git a/scripts/job_status.py b/scripts/job_status.pyindex b60819b38..4c462891d 100644--- a/scripts/job_status.py+++ b/scripts/job_status.py@@ -27,9 +27,14 @@ import sysfrom datetime import datetime, timezonefrom pathlib import Path+PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))+from peach.config import DATABASE_PATH, GENERATED_DIR-DOC = Path(__file__).resolve().parent.parent / "docs" / "STATUS.md"+DOC = PROJECT_ROOT / "docs" / "STATUS.md"STATE = Path(r"R:\peach-data\state\agent-handoff.json")START = "<!-- job-status:start -->"END = "<!-- job-status:end -->"diff --git a/tests/test_job_status.py b/tests/test_job_status.pyindex 3527c0974..609ca51f3 100644--- a/tests/test_job_status.py+++ b/tests/test_job_status.py@@ -2,6 +2,8 @@ from __future__ import annotationsimport importlib.utilimport json+import subprocess+import sysimport tempfileimport unittestfrom pathlib import Path@@ -15,6 +17,26 @@ SPEC.loader.exec_module(MODULE)class JobStatusTests(unittest.TestCase):+ def test_hook_works_without_a_worktree_virtual_environment(self) -> None:+ settings = json.loads(+ (SCRIPT.parents[1] / ".claude" / "settings.json").read_text(encoding="utf-8")+ )+ commands = [+ hook["command"]+ for event in settings["hooks"].values()+ for matcher in event+ for hook in matcher["hooks"]+ ]+ self.assertEqual(commands, ["python", "python", "python"])+ result = subprocess.run(+ [sys.executable, str(SCRIPT), "--help"],+ cwd=SCRIPT.parents[1],+ capture_output=True,+ text=True,+ check=False,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+def test_hook_event_is_sanitized_and_atomic(self) -> None:with tempfile.TemporaryDirectory() as root:state = Path(root) / "state" / "handoff.json"diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 48fa001ee..9ec132a3b 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -125,6 +125,21 @@ class WebUiSourceTests(unittest.TestCase):self.assertIn(".hovertools button{pointer-events:none", self.page)self.assertIn(".card.longhover .seektools button,.card:hover .later-tools button{pointer-events:auto}", self.page)+ def test_remote_hover_previews_do_not_stream_full_media(self):+ self.assertIn("if(it.location!=='local')", self.page)+ self.assertIn("el.dataset.hoverMode=it.location==='local'?'video':'frames'", self.page)+ self.assertIn("function releaseHoverPreviews(root=document,except=null)", self.page)+ self.assertIn("releaseHoverPreviews(document,el)", self.page)+ self.assertIn("window.addEventListener('pagehide',()=>releaseHoverPreviews())", self.page)+ self.assertIn("if(document.hidden)releaseHoverPreviews()", self.page)+ self.assertIn("if(reset)releaseHoverPreviews($('#grid'))", self.page)+ self.assertIn("releaseHoverPreviews($('#srow'))", self.page)++ def test_detail_close_returns_to_the_collection_that_opened_it(self):+ self.assertIn("detailReturnPath='/'", self.page)+ self.assertIn("if(push)detailReturnPath=location.pathname+location.search", self.page)+ self.assertIn("if(push)route(detailReturnPath||'/')", self.page)+def test_entity_profile_uses_logo_links_without_a_redundant_back_row(self):self.assertIn("const faviconUrl=url=>", self.page)self.assertIn('class="entitylinkicon"', self.page)diff --git a/web/index.html b/web/index.htmlindex cf8b7dff8..a241421de 100644--- a/web/index.html+++ b/web/index.html@@ -786,7 +786,7 @@ let state={loc:initialParams.get('loc')||'local,115',creator:initialParams.get('seed:initialParams.get('seed')||String((Date.now()^(Math.random()*1e9|0))%99991),q:initialParams.get('q')||'',thumb:'1'};$('#q').value=state.q;const REP={}; // 创作者/厂牌 → 代表作 id,用来做圆头像(裁接触印相中心格,不另造图)-let offset=0,total=0,facets=null,current=null;+let offset=0,total=0,facets=null,current=null,detailReturnPath='/';const CACHE={};const cache=items=>{items.forEach(x=>CACHE[x.id]=x);return items};function disposeStage(push=false){@@ -795,7 +795,7 @@ function disposeStage(push=false){if(video._hop)clearInterval(video._hop);video.pause();video.removeAttribute('src');video.load();video.remove()});stage.innerHTML='';stage.hidden=true;document.body.classList.remove('detail-open');current=null;- if(push)route('/');+ if(push)route(detailReturnPath||'/');}const selected=new Set();let selectMode=false,lastSelectedId=null;@@ -835,20 +835,30 @@ $('#density').onclick=()=>{density=density==='big'?'dense':'big';localStorage.setItem('density',density);applyDensity()};applyDensity();-/* ── 悬停即播真视频 —— 只对免费源(本地 / 115)。- 计费源(PikPak)永远不自动拉流,退回接触印相逐格扫视,零流量。 ── */+/* ── 悬停预览:只有本地文件拉真视频。+ 115 / PikPak 等远端源只扫本地接触印相,避免页面移除后继续下载或填满缓存。 ── */const POS=[[0,0],[50,0],[100,0],[0,50],[50,50],[100,50],[0,100],[50,100],[100,100]];+function releaseHoverPreviews(root=document,except=null){+ if(!root||!root.querySelectorAll)return;+ root.querySelectorAll('.card').forEach(card=>{+ if(card!==except&&card._stopHover)card._stopHover()});+ root.querySelectorAll('video.hv').forEach(v=>{+ if(v.closest('.card')===except)return;+ if(v._hop)clearInterval(v._hop);v.pause();v.removeAttribute('src');v.load();v.remove()});+}function wireHover(el,it){const pic=el.querySelector('.pic'); if(!pic)return;+ el.dataset.hoverMode=it.location==='local'?'video':'frames';let longTimer=null;const armLong=()=>{clearTimeout(longTimer);el.classList.add('previewing');longTimer=setTimeout(()=>el.classList.add('longhover'),5000)};const clearLong=()=>{clearTimeout(longTimer);el.classList.remove('previewing','longhover')};- if(it.cost==='metered'){ // 计费源:只换预览图逐格扫视,零流量+ if(it.location!=='local'){ // 远端源:只换预览图逐格扫视,零网络流量const im=pic.querySelector('.poster'); if(!im)return;let t=null,i=4;el.addEventListener('mouseenter',()=>{armLong();t=setInterval(()=>{i=(i+1)%9; im.src=`/poster?id=${it.id}&c=${i}`},430)});- el.addEventListener('mouseleave',()=>{clearLong();clearInterval(t);im.src=`/poster?id=${it.id}&c=4`});+ const stop=()=>{clearLong();clearInterval(t);t=null;im.src=`/poster?id=${it.id}&c=4`};+ el._stopHover=stop;el.addEventListener('mouseleave',stop);return;}let timer=null,v=null;@@ -856,6 +866,7 @@ function wireHover(el,it){if(window.__scrolling)return; // 滚动中不起播,否则每张卡都发请求 → 卡死timer=setTimeout(()=>{if(window.__scrolling)return;+ releaseHoverPreviews(document,el); // 同一时间只保留一个本地视频预览v=document.createElement('video');v.className='hv'; v.muted=true; v.playsInline=true; v.loop=true; v.preload='metadata';v.src='/stream?id='+it.id;@@ -870,12 +881,15 @@ function wireHover(el,it){pic.appendChild(v); v.play().catch(()=>{});},340); // 340ms 防抖,鼠标划过不触发});- el.addEventListener('mouseleave',()=>{+ const stop=()=>{clearLong();- clearTimeout(timer);+ clearTimeout(timer);timer=null;if(v){if(v._hop)clearInterval(v._hop);v.pause();v.removeAttribute('src');v.load();v.remove();v=null}- });+ };+ el._stopHover=stop;el.addEventListener('mouseleave',stop);}+window.addEventListener('pagehide',()=>releaseHoverPreviews());+document.addEventListener('visibilitychange',()=>{if(document.hidden)releaseHoverPreviews()});function cardHtml(it,cls){const ar=(it.width&&it.height)?Math.min(1.9,Math.max(0.5,it.width/it.height)):16/9;@@ -1120,6 +1134,7 @@ function renderCombo(){/* ── 统计与管理 ── */async function openStats(push=true){+ releaseHoverPreviews();if(push)route('/stats');document.body.classList.remove('entity-open');disposeStage(false);@@ -1189,6 +1204,7 @@ function closeStats(push=true){if(push)route('/');$('#stats').hidden=true;let tagIndexMode='alphabet',tagIndexCategory='all',indexRequestSeq=0;const TAG_CATEGORIES=[['all','全部'],['general','内容'],['artist','人物'],['character','角色'],['copyright','作品'],['meta','规格']];async function openIndex(kind,q,push=true){+ releaseHoverPreviews();const requestSeq=++indexRequestSeq;document.body.classList.remove('entity-open');delete $('#index').dataset.entityKind;delete $('#index').dataset.entityName;@@ -1290,6 +1306,7 @@ async function updateEntityCollection(kind,name,entityTag,push=true){renderEntityCollection(kind,name,items,entityTag)}async function openEntity(kind,name,push=true,requestedTag){+ releaseHoverPreviews();const entityTag=requestedTag===undefined? (push?'':new URLSearchParams(location.search).get('tag')||''): requestedTag;@@ -1393,8 +1410,7 @@ window.addEventListener('scroll',()=>{window.__scrolling=true;// 滚动中挂起悬停预览:内容从鼠标下滑过会连续触发 mouseenter,// 每次新建 video 并发 /stream,几十个并发直接把页面拖垮- document.querySelectorAll('video.hv').forEach(v=>{- if(v._hop)clearInterval(v._hop); v.pause(); v.removeAttribute('src'); v.load(); v.remove();});+ releaseHoverPreviews();clearTimeout(scrollT); scrollT=setTimeout(()=>{window.__scrolling=false},180);},{passive:true});@@ -1419,6 +1435,7 @@ async function load(reset){adsBatch=nextAds;cache(adsBatch.items)}const batch=adsBatch.items.slice(offset,offset+60);const html=batch.map(it=>cardHtml(it)).join('');+ if(reset)releaseHoverPreviews($('#grid'));if(reset)$('#grid').innerHTML=html;else $('#grid').insertAdjacentHTML('beforeend',html);$('#count').innerHTML=`疑似广告 ${adsBatch.total} 个 · 当前载入 ${$('#grid').children.length} 个 · 标记后统一复核,不会直接删除`;$('#loadSentinel').hidden=$('#grid').children.length>=adsBatch.items.length;@@ -1432,6 +1449,7 @@ async function load(reset){if(requestSeq!==loadRequestSeq)return;if(reset)total=d.total;const html=d.items.map(it=>cardHtml(it)).join('');+ if(reset)releaseHoverPreviews($('#grid'));if(reset)$('#grid').innerHTML=html; else $('#grid').insertAdjacentHTML('beforeend',html);renderCount();$('#loadSentinel').hidden=$('#grid').children.length>=total;@@ -1463,12 +1481,15 @@ async function loadShorts(requestSeq=loadRequestSeq){if(!d.items.length){$('#shortsSec').hidden=true;return}cache(d.items);$('#shortsSec').hidden=false; $('#shortsN').textContent=d.total.toLocaleString()+' 个';+ releaseHoverPreviews($('#srow'));$('#srow').innerHTML=d.items.map(it=>cardHtml(it,'scard')).join('');wireCards($('#srow'),openTok); wireDrag($('#srow'));}/* ── 就地展开播放 ── */async function openItem(id,push=true){+ releaseHoverPreviews();+ if(push)detailReturnPath=location.pathname+location.search;disposeStage(false);if(push)route('/item/'+id);const it=await api('/api/item?id='+id); if(it.error)return;