Peach: Local-first video metadata scraper and media manager.
fix(web): 数据管理页去掉重复入口条,处理失败的问题清单收进折叠
longmeidaoc1d60d950b79
diff --git a/docs/STATUS.md b/docs/STATUS.mdindex a9263031d..cc7172e1d 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -30,7 +30,7 @@- 前端按 ADR-0022 以 Preact island 逐岛迁往 `frontend/`(Vite + TypeScript),产物 `web/dist/peach-ui.js` 进 Git、经 `/dist/{name}` 提供,`/quality-goals` 已迁;改前端需 Node 24+,见 `docs/FRONTEND.md`。- 本机运行 Python 3.14;`requires-python` 下限 3.12,GitHub Actions 同时测 3.12 与 3.14;Windows FFmpeg/ffprobe 位于 `peach-data/tools/ffmpeg`,macOS 走 PATH。- 发行名 `peach`,目录名 `peach-app`;Windows venv 已按发行名重装。macOS 落后 master 一组有顺序的操作(待办「待执行的操作」第 30 条),做完之前别重启菜单栏:没有口令的 `peach serve --host 0.0.0.0` 会拒绝启动。-- 扫描与采集任务显示当前项目、动作与等待时长;无进展 120 秒先在页面预警,单项外部动作(资料 90 秒、封面 240 秒)超预算只跳过当前项目并计入可重试;「重试未完成项」按原任务失败集合重试。完整问题写入 `state/library-processing-<job_id>.issues.jsonl`,接口按 `job_id` 分页读取;旧任务的问题列表读取时投影成计数与前 20 条。已部署并核对。+- 扫描与采集显示当前项目、动作与等待时长;无进展 120 秒页面预警,单项外部动作(资料 90 秒、封面 240 秒)超预算只跳过该项并计入可重试;「重试未完成项」按原任务失败集合重试。完整问题写入 `state/library-processing-<job_id>.issues.jsonl`,每条带标题与路径,接口按 `job_id` 分页读取;页面把前 20 条与日志地址收在错误提示的折叠里。已部署核对。## 批处理进度diff --git a/frontend/src/board-state-preview.tsx b/frontend/src/board-state-preview.tsxindex d2777ddaa..5f61a678e 100644--- a/frontend/src/board-state-preview.tsx+++ b/frontend/src/board-state-preview.tsx@@ -23,7 +23,8 @@ function StatePreview() {stage:state==='preparing'?'正在准备扫描':state==='retrying'?'等待来源响应 · 8 秒后重试':'正在整理资料',checked:value,...(state==='preparing'?{}:{total:100}),error:state==='failed'?'来源暂时不可用,请重试未完成项':'',issue_count:state==='failed'?1:0,- issue_preview:state==='failed'?[{asset_id:null,message:'来源连接超时'}]:[],+ issue_preview:state==='failed'?[{asset_id:null,title:'本地磁盘',path:'R:\\Media',message:'来源连接超时'}]:[],+ issues_log:state==='failed'?'peach-data\\state\\library-processing-preview.issues.jsonl':'',retryable_asset_ids:state==='failed'?[7]:[]};const problem=state==='disconnected'?'连接中断,正在重新读取处理进度':'';return <main class="board-state-preview">diff --git a/frontend/src/islands/library-processing.tsx b/frontend/src/islands/library-processing.tsxindex 26bd592bc..34f3320e1 100644--- a/frontend/src/islands/library-processing.tsx+++ b/frontend/src/islands/library-processing.tsx@@ -5,10 +5,10 @@ import { jobActivityHtml, watchJob } from '../jobs';import type { JobState } from '../jobs';import type { IslandState } from '../islands';-export interface LibraryProcessingIssue { asset_id: number | null; message: string }+export interface LibraryProcessingIssue { asset_id: number | null; title?: string; path?: string; message: string }export interface LibraryProcessingData extends JobState {stage?: string; scanned?: number; identified?: number; candidates?: number; covers?: number;- issue_count?: number; issue_preview?: LibraryProcessingIssue[];+ issue_count?: number; issue_preview?: LibraryProcessingIssue[]; issues_log?: string;issues_truncated?: boolean; retryable_asset_ids?: number[];current_asset_id?: number | null; current_asset_name?: string; current_action?: string;current_started_at?: number; last_progress_at?: number; stalled?: boolean; waited_seconds?: number;@@ -88,6 +88,19 @@ export function LibraryProcessing({ data, error, toast, onComplete, mode, monito的下场,挂在卡片外面,和链接管理、资源同步那两块同一个写法。 */const issues = state.issue_preview || [];const retryable = state.status === 'failed' && !!state.retryable_asset_ids?.length;+ /* 问题清单收进那条错误 Note 的折叠里:卡片下面先看到的应该是「这一趟怎么了」,+ 逐条明细是要展开才读的东西。完整清单在状态给出的日志文件里,界面只留前 20 条。 */+ const issueDetails = state.status === 'failed' && issues.length ? {+ label: state.issues_truncated+ ? `问题清单:共 ${state.issue_count || 0} 项,展开查看前 ${issues.length} 项`+ : `问题清单:共 ${state.issue_count || 0} 项`,+ items: issues.map(issue => ({+ label: issue.title || (issue.asset_id ? `视频 ${issue.asset_id}` : '媒体来源'),+ href: issue.asset_id ? `/item/${issue.asset_id}` : '',+ note: issue.message, hint: issue.path || '',+ })),+ footnote: state.issues_log ? `完整记录:${state.issues_log}` : '',+ } : null;return <><section class="cleanupfieldset" data-geist-fieldset aria-labelledby="cleanupScrapingTitle"><div class="geist-fieldset-content library-processing">@@ -106,14 +119,7 @@ export function LibraryProcessing({ data, error, toast, onComplete, mode, monito{state.status === 'running' && state.stalled && <div class="library-processing-stalled" dangerouslySetInnerHTML={{ __html: noteHtml('这个项目处理时间较长,暂时没有新进展。可以继续等待,或在任务结束后重试未完成项。',{ variant: 'warning', label: '处理较慢', filled: true }) }} />}- {(problem || state.status === 'failed') && <div role="alert" onClick={event=>{if((event.target as HTMLElement).closest('[data-note-action]'))retry();}} dangerouslySetInnerHTML={{ __html: noteHtml(problem || state.error || '处理未完成,请重试', { variant: 'error',filled:true,actionLabel:retryable?'重试未完成项':'' }) }} />}- {state.status === 'failed' && !!issues.length && <div class="library-processing-issues-wrap">- <p class="library-processing-issues-summary">{state.issues_truncated- ? `共 ${state.issue_count || 0} 项问题,以下为前 ${issues.length} 项`- : `共 ${state.issue_count || 0} 项问题`}</p>- <ul class="library-processing-issues">{issues.map(issue =>- <li>{issue.asset_id ? <a href={`/item/${issue.asset_id}`}>查看视频</a> : null}{issue.asset_id ? ':' : ''}{issue.message}</li>)}</ul>- </div>}+ {(problem || state.status === 'failed') && <div role="alert" onClick={event=>{if((event.target as HTMLElement).closest('[data-note-action]'))retry();}} dangerouslySetInnerHTML={{ __html: noteHtml(problem || state.error || '处理未完成,请重试', { variant: 'error',filled:true,actionLabel:retryable?'重试未完成项':'',details:issueDetails }) }} />}{receipt && <div class="library-processing-result" dangerouslySetInnerHTML={{ __html: noteHtml(`已扫描 ${state.scanned || 0} 个文件,识别 ${state.identified || 0} 个番号,整理 ${state.candidates || 0} 组资料候选。`, { variant: 'success', label: '处理完成' }) }} />}</div></>;diff --git a/frontend/src/legacy/ui.d.ts b/frontend/src/legacy/ui.d.tsindex 4670ad504..b7a5e4f2f 100644--- a/frontend/src/legacy/ui.d.ts+++ b/frontend/src/legacy/ui.d.ts@@ -40,6 +40,12 @@ export declare function noteHtml(className?: string;size?: 'small' | 'medium';actionLabel?:string; filled?: boolean;+ /** 逐条明细,收在 Note 里默认折叠的 details;`hint` 放路径这类次要标注。 */+ details?: {+ label: string;+ items: { label: string; href?: string; note?: string; hint?: string }[];+ footnote?: string;+ } | null;},): string;export declare function projectBannerHtml(message:string,options:{variant?:'gray'|'success'|'warning'|'error';href:string;label:string;value?:number;max?:number}):string;diff --git a/frontend/test/library-processing.test.tsx b/frontend/test/library-processing.test.tsxindex 57b546ffc..d1023e787 100644--- a/frontend/test/library-processing.test.tsx+++ b/frontend/test/library-processing.test.tsx@@ -49,7 +49,7 @@ it('运行态显示当前项目、动作与等待时长,stalled 只提示不expect(host.textContent).toContain('处理时间较长');expect(host.querySelector('[data-note-action]')).toBeNull();});-it('失败时列出问题总数并只提交失败项重试', async () => {+it('失败时把问题清单折叠进错误提示并只提交失败项重试', async () => {const calls:{url:string,init:RequestInit|undefined}[]=[];vi.stubGlobal('fetch',vi.fn(async (url:string, init?:RequestInit)=>{calls.push({url,init});@@ -57,9 +57,17 @@ it('失败时列出问题总数并只提交失败项重试', async () => {}));host=document.createElement('div');document.body.append(host);const data={status:'failed',job_id:'one',error:'2 项需要处理',issue_count:23,- issue_preview:[{asset_id:7,message:'未识别到番号'}],issues_truncated:true,retryable_asset_ids:[7,8]};+ issues_log:'C:\\peach-data\\state\\library-processing-one.issues.jsonl',+ issue_preview:[{asset_id:7,title:'样品.mp4',path:'R:\\Media\\样品.mp4',message:'未识别到番号'}],+ issues_truncated:true,retryable_asset_ids:[7,8]};await act(async()=>{render(h(LibraryProcessing,{data,error:'',toast:vi.fn()}),host)});- expect(host.textContent).toContain('共 23 项问题,以下为前 1 项');+ const details=host.querySelector<HTMLDetailsElement>('.geist-note .geist-note-details')!;+ expect(details.open).toBe(false);+ expect(details.querySelector('summary')?.textContent).toBe('问题清单:共 23 项,展开查看前 1 项');+ expect(details.querySelector('li a')?.getAttribute('href')).toBe('/item/7');+ expect(details.querySelector('li')?.textContent).toContain('样品.mp4');+ expect(details.querySelector('li code')?.textContent).toBe('R:\\Media\\样品.mp4');+ expect(details.querySelector('p')?.textContent).toContain('C:\\peach-data\\state\\library-processing-one.issues.jsonl');expect(host.textContent).toContain('重试未完成项');expect(host.querySelector('.geist-fieldset-footer .geist-button.primary')).toBeNull();await act(async()=>{host.querySelector<HTMLButtonElement>('[data-note-action]')!.click();await new Promise(resolve=>setTimeout(resolve,0));});diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex 047f5223c..2e302723a 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -113,7 +113,8 @@ def decorate(state, *, now=None):legacy = state.pop('issues', None)if legacy and 'issue_count' not in state:state['issue_count'] = len(legacy)- state['issue_preview'] = [dict(asset_id=row.get('asset_id'), message=str(row.get('message') or ''))+ state['issue_preview'] = [dict(asset_id=row.get('asset_id'), title=str(row.get('title') or ''),+ path=str(row.get('path') or ''), message=str(row.get('message') or ''))for row in legacy[:ISSUE_PREVIEW_LIMIT]]state['issues_truncated'] = len(legacy) > ISSUE_PREVIEW_LIMITif state.get('status') != 'running':@@ -220,6 +221,9 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='cocurrent_started_at=None, current_deadline_at=None,started_at=time.time(), error='')log_path = issues_path(config, state['job_id'])+ # 界面只展示前 20 条,完整清单在这个文件里;地址跟着状态一起给出,+ # 不让人按 job_id 自己去拼路径。+ state['issues_log'] = str(log_path)for stale in log_path.parent.glob('library-processing-*.issues.jsonl'):stale.unlink(missing_ok=True)@@ -233,14 +237,24 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co_save(path, state)report(dict(state))- def issue(asset_id, message, *, action='', retryable=False):+ def issue(asset, message, *, action='', retryable=False):+ """`asset` 是这一项的馆藏行,来源离线一类与具体项目无关的问题给 `None`。++ 每条问题都带上标题与路径:光有「未识别到番号」和一个链接,人得逐个点开+ 才知道是哪个文件,而路径才是去磁盘上确认或改名时真正要用的东西。+ """+ asset = asset or {}+ asset_id = asset.get('id')+ title = str(asset.get('catalog_title') or '') or Path(str(asset.get('name') or '')).name+ asset_path = str(asset.get('path') or '')with open(log_path, 'a', encoding='utf-8') as handle:- handle.write(json.dumps({'asset_id': asset_id, 'message': message,- 'failed_action': action, 'retryable': retryable,+ handle.write(json.dumps({'asset_id': asset_id, 'title': title, 'path': asset_path,+ 'message': message, 'failed_action': action, 'retryable': retryable,'last_failed_at': time.time()}, ensure_ascii=False) + '\n')state['issue_count'] += 1if len(state['issue_preview']) < ISSUE_PREVIEW_LIMIT:- state['issue_preview'].append(dict(asset_id=asset_id, message=message))+ state['issue_preview'].append(dict(asset_id=asset_id, title=title,+ path=asset_path, message=message))else:state['issues_truncated'] = Trueif retryable and asset_id is not None and asset_id not in state['retryable_asset_ids']:@@ -297,7 +311,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='cocurrent_deadline_at=None)video = translate_ledger_path(row['path'])if not video.is_file():- issue(row['id'], '媒体文件不可访问', action='reading_local', retryable=True)+ issue(row, '媒体文件不可访问', action='reading_local', retryable=True)continuecode = row['code'] or release_code_from_filename(row['name'])payload = None@@ -309,7 +323,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='coraise ValueError('文件名与 NFO 番号冲突,请复核')code = code or payload['id']except (OSError, ValueError, ET.ParseError) as error:- issue(row['id'], str(error), action='reading_local')+ issue(row, str(error), action='reading_local')continueif not code and not payload:# 番号认不出不影响本地封面:正片旁边的同名 PNG/JPG 就是它的海报,@@ -319,14 +333,14 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='covideo, f"{row['id']}_4",config.directory('generated') / 'posters'))except (OSError, ValueError):- issue(row['id'], '本地封面无法读取', action='reading_local', retryable=True)- issue(row['id'], '未识别到番号,请在详情中补充资料', action='reading_local')+ issue(row, '本地封面无法读取', action='reading_local', retryable=True)+ issue(row, '未识别到番号,请在详情中补充资料', action='reading_local')continueif code:try:code = validate_provider_code(code)except ValueError:- issue(row['id'], '番号格式无效,请复核影片资料', action='reading_local')+ issue(row, '番号格式无效,请复核影片资料', action='reading_local')continueif code and not row['code']:with closing(sqlite3.connect(db_path, timeout=30)) as connection, connection:@@ -336,7 +350,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='coposter_root = cover_root if code else config.directory('generated') / 'posters'state['covers'] += int(_local_poster(video, code or f"{row['id']}_4", poster_root, payload))except (OSError, ValueError):- issue(row['id'], '本地封面无法读取', action='reading_local', retryable=True)+ issue(row, '本地封面无法读取', action='reading_local', retryable=True)entries = []if payload:evidence_path = config.directory('sources') / 'library-metadata' / (hashlib.sha256(raw).hexdigest() + '.nfo')@@ -367,10 +381,10 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='coentries.append(('r18dev', external, evidence_path))except DeadlineExceeded:reset_provider()- issue(row['id'], '外部资料在预算时间内未取得,可稍后重试',+ issue(row, '外部资料在预算时间内未取得,可稍后重试',action='querying_metadata', retryable=True)except Exception:- issue(row['id'], '外部资料未取得,请检查采集来源后重试',+ issue(row, '外部资料未取得,请检查采集来源后重试',action='querying_metadata', retryable=True)if jav_catalog and not (cover_root / (code + '.jpg')).is_file():budget = ACTION_BUDGETS['fetching_cover']@@ -384,10 +398,10 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='codeadline=time.monotonic() + budget))except DeadlineExceeded:reset_provider()- issue(row['id'], '封面在预算时间内未取得,可稍后重试',+ issue(row, '封面在预算时间内未取得,可稍后重试',action='fetching_cover', retryable=True)except Exception:- issue(row['id'], '封面未取得,请检查采集来源后重试',+ issue(row, '封面未取得,请检查采集来源后重试',action='fetching_cover', retryable=True)update(stage='保存资料候选', current_action='writing_candidates',current_started_at=time.time(), current_deadline_at=None)diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.pyindex 57635349f..8327b014a 100644--- a/src/peach/web_library_processing.py+++ b/src/peach/web_library_processing.py@@ -11,7 +11,14 @@ def _current(contract):def q_library_processing(contract, _args):- return decorate(_current(contract))+ state = decorate(_current(contract))+ # 上一趟任务的状态文件里没有这个字段,而它那份完整清单还在磁盘上:按 job_id+ # 推出地址补回去,界面才有得可给。+ if state.get('issue_count') and state.get('job_id') and not state.get('issues_log'):+ path = issues_path(settings_file.active(), str(state['job_id']))+ if path.is_file():+ state['issues_log'] = str(path)+ return statedef q_library_processing_issues(contract, args):diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.pyindex b223b2e8f..46b046621 100644--- a/tests/test_metadata_library.py+++ b/tests/test_metadata_library.py@@ -276,6 +276,40 @@ class LibraryWatchdogTests(unittest.TestCase):logged = [json.loads(line) for line in log.read_text(encoding='utf-8').splitlines() if line]self.assertEqual(page['rows'], logged[20:25])+ def test_status_read_recovers_the_log_path_left_by_an_earlier_job(self):+ """上一趟任务的状态文件里没有这个字段,它那份完整清单却还在磁盘上。"""+ from peach.web_library_processing import q_library_processing+ config = self._config(self.root / 'media')+ log = issues_path(config, 'old')+ log.parent.mkdir(parents=True, exist_ok=True)+ log.write_text(json.dumps({'asset_id': 1, 'message': '未识别到番号'}) + '\n', encoding='utf-8')+ state_path(config).write_text(json.dumps({'status': 'failed', 'job_id': 'old', 'issue_count': 1}),+ encoding='utf-8')+ contract = Mock()+ contract.library_processing_job.snapshot.return_value = None+ with patch('peach.web_library_processing.settings_file.active', return_value=config):+ self.assertEqual(q_library_processing(contract, {})['issues_log'], str(log))++ @unittest.skipUnless(os.name == 'nt', '真实声明根使用 Windows 盘符')+ def test_each_issue_names_the_item_its_path_and_where_the_full_log_is(self):+ """一句「未识别到番号」加一个链接,是哪个文件得逐个点开才知道;改名或去磁盘上+ 确认时要用的是路径。完整清单的地址跟着状态一起给出,不让人按 job_id 自己去拼。+ """+ media = self.root / 'media'+ media.mkdir()+ (media / '样品.mp4').write_bytes(b'video')+ db = fresh_ledger(self.root)+ config = self._config(media)+ result = process_library(config, db, self.root / 'generated', self.root / 'covers')+ preview = result['issue_preview'][0]+ self.assertEqual(preview['title'], '样品.mp4')+ self.assertTrue(preview['path'].endswith('样品.mp4'), preview['path'])+ self.assertEqual(result['issues_log'], str(issues_path(config, result['job_id'])))+ log = issues_path(config, result['job_id'])+ logged = json.loads(log.read_text(encoding='utf-8').splitlines()[0])+ self.assertEqual(logged['title'], '样品.mp4')+ self.assertEqual(logged['path'], preview['path'])+def test_stalled_warning_never_flips_a_live_task_to_failed(self):config = self._config(self.root / 'media')path = state_path(config)@@ -313,7 +347,8 @@ class LibraryWatchdogTests(unittest.TestCase):self.assertNotIn('issues', state)self.assertEqual(state['issue_count'], 25)self.assertEqual(len(state['issue_preview']), 20)- self.assertEqual(state['issue_preview'][0], {'asset_id': 1, 'message': '未识别到番号'})+ self.assertEqual(state['issue_preview'][0],+ {'asset_id': 1, 'title': '', 'path': '', 'message': '未识别到番号'})self.assertTrue(state['issues_truncated'])@unittest.skipUnless(os.name == 'nt', '真实声明根使用 Windows 盘符')diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 359470766..35eb2c76d 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -4405,12 +4405,12 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("const stat=(label,value,note='')=>")self.assertPageContains(".map(([kind,count])=>stat(KINDS[kind]||kind,Number(count).toLocaleString())).join('');")self.assertPageContains(".linkstats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr))")- self.assertPageContains('<div class="linkhosts"><span>来得最多的站点</span>')+ self.assertPageContains('<div class="linkhosts"><span>主要站点</span>')# 类型名要能被没读过代码的人读懂:`catalog` 收的是 DMM、MGStage、JavLibrary# 这类作品检索站,`source_reference` 是这条资料的出处。self.assertPageContains("catalog:'作品资料站'")self.assertPageContains("source_reference:'资料出处'")- self.assertPageContains("挂在 ${info.entities.toLocaleString()} 位女优、厂牌或系列名下")+ self.assertPageContains("分布在 ${info.entities.toLocaleString()} 个女优、厂牌与系列")def test_taste_page_combines_private_exports_and_peach_behavior(self):self.assertRoute('/taste', "openTaste(push)", "section:'taste'")@@ -7257,8 +7257,8 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("async function openDataCleanup(push=true)")self.assertPageContains("route('/data-cleanup')")self.assertPageContains("${(sources.sources||[]).some(source=>['local','115','pikpak'].includes(source.location)&&source.roots?.length)?resourceSyncMarkup():''}")- self.assertPageContains("fieldsetTitle('resourceBoxTitle','文件与记录是否对得上')")- self.assertPageContains("照着馆藏里的记录,去本地磁盘和网盘上找对应的文件")+ self.assertPageContains("fieldsetTitle('resourceBoxTitle','文件与记录核对')")+ self.assertPageContains("按馆藏记录逐条查找本地磁盘与网盘上的文件")self.assertPageContains("cloudPreferenceLocations(g.files,d.cloudLocations||[])")self.assertPageContains("Boolean(s.history_sources||d.updated_at),localStorage.getItem(TASTE_GUIDE_KEY)==='1')")self.assertPageContains('wireTasteHistoryGuide(root,localStorage);')@@ -8139,6 +8139,23 @@ class WebUiSourceTests(unittest.TestCase):# 一格里空着的第二行照样占一条轨道,卡片底下会凭空多出一个间距。self.assertIn(".library-processing-outcome:empty{display:none}", board)+ def test_a_failed_scan_folds_its_issue_list_into_the_error_note(self):+ """处理失败先给一句结论,逐条明细收在这条 Note 自己的 details 里,默认折叠。++ 一次扫描能攒下几千条问题,摊开写就把结论、重试键和下面两块面板全推走了。每条+ 给标题、说明和路径三段:只给一个链接的话,是哪个文件得逐个点开才知道,而路径+ 才是去磁盘上确认或改名时要用的。前 20 条之外的去完整日志里看,地址写在折叠底部。+ """+ island = (Path(__file__).resolve().parents[1]+ / "frontend" / "src" / "islands" / "library-processing.tsx").read_text(encoding="utf-8")+ self.assertIn("actionLabel:retryable?'重试未完成项':'',details:issueDetails", island)+ self.assertIn("label: issue.title || (issue.asset_id ? `视频 ${issue.asset_id}` : '媒体来源'),", island)+ self.assertIn("note: issue.message, hint: issue.path || '',", island)+ self.assertIn("footnote: state.issues_log ? `完整记录:${state.issues_log}` : '',", island)+ self.assertPageContains('<details class="geist-note-details"><summary>${esc(label)}</summary>')+ self.assertPageContains(".geist-note-details{grid-column:2/-1;")+ self.assertPageContains(".geist-note-details>ul{box-sizing:border-box;display:grid;gap:8px;max-height:min(40vh,520px);")+def test_the_pinned_review_bars_share_one_pane_of_glass(self):"""粘住的工具条和分组条是一块玻璃,中间没有接缝。@@ -8220,19 +8237,19 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("$('#batchbar').querySelectorAll('[data-follow-batch]').forEach(button=>button.hidden=!followPage);")def test_the_data_management_page_opens_with_a_row_of_stat_cards(self):- """数据管理页照 Board 的 dashboard 模板:工作区切换条领头,跟着一排读数卡,- 下面两张任务卡各占一行。+ """数据管理页照 Board 的 dashboard 模板:一排读数卡打头,下面两张任务卡各占一行。读数卡是 stat-cards.tsx 的 plain 变体做成按钮(132px、圆角 16、secondary 底、内边距 16、32px 图标格里 20px 字形、读数 24/34),整张卡就是那一页的入口;五张在 1120 内一行摆下,窄了折两列、再折一列。扫描与采集和空文件夹是要做的事,不是读数,各占一整行、左说明右按钮。- 骨架复用同一套结构。+ 骨架复用同一套结构,页首因此和读数卡直接接上:同样五个入口再排一条链接条,是同一件事+ 画两遍,而那条链接条连选中态都没有。"""self.assertPageContains("const DATA_MANAGEMENT_STATS=['review','quality','duplicates','junk','trash'];")self.assertPageContains('<button type="button" class="board-plain-stat" ${attrs}>')self.assertPageContains('<span class="board-plain-stat-head"><span class="board-stat-tile">${icon(glyph)}</span>${esc(title)}</span>${body}</button>`;')- self.assertPageContains('<div class="cleanuppage"><div class="cleanup-workspace-switch" role="tablist"')- self.assertPageContains('</div><div class="cleanupstats">')+ self.assertPageContains('<div class="cleanuppage"><div class="cleanupstats">')+ self.assertPageLacks('cleanup-workspace-switch')self.assertPageContains('</div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}</div>')for entry in ("['review','人工复核','square-check-big']", "['trash','回收站','trash']", "['quality','高清版','sparkles']"):self.assertPageContains(entry)diff --git a/web/app.js b/web/app.jsindex 6a1fbdb29..3611ff3bf 100644--- a/web/app.js+++ b/web/app.js@@ -3804,7 +3804,7 @@ function linkManagerMarkup(){return `<section class="resourcesync" id="link-manager" aria-labelledby="linkManagerTitle"><h2 id="linkManagerTitle">链接管理</h2><div class="resourcesyncbox" data-geist-fieldset>- <div class="resourcesyncbody geist-fieldset-content">${fieldsetTitle('linkBoxTitle','库里存着的站外链接')}+ <div class="resourcesyncbody geist-fieldset-content">${fieldsetTitle('linkBoxTitle','站外链接')}<div id="linkSummary" class="linksummary"></div></div><div class="resourcesyncfooter geist-fieldset-footer" data-geist-fieldset-footer><button class="resourceaction" type="button" id="linkCheck">${icon('unlink')}<span>检查死链</span></button></div></div>@@ -3826,16 +3826,16 @@ async function wireLinkManager(){.map(([kind,count])=>stat(KINDS[kind]||kind,Number(count).toLocaleString())).join('');const hosts=(info.top_hosts||[]).slice(0,3).map(([host,count])=>`${esc(host)} ${count}`).join(' · ');summary.innerHTML=`<div class="linkstats">- ${stat('链接总数',info.total.toLocaleString(),`挂在 ${info.entities.toLocaleString()} 位女优、厂牌或系列名下`)}+ ${stat('链接总数',info.total.toLocaleString(),`分布在 ${info.entities.toLocaleString()} 个女优、厂牌与系列`)}${kinds}</div>- ${hosts?`<div class="linkhosts"><span>来得最多的站点</span><b>${hosts}</b></div>`:''}`;+ ${hosts?`<div class="linkhosts"><span>主要站点</span><b>${hosts}</b></div>`:''}`;}catch(error){summary.innerHTML=noteHtml(error.message,{variant:'error',label:'读取失败'})}const row=(item,pick)=>`<tr>${pick?`<td class="linkpick"><input type="checkbox" data-link-id="${item.id}" aria-label="选择 ${esc(item.entity)} 的${esc(item.label||item.url)}"></td>`:''}<td>${esc(item.entity)}</td><td>${esc(KINDS[item.link_kind]||item.link_kind)}</td><td>${esc(item.label||'')}</td><td class="linknote">${esc(item.note)}</td><td class="linkurl"><a class="externallink" href="${esc(item.url)}" target="_blank" rel="noreferrer"><span data-middle-truncate>${esc(item.url)}</span>${icon('external-link','externalmark')}</a></td></tr>`;const table=(title,items,hint,{pick=false,footer=''}={})=>items.length?`<div class="linkgroup"><h4>${esc(title)} <b>${items.length}</b></h4>- <p>${esc(hint)}</p><div class="linktablewrap"><table class="linktable"><thead><tr>${pick?'<th class="linkpick"><input type="checkbox" id="linkPickAll" aria-label="全选这次没访问成功的链接"></th>':''}<th>所属</th><th>类型</th><th>标签</th><th>结果</th><th>地址</th></tr></thead><tbody>${items.map(item=>row(item,pick)).join('')}</tbody></table></div>${footer}</div>`:'';+ <p>${esc(hint)}</p><div class="linktablewrap"><table class="linktable"><thead><tr>${pick?'<th class="linkpick"><input type="checkbox" id="linkPickAll" aria-label="全选本次未访问成功的链接"></th>':''}<th>所属</th><th>类型</th><th>标签</th><th>结果</th><th>地址</th></tr></thead><tbody>${items.map(item=>row(item,pick)).join('')}</tbody></table></div>${footer}</div>`:'';const render=payload=>{const running=payload.status==='running';@@ -3848,17 +3848,17 @@ async function wireLinkManager(){const progress=running?jobActivityHtml(payload.total?`${retrying?'已重验':'已检查'} ${payload.checked.toLocaleString()} / ${payload.total.toLocaleString()} 条链接`:retrying?'正在重验链接':'正在检查链接',payload.checked,payload.total):'';/* gone 和 unclear 必须分开摆:`linktr.ee` 回 403 是挡爬虫、`x.com` 回 500 是临时错误,链接本身好好的。混成一张表会让人顺手把好链接一起删掉。 */- const gone=table('页面已经没了',payload.gone||[],'站点明确回答这个地址不存在(HTTP 404 或 410)。');+ const gone=table('地址已失效',payload.gone||[],'站点返回 404 或 410,确认这个地址不存在。');/* 这一组大多是站点拒绝程序访问或一次抖动,换个时间再问一次就通了。重跑整批要好几分钟,所以这里能挑着重试:勾中哪几条就只问哪几条,别的结论原样留着。 */const retryable=done?(payload.unclear||[]):[];const retryRow=retryable.length?`<div class="linkretryrow"><button class="resourceaction" type="button" id="linkRetryPicked" disabled>${icon('rotate-cw')}<span>重试选中的链接</span></button><button class="resourceaction" type="button" id="linkRetryAll">${icon('rotate-cw')}<span>全部重试(${retryable.length})</span></button></div>`:'';- const unclear=table('这次没访问成功',payload.unclear||[],'页面不一定没了:有的站点拒绝程序访问,有的是临时故障。这些链接会保留,勾选后可以只重试其中几条。',{pick:retryable.length>0,footer:retryRow});+ const unclear=table('本次未访问成功',payload.unclear||[],'未必失效:部分站点拒绝程序访问,也可能是临时故障。这些链接保留,可勾选后单独重试。',{pick:retryable.length>0,footer:retryRow});const apply=(done&&(payload.gone||[]).length)?`<div class="resourceapplyrow"><p>删除前会逐条重验一次;此操作不可撤销。</p><button class="resourceaction danger" type="button" id="linkPrune">删除 ${payload.gone.length} 条失效链接</button></div>`:'';- const clean=(done&&!(payload.gone||[]).length&&!(payload.unclear||[]).length)?'<p class="resourcesyncok">全部链接都能打开。</p>':'';+ const clean=(done&&!(payload.gone||[]).length&&!(payload.unclear||[]).length)?'<p class="resourcesyncok">全部链接均可访问。</p>':'';result.innerHTML=`<div class="resourcepanel"${apply?' data-fieldset-type="error"':''}>${progress}${gone}${unclear}${apply}${clean}</div>`;$('#linkPrune')?.addEventListener('click',async event=>{const control=event.currentTarget;@@ -3924,8 +3924,8 @@ function resourceSyncMarkup(){return `<section class="resourcesync" id="resource-sync" aria-labelledby="resourceSyncTitle"><h2 id="resourceSyncTitle">资源同步</h2><div class="resourcesyncbox" data-geist-fieldset>- <div class="resourcesyncbody geist-fieldset-content">${fieldsetTitle('resourceBoxTitle','文件与记录是否对得上')}- <p>照着馆藏里的记录,去本地磁盘和网盘上找对应的文件:文件已经不在的记录挑出来,没有记录再用到的缓存一并列出。</p></div>+ <div class="resourcesyncbody geist-fieldset-content">${fieldsetTitle('resourceBoxTitle','文件与记录核对')}+ <p>按馆藏记录逐条查找本地磁盘与网盘上的文件,列出文件已不存在的记录,以及不再被引用的缓存。</p></div><div class="resourcesyncfooter geist-fieldset-footer" data-geist-fieldset-footer><button class="resourceaction" type="button" id="resourceScan">${icon('git-compare')}<span>检查文件</span></button></div></div><div id="resourceSyncResult" aria-live="polite"></div></section>`;@@ -4508,10 +4508,7 @@ async function openDataCleanup(push=true){</section>`,review:entryCard('review'),quality:entryCard('quality'),trash:entryCard('trash'),};- const cleanupNav=[['/review','人工复核','review'],['/quality-goals','高清版','sparkles'],['/duplicates','重复文件','file-stack'],['/junk-files','垃圾文件','file-archive'],['/trash','回收站','trash']];- $('#stats').innerHTML=`<div class="cleanuppage"><div class="cleanup-workspace-switch" role="tablist" aria-label="数据管理区域">- ${cleanupNav.map(([href,label,glyph])=>`<a href="${href}" role="tab" data-cleanup-workspace="${href}" aria-selected="false">${icon(glyph)}<span>${label}</span></a>`).join('')}- </div><div class="cleanupstats">+ $('#stats').innerHTML=`<div class="cleanuppage"><div class="cleanupstats">${DATA_MANAGEMENT_STATS.map(section=>cleanupCards[section]).join('')}</div><div class="cleanupgrid">${cleanupCards.scraping}${cleanupCards.empty}</div>${linkManagerMarkup()}diff --git a/web/css/04-manage.css b/web/css/04-manage.cssindex 6d51921d4..4c7e51e2f 100644--- a/web/css/04-manage.css+++ b/web/css/04-manage.css@@ -131,11 +131,6 @@.fsrcoption label{flex:1;min-width:0}.fsrcoption .geist-button{font-size:var(--fs-sm);white-space:nowrap}.library-processing-outcome{min-width:0;max-width:100%}-.library-processing-issues-wrap{min-width:0;max-width:100%;margin-top:12px}-.library-processing-issues-summary{margin:0 0 8px;color:var(--muted);font-size:var(--fs-xs);overflow-wrap:anywhere}-/* 问题列表可能有上千条:只在这个框里滚,长消息就地换行,不让页面被撑破。 */-.library-processing-issues{box-sizing:border-box;max-width:100%;max-height:min(40vh,520px);margin:0;padding-inline-start:20px;overflow-x:hidden;overflow-y:auto;overflow-wrap:anywhere;overscroll-behavior:contain}-.library-processing-issues li{min-width:0;overflow-wrap:anywhere}.statsdashboard .emptystate{border:0;background:var(--ground)}.taste-history-guide-content a{color:var(--tungsten);text-decoration:none}.taste-history-guide-content a:hover{text-decoration:underline;text-underline-offset:3px}diff --git a/web/css/22-followmanage.css b/web/css/22-followmanage.cssindex 23c3eab4a..ad7bce15c 100644--- a/web/css/22-followmanage.css+++ b/web/css/22-followmanage.css@@ -92,6 +92,17 @@.geist-note-filled{background:color-mix(in srgb,var(--feedback-color) 8%,var(--ground))}.geist-note-small{min-height:32px;padding:4px 8px;font-size:var(--fs-xs);line-height:22px}.geist-note-small>svg{height:22px}+/* 折叠明细跟结论同一列,带操作按钮时那一列到行尾为止。 */+.geist-note-details{grid-column:2/-1;min-width:0;margin-bottom:6px;font-size:var(--fs-sm);line-height:22px}+.geist-note-details>summary{cursor:pointer;color:inherit}+/* 明细可能有上千条:只在这块里滚,长路径就地换行,不让页面被撑破。 */+.geist-note-details>ul{box-sizing:border-box;display:grid;gap:8px;max-height:min(40vh,520px);margin:8px 0 0;padding-inline-start:0;list-style:none;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain}+.geist-note-details li{display:grid;gap:2px;min-width:0;overflow-wrap:anywhere}+.geist-note-details li>a{justify-self:start;color:inherit;font-weight:500}+.geist-note-details li>b{font-weight:500}+.geist-note-details li>span,.geist-note-details li>code,.geist-note-details>p{color:var(--muted)}+.geist-note-details li>code{font-size:var(--fs-xs)}+.geist-note-details>p{margin:8px 0 0;overflow-wrap:anywhere}.project-banner{--feedback-color:var(--muted);display:flex;align-items:center;justify-content:center;gap:8px 16px;flex-wrap:wrap;padding:8px 24px;min-height:40px;border-block:1px solid color-mix(in srgb,var(--feedback-color) 30%,var(--ground));background:color-mix(in srgb,var(--feedback-color) 5%,var(--ground));color:var(--feedback-color);font-size:var(--fs-md);line-height:20px}.project-banner>div{display:flex;align-items:center;gap:8px;min-width:0}.project-banner p{margin:0;overflow-wrap:anywhere}/* 圆头端点是这枚字形的一部分:alert 与 info 圆圈里那个点是长度 .01 的路径,diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex b77722f28..33474202b 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -720,7 +720,16 @@ function ht({ data: e, error: t, toast: n, onComplete: r, mode: i, monitor: a, p...s.status === "running" && s.total !== void 0 ? { max: s.total } : {}}) } });}- let O = s.issue_preview || [], k = s.status === "failed" && !!s.retryable_asset_ids?.length;+ let O = s.issue_preview || [], k = s.status === "failed" && !!s.retryable_asset_ids?.length, A = s.status === "failed" && O.length ? {+ label: s.issues_truncated ? `问题清单:共 ${s.issue_count || 0} 项,展开查看前 ${O.length} 项` : `问题清单:共 ${s.issue_count || 0} 项`,+ items: O.map((e) => ({+ label: e.title || (e.asset_id ? `视频 ${e.asset_id}` : "媒体来源"),+ href: e.asset_id ? `/item/${e.asset_id}` : "",+ note: e.message,+ hint: e.path || ""+ })),+ footnote: s.issues_log ? `完整记录:${s.issues_log}` : ""+ } : null;return /* @__PURE__ */ J(L, { children: [/* @__PURE__ */ J("section", {class: "cleanupfieldset","data-geist-fieldset": !0,@@ -778,26 +787,10 @@ function ht({ data: e, error: t, toast: n, onComplete: r, mode: i, monitor: a, pdangerouslySetInnerHTML: { __html: p(l || s.error || "处理未完成,请重试", {variant: "error",filled: !0,- actionLabel: k ? "重试未完成项" : ""+ actionLabel: k ? "重试未完成项" : "",+ details: A}) }}),- s.status === "failed" && !!O.length && /* @__PURE__ */ J("div", {- class: "library-processing-issues-wrap",- children: [/* @__PURE__ */ J("p", {- class: "library-processing-issues-summary",- children: s.issues_truncated ? `共 ${s.issue_count || 0} 项问题,以下为前 ${O.length} 项` : `共 ${s.issue_count || 0} 项问题`- }), /* @__PURE__ */ J("ul", {- class: "library-processing-issues",- children: O.map((e) => /* @__PURE__ */ J("li", { children: [- e.asset_id ? /* @__PURE__ */ J("a", {- href: `/item/${e.asset_id}`,- children: "查看视频"- }) : null,- e.asset_id ? ":" : "",- e.message- ] }))- })]- }),g && /* @__PURE__ */ J("div", {class: "library-processing-result",dangerouslySetInnerHTML: { __html: p(`已扫描 ${s.scanned || 0} 个文件,识别 ${s.identified || 0} 个番号,整理 ${s.candidates || 0} 组资料候选。`, {@@ -894,8 +887,11 @@ function Ct() {issue_count: +(e === "failed"),issue_preview: e === "failed" ? [{asset_id: null,+ title: "本地磁盘",+ path: "R:\\Media",message: "来源连接超时"}] : [],+ issues_log: e === "failed" ? "peach-data\\state\\library-processing-preview.issues.jsonl" : "",retryable_asset_ids: e === "failed" ? [7] : []}, l = e === "disconnected" ? "连接中断,正在重新读取处理进度" : "";return /* @__PURE__ */ J("main", {diff --git a/web/js/ui-components.js b/web/js/ui-components.jsindex eb3f0a26e..3d4ca3a80 100644--- a/web/js/ui-components.js+++ b/web/js/ui-components.js@@ -102,13 +102,24 @@ export function mountFilterFrame(top,bottom,{views,tags,readout,controls}){return frame;}+/* 逐条明细收在 Note 自己的 <details> 里,默认折叠:一句话的结论后面跟着上千行清单时,+ 下面的内容全被推走,而那句结论本身才是要先读到的东西。每条给标题、说明和路径三段:+ 只给一个「查看视频」链接的话,是哪个文件得逐个点开才知道。 */+function noteDetailsHtml({label='',items=[],footnote=''}={}){+ const line=item=>`<li>${item.href?`<a href="${esc(item.href)}">${esc(item.label||'')}</a>`+ :`<b>${esc(item.label||'')}</b>`}<span>${esc(item.note||'')}</span>${+ item.hint?`<code>${esc(item.hint)}</code>`:''}</li>`;+ return `<details class="geist-note-details"><summary>${esc(label)}</summary>+ <ul>${items.map(line).join('')}</ul>${footnote?`<p>${esc(footnote)}</p>`:''}</details>`;+}+/** Inline, persistent context beside the field/card/section it describes. */-export function noteHtml(message,{variant='secondary',label='',className='',size='medium',filled=false,actionLabel=''}={}){+export function noteHtml(message,{variant='secondary',label='',className='',size='medium',filled=false,actionLabel='',details=null}={}){const kind=NOTE_VARIANTS.has(variant)?variant:'secondary';const symbol=kind==='secondary'?'info':kind==='success'?'check':'alert';const role=kind==='error'?' role="alert"':' role="note"';return `<div class="geist-note geist-note-${kind}${className?` ${esc(className)}`:''}${size==='small'?' geist-note-small':''}${filled?' geist-note-filled':''}"${role}>- ${icon(symbol)}<p>${label?`<b>${esc(label)}</b>`:''}<span>${esc(kind==='error'?requestErrorMessage(message):message)}</span></p>${actionLabel?`<button type="button" class="geist-button primary" data-note-action>${esc(actionLabel)}</button>`:''}</div>`;+ ${icon(symbol)}<p>${label?`<b>${esc(label)}</b>`:''}<span>${esc(kind==='error'?requestErrorMessage(message):message)}</span></p>${actionLabel?`<button type="button" class="geist-button primary" data-note-action>${esc(actionLabel)}</button>`:''}${details?noteDetailsHtml(details):''}</div>`;}const PROJECT_BANNER_CLASSES={gray:'project-banner-gray',success:'project-banner-success',warning:'project-banner-warning',error:'project-banner-error'};