Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

42.1 KB
Raw Blame
import { scanDuplicateCases, compareDuplicateCases, chooseDuplicateKeeper, duplicateOrigin, duplicateRevision, duplicateContent, mediaIdentity, duplicateVisualAssets, bulkDuplicateGroups } from './library-duplicates.js';
import { appendTextDifference } from './case-dedupe-diff.js';
import { bindPopoverMenu } from './transient-menu.js';
import { createUiIcon } from './ui-icons.js';
import { getLibraryStorage } from './library-storage.js';
import { DEDUPE_REVIEW_KEY, unverifiedCases, updateReviewDismissals } from './dedupe-review-state.js';
import { t } from './i18n.js';

const cache = new WeakMap();
const node = (tag, text, cls) => { const n = document.createElement(tag); if (text != null) n.textContent = text; if (cls) n.className = cls; return n; };
const button = (label, fn, cls = 'button-secondary') => { const n = node('button', t(label), cls); n.type = 'button'; n.addEventListener('click', fn); return n; };
const iconButton = (label, icon, fn) => { const n = button(label, fn, 'icon-button'); n.title = t(label); n.setAttribute('aria-label', t(label)); n.replaceChildren(createUiIcon(icon)); return n; };
const SECTIONS = { title: '案例标题', text: '正文', prompts: '提示词', document: '文档', media: '媒体', labels: '标签与分类', notes: '备注', analysis: '分析', source: '来源', other: '其他资料' };
const ORIGINS = { copy: '有复制来源记录', imports: '来自不同导入批次', reference: '有创作引用关系', unknown: '来源记录不足,无法确定重复原因' };
const KEY_NAMES = { title: '案例标题', text: '正文', url: '来源', sourceTitle: '文件名', sourceAuthor: '作者', author: '作者', capturedAt: '采集时间', publishedAt: '发布时间', libraryAddedAt: '入库时间', libraryUpdatedAt: '编辑时间', savedAt: '保存时间', width: '宽度', height: '高度', byteSize: '文件大小', durationMs: '时长', sourceUrl: '来源', prompt: '提示词', originalPrompt: '提示词', note: '备注' };
const DISPLAY_INTERNAL = new Set(['id', 'contentHash', 'inputHash', 'inputDigest', 'sourceDigest', 'sourceHash', 'analysisMeta', 'usage', 'usagePolicy', 'tokenUsage', 'tokens', 'provider', 'schemaVersion', 'revision', 'sourceRevision', 'status', 'source', 'confidence', 'reason', 'order', 'facetId', 'classificationSource', 'autoGenerated', 'generatedAt', 'analyzedAt', 'updatedAt', 'storageMode', 'role', 'kind', 'palette', 'reviewStatus', 'captureMethod', 'screenshotMeta']);
function readable(value, key = '', names = new Map(), contentLabel = value => value) {
  if (value == null) return '';
  if (Array.isArray(value)) return value.map(v => readable(v, key, names, contentLabel)).filter(Boolean).join('\n');
  if (typeof value === 'object') return Object.entries(value).filter(([k]) => !DISPLAY_INTERNAL.has(k))
    .map(([k, v]) => readable(v, k, names, contentLabel)).filter(Boolean).join('\n');
  if (typeof value === 'string' && /Ids?$/u.test(key) && /^\$media:\d+:/u.test(value)) {
    return t('第 {count} 份素材', { count: Number(value.split(':')[1]) + 1 });
  }
  if (key === 'nodeId') return names.get(value) || t('未命名标签');
  if (key === 'contentTypeId' || key === 'pathIds') return contentLabel(value);
  if (typeof value === 'boolean') return '';
  return `${KEY_NAMES[key] ? `${t(KEY_NAMES[key])}:` : ''}${value}`;
}
function comparisonText(section, fields, entry, other, names, contentLabel) {
  const text = readable(fields[section], '', names, contentLabel);
  if (section !== 'media') return text;
  const notes = (entry.mediaAssets || []).flatMap((asset, index) => {
    const counterpart = other.mediaAssets?.[index];
    if (!counterpart) return [t('第 {count} 份素材:另一案例没有此位置的素材', { count: index + 1 })];
    if (!mediaIdentity(asset) || !mediaIdentity(counterpart)) return [t('第 {count} 份素材:原件尚未核对', { count: index + 1 })];
    return mediaIdentity(asset) === mediaIdentity(counterpart) ? [] : [t('第 {count} 份素材:原件内容不同', { count: index + 1 })];
  });
  return [...notes, text].join('\n');
}
function dateText(value) { return value && Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : t('未知'); }

export function mountCaseDedupePanel(body, { state: initialState, facetCatalog, contentLabel, projectId = '', selectedIds = [], pageSize, currentState, send, thumbnailUrl, mediaUrl, openCase, heading }) {
  const storage = getLibraryStorage();
  const headingParent = heading?.parentNode, headingNext = heading?.nextSibling;
  let dismissed = {}, initialized = false, initializing = false;
  const verificationErrors = new Map();
  let pendingPanel, pendingRows, pendingSummary, ignoredPanel, ignoredRows, ignoredSummary;
  const tagNames = new Map((facetCatalog?.nodes || []).map(item => [item.id, item.name]));
  let state = initialState, result, scanned, activeId = null, memberPage = 0, visibleGroups = pageSize;
  let scanning = false, paused = false, closed = false, checking = false, applying = false;
  let selections = new Map(), keepers = new Map(), rule = 'newest', preferredProject = projectId;
  let scope = projectId || '*', scanSteps, pendingRequest = null, confirmation = null, acrossProjects = false, onlyMatchingData = false;
  let refreshButton, status, list, compare, selectionStatus, execute, scopeSelect, rules, checkButton, pauseButton, summary, review, footer, projects, projectHint;
  let progressStamp = 0, indexedEntries, entryIndex, unbindOptions;
  const frameBudget = 1000 / 60;
  const projectMap = new Map((state.organizerState?.collections || []).map(c => [c.id, c]));
  const path = id => { const parts = [], seen = new Set(); let c = projectMap.get(id); while (c && !seen.has(c.id)) { seen.add(c.id); parts.unshift(c.name); c = projectMap.get(c.parentId); } return parts.join(' / '); };
  const projectNames = id => (result?.projects.get(id) || []).map(path).join(' · ') || t('未归项目');
  const byId = () => { if (indexedEntries !== state.entries) { indexedEntries = state.entries; entryIndex = new Map(state.entries.map(e => [e.id, e])); } return entryIndex; };
  const selectedGroup = group => selections.get(group.id) || new Set();
  const say = message => { if (!closed) { status.textContent = message; status.hidden = !message; } };
  function invalidate() { confirmation = null; pendingRequest = null; if (review) review.replaceChildren(); if (execute) execute.textContent = t('一键清理重复'); }
  function scopedState() {
    if (scope === '*') return state;
    const ids = new Set(scope === '@selection' ? selectedIds : []);
    if (scope !== '@selection') {
      const parents = new Set([scope]); let changed = true;
      while (changed) { changed = false; for (const c of projectMap.values()) if (parents.has(c.parentId) && !parents.has(c.id)) { parents.add(c.id); changed = true; } }
      for (const id of parents) for (const entryId of projectMap.get(id)?.entryIds || []) ids.add(entryId);
    }
    return { ...state, entries: state.entries.filter(e => ids.has(e.id)) };
  }
  function selectAll() {
    selections.clear();
    for (const group of result?.groups || []) {
      const keep = byId().get(keepers.get(group.id));
      selections.set(group.id, new Set(group.caseIds.filter(id => id !== keep.id && (!onlyMatchingData || compareDuplicateCases(keep, byId().get(id), result.projects).exact))));
    }
    invalidate();
  }
  function prepare() {
    if (!scanned) return;
    result = { ...scanned, groups: bulkDuplicateGroups(scanned, state.entries, acrossProjects) };
    for (const group of result.groups) {
      const prior = keepers.get(group.id);
      const choice = chooseDuplicateKeeper(group.caseIds.map(id => byId().get(id)), rule, preferredProject, result.projects, group.caseIds.includes(prior) ? prior : undefined);
      keepers.set(group.id, choice.id);
    }
    selectAll(); render();
  }
  function updateSelection() {
    const total = [...selections.values()].reduce((sum, ids) => sum + ids.size, 0);
    const count = new Set((result?.groups || []).flatMap(g => g.caseIds)).size;
    selectionStatus.textContent = t('保留 {keep} 份 · 清理 {remove} 份', { keep: count - total, remove: total });
    footer.hidden = !count; rules.hidden = !count; projects.hidden = !count || rule !== 'project';
    execute.disabled = !total || applying || scanning || checking || !initialized;
    refreshButton.disabled = initializing || scanning || checking || applying;
    pauseButton.hidden = !scanSteps && !scanning; checkButton.hidden = !currentReviews().some(row => !row.dismissed) && !checking;
    checkButton.disabled = scanning || applying || !initialized;
    for (const control of body.querySelectorAll(".dedupe-unverified-row button")) control.disabled = scanning || applying || checking; rules.disabled = !result || applying || checking;
  }
  async function dismissReview(row, dismiss) {
    try {
      await storage.update(DEDUPE_REVIEW_KEY, stored => ({
        [DEDUPE_REVIEW_KEY]: updateReviewDismissals(stored[DEDUPE_REVIEW_KEY], state.entries, row, dismiss)
      }));
      // Read the small preference record, never reload the whole library for a reminder.
      dismissed = (await storage.get(DEDUPE_REVIEW_KEY))[DEDUPE_REVIEW_KEY] || {};
      renderPending(); updateSelection();
    } catch (error) { say(t(error.message)); }
  }
  let reviewCache, renderedReviewRows;
  const pendingNodes = new WeakMap();
  let comparisonView;
  const expandedDetails = new Map();
  function currentReviews() {
    if (reviewCache?.entries !== state.entries || reviewCache?.dismissed !== dismissed || reviewCache?.scope !== scope) {
      reviewCache = { entries: state.entries, dismissed, scope, rows: unverifiedCases(scopedState().entries, dismissed) };
    }
    return reviewCache.rows;
  }
  function renderPending(force = false) {
    if (closed) return;
    const rows = currentReviews();
    if (!force && renderedReviewRows === rows) return;
    renderedReviewRows = rows;
    for (const [panel, heading, container, ignored] of [[pendingPanel, pendingSummary, pendingRows, false], [ignoredPanel, ignoredSummary, ignoredRows, true]]) {
      const members = rows.filter(row => row.dismissed === ignored);
      heading.hidden = !members.length; panel.hidden = !members.length || !panel.open;
      heading.setAttribute('aria-expanded', String(panel.open && members.length > 0));
      heading.textContent = t(ignored ? '已略过 {count} 个案例' : '待核对 {count} 个案例', { count: members.length });
      const existing = new Map([...container.querySelectorAll('.dedupe-unverified-row')].map(card => [card.dataset.entryId, card]));
      const valid = new Map(members.map(row => [row.entry.id, row.entry]));
      for (const [id, card] of existing) if (valid.get(id) !== pendingNodes.get(card)?.entry) {
        card.querySelectorAll('video,audio').forEach(media => media.pause()); card.remove(); existing.delete(id);
      }
      if (!panel.open || !members.length) {
        container.querySelectorAll('video,audio').forEach(media => media.pause());
        container.replaceChildren(); delete container.dataset.shown; continue;
      }
      let shown = Math.max(pageSize, Number(container.dataset.shown) || pageSize);
      function more(extend = true) {
        if (extend) shown += pageSize;
        container.querySelector('.dedupe-pending-more')?.remove();
        for (const row of members.slice(0, shown)) {
          if (existing.has(row.entry.id)) continue;
          const card = node('article', null, 'dedupe-unverified-row'); card.dataset.entryId = row.entry.id;
          const actions = node('div', null, 'dedupe-unverified-actions');
          const reason = () => [...new Set(row.assets.map(asset => verificationErrors.get(JSON.stringify([row.entry.id, asset.id])) ||
            (asset.storageMode === 'reference' ? '原件仅保留外部引用,尚未保存到本机' : '原件尚未核对')))];
          const title = button('查看案例', () => {
            const existing = card.querySelector('.dedupe-case');
            if (existing) { existing.querySelectorAll('video,audio').forEach(media => media.pause()); existing.remove(); title.setAttribute('aria-expanded', 'false'); return; }
            title.setAttribute('aria-expanded', 'true');
            const detail = node('div', null, 'dedupe-case dedupe-inspection');
            const reasonText = node('p', reason().map(value => t(value)).join(';'), 'dedupe-inspection-reason');
            reasonText.setAttribute('role', 'status');
            const metadata = node('div', null, 'dedupe-inspection-meta');
            metadata.append(node('span', projectNames(row.entry.id)));
            if (/^https?:\/\//iu.test(row.entry.url || '')) {
              const source = node('a', null, 'button-secondary');
              source.append(createUiIcon('external-link'), node('span', t('查看来源')));
              source.href = row.entry.url; source.target = '_blank'; source.rel = 'noopener noreferrer'; metadata.append(source);
            }
            detail.append(reasonText, metadata);
            if (row.entry.text || row.entry.mediaPrompts?.length) {
              const contents = node('details'); contents.append(node('summary', t('完整案例内容')));
              if (row.entry.text) contents.append(node('pre', row.entry.text));
              if (row.entry.mediaPrompts?.length) contents.append(node('pre', readable(row.entry.mediaPrompts)));
              detail.append(contents);
            }
            card.append(detail);
            void renderMedia(detail, row.entry, row.assets[0]?.id, error => {
              // Keep one actionable reason. Reference-only entries are already explained above.
              if (!row.assets.every(asset => asset.storageMode === 'reference')) reasonText.textContent = error;
            });
          }, 'button-secondary dedupe-review-title');
          title.textContent = row.entry.title || t('未命名');
          title.setAttribute('aria-expanded', 'false');
          actions.append(iconButton('重试核对', 'refresh-cw', () => void checkOriginals(row.entry.id)),
            iconButton(ignored ? '恢复提醒' : '不再提示', ignored ? 'arrow-left' : 'x', () => void dismissReview(row, !ignored)));
          card.append(title, actions); pendingNodes.set(card, { entry: row.entry }); container.append(card); existing.set(row.entry.id, card);
        }
        container.dataset.shown = String(shown);
        if (shown < members.length) container.append(button('显示更多待核对项', () => more(true), 'button-secondary dedupe-pending-more'));
        updateSelection();
      }
      more(false);
    }
  }
  function renderList() {
    list.replaceChildren(); const groups = result?.groups || [];
    summary.textContent = groups.length ? t('{groups} 组重复 · {cases} 个案例', { groups: groups.length, cases: new Set(groups.flatMap(g => g.caseIds)).size }) : (scanned?.unknown ? t('已核对项无重复') : t('未发现重复'));
    const preservedProjects = (scanned?.mediaGroups || []).flatMap(g => g.caseIds).length - groups.reduce((count, g) => count + g.caseIds.length, 0);
    projectHint.hidden = !preservedProjects;
    projectHint.textContent = t('跨项目保留 {count} 份', { count: preservedProjects });
    for (const group of groups.slice(0, visibleGroups)) {
      const keep = byId().get(keepers.get(group.id)), chosen = selectedGroup(group);
      const row = node('article', null, 'dedupe-group-row'); row.dataset.groupId = group.id;
      const check = node('input'); check.type = 'checkbox'; check.setAttribute('aria-label', t('选择此组')); check.checked = chosen.size > 0; check.indeterminate = chosen.size > 0 && chosen.size < group.caseIds.length - 1;
      check.addEventListener('change', () => { selections.set(group.id, new Set(check.checked ? group.caseIds.filter(id => id !== keep.id && (!onlyMatchingData || compareDuplicateCases(keep, byId().get(id), result.projects).exact)) : [])); invalidate();
        check.indeterminate = false; row.querySelector('.dedupe-group-count').textContent = t('清理 {count} 份', { count: selectedGroup(group).size });
        updateSelection(); });
      const preview = button('查看', () => { activeId = group.id; memberPage = 0; render(); }, 'dedupe-group-preview');
      const asset = duplicateVisualAssets(keep)[0];
      if (asset) void thumbnailUrl(asset.id).then(url => { if (!url || closed || !preview.isConnected) return; const img = node('img'); img.src = url; img.alt = keep.title || ''; preview.replaceChildren(img); }).catch(() => {});
      const info = node('div', null, 'dedupe-group-summary');
      const metadata = `${t('{count} 份相同原件', { count: group.caseIds.length })} · ${projectNames(keep.id)} · ${dateText(keep.libraryAddedAt)}`;
      const subtitle = node('small', metadata); subtitle.title = metadata;
      info.append(node('strong', keep.title || t('未命名')), subtitle);
      const count = node('span', t('清理 {count} 份', { count: chosen.size }), 'dedupe-group-count');
      row.append(check, preview, info, count, button('查看详情', () => { activeId = group.id; memberPage = 0; render(); })); list.append(row);
    }
    if (visibleGroups < groups.length) list.append(button('显示更多重复组', () => { visibleGroups += pageSize; renderList(); }));
  }
  function chooseKeeper(group, id) {
    const previous = keepers.get(group.id), selected = selectedGroup(group);
    if (selected.size && previous) selected.add(previous);
    keepers.set(group.id, id); selected.delete(id); selections.set(group.id, selected); invalidate(); void renderCompare(); updateSelection();
  }
  async function renderMedia(card, entry, initialAssetId, onUnavailable) {
    const assets = (entry.mediaAssets || []).filter(a => a.usage !== 'poster');
    const area = node('div', null, 'dedupe-preview'), picker = node('select');
    picker.setAttribute('aria-label', t('媒体')); assets.forEach(a => { const o = node('option', a.sourceTitle || t(a.kind === 'image' ? '图片' : a.kind === 'video' ? '视频' : '文档')); o.value = a.id; picker.append(o); });
    if (initialAssetId) picker.value = initialAssetId;
    let mediaIntent = 0;
    async function show() {
      const intent = ++mediaIntent; area.querySelectorAll('video,audio').forEach(media => media.pause()); area.replaceChildren(); area.hidden = true; area.classList.remove('dedupe-preview-unavailable'); const asset = assets.find(a => a.id === picker.value) || assets[0];
      if (asset && ['image', 'video', 'audio'].includes(asset.kind)) {
        try {
          const url = await (asset.kind === 'image' ? thumbnailUrl(asset.id) : mediaUrl(asset.id));
          if (intent !== mediaIntent || !area.isConnected) return;
          if (!url) throw new Error(t(asset.storageMode === 'reference' ? '原件仅保留外部引用,尚未保存到本机' : '本机原件未找到,可打开案例检查来源'));
          const media = node(asset.kind === 'image' ? 'img' : asset.kind); media.src = url;
          if (asset.kind !== 'image') { media.controls = true; media.preload = 'metadata'; }
          else { media.alt = asset.sourceTitle || entry.title || ''; media.addEventListener('click', async () => {
            const original = await mediaUrl(asset.id); if (original) window.open(original, '_blank', 'noopener');
          }); }
          media.addEventListener('error', () => unavailable(t('媒体无法预览')), { once: true });
          area.append(media); area.hidden = false;
        } catch (error) { unavailable(t(error.message)); }
      } else if (!onUnavailable) { area.append(node('pre', entry.text || asset?.sourceTitle || t('无正文'))); area.hidden = false; }
      function unavailable(message) {
        if (intent !== mediaIntent || !area.isConnected) return;
        area.replaceChildren(); area.classList.add('dedupe-preview-unavailable');
        area.hidden = Boolean(onUnavailable);
        if (onUnavailable) onUnavailable(message); else area.append(node('span', message));
      }
    }
    picker.addEventListener('change', () => void show());
    card.append(area); if (assets.length > 1) card.append(picker); await show();
  }
  async function renderCompare() {
    const focusedCard = document.activeElement?.closest('.dedupe-case');
    const focusedId = focusedCard && compare.contains(focusedCard) ? focusedCard.dataset.entryId : null;
    const positions = [];
    for (let parent = compare; parent; parent = parent.parentElement) if (parent.scrollHeight > parent.clientHeight) positions.push([parent, parent.scrollTop]);
    const reuse = comparisonView?.groupId === activeId && comparisonView.state === state;
    if (!reuse) {
      compare.querySelectorAll('video,audio').forEach(media => media.pause());
      compare.replaceChildren(); comparisonView = { groupId: activeId, state, page: -1, cards: new Map() };
    }
    const header = node('div'); header.append(button('返回全部重复组', () => { activeId = null; render(); }));
    if (comparisonView.header) comparisonView.header.replaceWith(header); else compare.append(header);
    comparisonView.header = header;
    const group = result?.groups.find(g => g.id === activeId);
    if (!group) { compare.append(node('p', scanning ? t('正在比较案例…') : t('当前范围没有这类重复'))); return; }
    const map = byId(), rows = group.caseIds.map(id => map.get(id));
    let keep = keepers.get(group.id);
    if (!group.caseIds.includes(keep)) {
      const choice = chooseDuplicateKeeper(rows, rule, preferredProject, result.projects);
      keep = choice.id; keepers.set(group.id, keep);
    }
    const reference = map.get(keep);
    const dateChoice = chooseDuplicateKeeper(rows, rule, preferredProject, result.projects, keep);
    const batchNames = new Map([...new Set(rows.map(e => e.importBatchId).filter(Boolean))].map((id, i) => [id, i + 1]));
    header.append(node('h3', t('图片/视频原件完全相同')), node('p', t(ORIGINS[duplicateOrigin(rows)]), 'dedupe-origin'));
    if (dateChoice.uncertain) header.append(node('p', t('日期或项目无法区分优先项,可手动更换保留项。')));
    if (rows.some(e => !compareDuplicateCases(reference, e, result.projects).sameProjects)) header.append(node('p', t('清理跨项目副本后,该项目中将不再显示此案例。')));
    if (!onlyMatchingData && rows.some(e => selectedGroup(group).has(e.id) && !compareDuplicateCases(reference, e, result.projects).exact)) header.append(node('p', t('附带资料不同的副本也已选中,清理后可从回收站恢复。')));
    const grid = comparisonView.grid || node('div', null, 'dedupe-cases');
    if (!comparisonView.grid) { comparisonView.grid = grid; compare.append(grid); }
    const others = rows.filter(e => e.id !== keep);
    const visible = comparisonView.page === memberPage ? comparisonView.visible.map(id => map.get(id))
      : [reference, ...others.slice(memberPage, memberPage + pageSize - 1)];
    comparisonView.page = memberPage; comparisonView.visible = visible.map(entry => entry.id);
    comparisonView.paging?.remove();
    if (others.length > pageSize - 1) {
      const paging = node('div', null, 'dedupe-toolbar');
      if (memberPage) paging.append(button('上一页', () => { memberPage = Math.max(0, memberPage - pageSize + 1); void renderCompare(); }));
      if (memberPage + pageSize - 1 < others.length) paging.append(button('下一页', () => { memberPage += pageSize - 1; void renderCompare(); }));
      compare.append(paging); comparisonView.paging = paging;
    }
    for (const entry of visible) {
      let card = comparisonView.cards.get(entry.id);
      if (card) {
        for (const detail of card.querySelectorAll('details')) expandedDetails.set(JSON.stringify([entry.id, detail.querySelector('summary')?.textContent]), detail.open);
        for (const child of [...card.children]) if (!child.matches('.dedupe-preview,select')) child.remove();
      } else {
        card = node('article', null, 'dedupe-case'); card.dataset.entryId = entry.id;
        comparisonView.cards.set(entry.id, card); grid.append(card);
        void renderMedia(card, entry, group.assetIds?.[entry.id]);
      }
      card.classList.toggle('keep', entry.id === keep);
      const heading = node('div', null, 'dedupe-case-heading'); heading.append(node('h4', entry.title || t('未命名'))); card.prepend(heading);
      const info = node('div', null, 'dedupe-case-info'); info.append(node('p', projectNames(entry.id)),
        node('small', `${t('入库时间')}:${dateText(entry.libraryAddedAt)}\n${t('编辑时间')}:${dateText(entry.libraryUpdatedAt)}`));
      if (entry.copyOrigin?.title) info.append(node('small', t('复制自:{title}', { title: entry.copyOrigin.title })));
      if (entry.importBatchId) info.append(node('small', t('本组第 {count} 批导入', { count: batchNames.get(entry.importBatchId) })));
      const assets = entry.mediaAssets || [];
      info.append(node('small', t('{count} 份素材', { count: assets.filter(a => a.usage !== 'poster').length })));
      card.append(info);
      const action = node('div', null, 'dedupe-case-actions');
      const keepButton = button(entry.id === keep ? '保留这份' : '改为保留这份', () => chooseKeeper(group, entry.id));
      keepButton.disabled = entry.id === keep; action.append(keepButton);
      if (entry.id !== keep) {
        const label = node('label'), check = node('input'); check.type = 'checkbox'; check.checked = selectedGroup(group).has(entry.id);
        check.addEventListener('change', () => { const ids = selectedGroup(group); check.checked ? ids.add(entry.id) : ids.delete(entry.id); selections.set(group.id, ids); invalidate(); updateSelection(); });
        label.append(check, node('span', t('清理这份'))); action.append(label);
      }
      card.append(action);
      const diff = compareDuplicateCases(reference, entry, result.projects);
      if (entry.id !== keep) {
        const fields = duplicateContent(entry), baseline = duplicateContent(reference);
        if (!diff.complete) card.append(node('p', t('原件尚未全部核对'), 'dedupe-pending'));
        for (const section of diff.differences.sort((a, b) => Object.keys(SECTIONS).indexOf(a) - Object.keys(SECTIONS).indexOf(b))) {
          const detail = node('details'), summary = node('summary', `${t(SECTIONS[section])} · ${t('不同')}`);
          detail.open = false; detail.append(summary);
          const texts = node('div', null, 'dedupe-text-diff');
          const left = node('pre'), right = node('pre');
          const a = comparisonText(section, baseline, reference, entry, tagNames, contentLabel), b = comparisonText(section, fields, entry, reference, tagNames, contentLabel);
          if (a === b) {
            detail.open = false; detail.append(node('p', t('内容展示相同,但关联或处理记录不同,未自动清理。'))); card.append(detail); continue;
          }
          left.append(node('strong', t('保留项')+'\n')); right.append(node('strong', t('当前项')+'\n'));
          appendTextDifference(left, a, b, 'left'); appendTextDifference(right, a, b, 'right'); texts.append(left, right); detail.append(texts); card.append(detail);
        }
      }
      const full = node('details'), summary = node('summary', t('完整案例内容')); full.append(summary);
      full.append(node('pre', entry.text || t('无正文')));
      if (entry.mediaPrompts?.length) full.append(node('pre', readable(entry.mediaPrompts)));
      if (entry.timeNotes?.length) full.append(node('pre', readable(entry.timeNotes)));
      card.append(full);
      for (const detail of card.querySelectorAll('details')) detail.open = expandedDetails.get(JSON.stringify([entry.id, detail.querySelector('summary')?.textContent])) || false;
    }
    const shown = new Set(visible.map(entry => entry.id));
    for (const [id, card] of comparisonView.cards) if (!shown.has(id)) {
      card.querySelectorAll('video,audio').forEach(media => media.pause()); card.remove(); comparisonView.cards.delete(id);
    }
    if (focusedId && !compare.contains(document.activeElement)) {
      const card = comparisonView.cards.get(focusedId); if (card) { card.tabIndex = -1; card.focus({ preventScroll: true }); }
    }
    for (const [parent, top] of positions) parent.scrollTop = top;
  }
  function render() {
    if (closed) return;
    const inspecting = Boolean(activeId && result?.groups.some(g => g.id === activeId));
    list.hidden = inspecting || !result?.groups.length; compare.hidden = !inspecting;
    if (inspecting) void renderCompare(); else { compare.querySelectorAll('video,audio').forEach(m => m.pause()); comparisonView = null; compare.replaceChildren(); renderList(); }
    renderPending(); updateSelection();
  }
  async function scan(fresh = true) {
    if (closed || !initialized || scanning) return;
    if (fresh) { scanSteps = scanDuplicateCases(scopedState(), { cache }); result = null; scanned = null; activeId = null; visibleGroups = pageSize; selections.clear(); invalidate(); }
    scanning = true; paused = false; say(t('正在比较案例…')); updateSelection(); scopeSelect.disabled = true; pauseButton.disabled = false;
    try {
      while (!closed && !paused) {
        const next = await scanSteps.next();
        if (next.done) { scanned = next.value; scanSteps = null; break; }
        if (performance.now() - progressStamp > frameBudget) { say(t('已比较 {count} / {total} 个案例', { count: next.value.checked, total: next.value.total })); progressStamp = performance.now(); await new Promise(requestAnimationFrame); }
      }
      if (scanned) { prepare(); say(scanned.unknown ? t('已比较可核对原件') : t('图片/视频原件核对完成')); status.hidden = true; }
    } catch (error) { say(t(error.message)); }
    finally { scanning = false; scopeSelect.disabled = false; pauseButton.disabled = !scanSteps; pauseButton.textContent = t(paused ? '继续' : '暂停'); render(); }
  }
  async function checkOriginals(entryId = null) {
    if (checking) { paused = true; return; }
    checking = true; paused = false; checkButton.textContent = t('暂停核对'); scopeSelect.disabled = true; updateSelection();
    let checked = 0;
    const originals = new Map();
    const candidates = currentReviews().filter(row => entryId ? row.entry.id === entryId : !row.dismissed);
    for (const { entry, assets } of candidates) for (const asset of assets) {
      if (mediaIdentity(asset) && asset.byteSize > 0) continue;
      if (!originals.has(asset.id)) originals.set(asset.id, []);
      originals.get(asset.id).push(entry);
    }
    try {
      const pending = [...originals];
      for (let offset = 0; offset < pending.length; offset += pageSize) {
        if (closed || paused) break;
        const batch = pending.slice(offset, offset + pageSize);
        say(t('已核对 {count} / {total} 份原件', { count: checked, total: pending.length }));
        const data = await send({ type: 'VERIFY_DEDUPE_MEDIA', assets: batch.map(([assetId, entries]) => ({ assetId, entryIds: entries.map(e => e.id) })) });
        const updates = new Map();
        for (const row of data.results) {
          for (const id of row.updatedIds) {
            if (!updates.has(id)) updates.set(id, new Map());
            updates.get(id).set(row.assetId, row);
            verificationErrors.delete(JSON.stringify([id, row.assetId]));
          }
          for (const id of row.failedIds) {
            const asset = byId().get(id)?.mediaAssets?.find(asset => asset.id === row.assetId);
            verificationErrors.set(JSON.stringify([id, row.assetId]), row.error || (asset?.storageMode === 'reference'
              ? '原件仅保留外部引用,尚未保存到本机' : '案例中的这份媒体已变化,请重新比较'));
          }
          checked += 1;
        }
        state = { ...state, entries: state.entries.map(e => !updates.has(e.id) ? e : { ...e, mediaAssets: e.mediaAssets.map(a => {
          const update = updates.get(e.id).get(a.id);
          return update ? { ...a, contentHash: update.contentHash, byteSize: update.byteSize } : a;
        }) }) };
      }
      if (!closed) { await scan(true); }
    } catch (error) { say(t(error.message)); }
    finally { checking = false; scopeSelect.disabled = false; checkButton.textContent = t('核对原件'); updateSelection(); }
  }
  function renderBlocked(rows) {
    for (const row of rows) {
      const item = node('div', null, 'dedupe-blocked');
      item.append(node('p', `${t('保留项')}:${row.title}`));
      if (row.references?.length) {
        for (const reference of row.references) {
          const owner = node('div', null, 'dedupe-reference');
          owner.append(node('span', `${t(reference.kind)}:${reference.title || t('未命名')}`));
          if (reference.caseId && openCase) owner.append(button('查看案例', () => void openCase(reference.caseId)));
          item.append(owner);
        }
      } else item.append(node('p', t(row.reason)));
      review.append(item);
    }
  }
  async function cleanup() {
    if (applying) return; applying = true; updateSelection();
    const controls = [...body.querySelectorAll('button, select, input')].filter(el => !heading?.contains(el)).map(el => [el, el.disabled]); controls.forEach(([el]) => { el.disabled = true; });
    try {
      if (!confirmation && !pendingRequest) {
        const map = byId(), groups = [];
        for (const group of result.groups) {
          const ids = [...selectedGroup(group)]; if (!ids.length) continue;
          const keepId = keepers.get(group.id), keep = map.get(keepId);
          groups.push({ keepId, keepRevision: await duplicateRevision(keep, result.projects.get(keepId)), allowDifferent: !onlyMatchingData,
            allowCrossProject: acrossProjects, remove: await Promise.all(ids.map(async id => ({ id, revision: await duplicateRevision(map.get(id), result.projects.get(id)) }))) });
        }
        const preview = await send({ type: 'PREVIEW_CASE_DEDUPE', groups });
        const accepted = new Set(preview.accepted);
        const eligibleGroups = groups.map(group => ({ ...group, remove: group.remove.filter(row => accepted.has(row.id)) })).filter(group => group.remove.length);
        const count = new Set(result.groups.flatMap(group => group.caseIds)).size;
        const differences = eligibleGroups.flatMap(g => g.remove.filter(r => !compareDuplicateCases(map.get(g.keepId), map.get(r.id), result.projects).exact));
        for (const [id, selected] of selections) selections.set(id, new Set([...selected].filter(id => accepted.has(id))));
        confirmation = accepted.size ? { groups: eligibleGroups, preview } : null;
        review.replaceChildren();
        if (accepted.size) {
          review.append(node('strong', t('将保留 {keep} 份,清理 {remove} 份', { keep: count - accepted.size, remove: accepted.size })), node('p', t('清理后进入回收站,可恢复。')));
          if (differences.length) review.append(node('p', t('其中 {count} 份附带资料有差异,将随副本一起进入回收站。', { count: differences.length })));
          if (acrossProjects) review.append(node('p', t('清理跨项目副本后,该项目中将不再显示此案例。')));
          const details = node('details'); details.append(node('summary', t('查看保留与清理清单')));
          details.append(node('pre', eligibleGroups.map(g => `${t('保留项')}:${map.get(g.keepId).title} · ${projectNames(g.keepId)}
${t('清理这份')}:${g.remove.map(r => `${map.get(r.id).title} · ${projectNames(r.id)}`).join(';')}`).join('\n\n'))); review.append(details);
        }
        renderBlocked(preview.skipped);
        if (accepted.size) review.append(button('取消', () => { invalidate(); render(); }));
        say(t(accepted.size ? '请确认本次批量清理数量' : '所选案例仍有关联引用或变化,本次未清理'));
        execute.textContent = t(accepted.size ? '确认移入回收站' : '一键清理重复');
        render();
        review.scrollIntoView({ block: 'nearest' });
      } else {
        pendingRequest ||= { requestId: crypto.randomUUID(), groups: confirmation.groups };
        const outcome = await send({ type: 'APPLY_CASE_DEDUPE', input: pendingRequest });
        const moved = new Set(outcome.movedEntryIds); state = { ...state, entries: state.entries.filter(e => !moved.has(e.id)) };
        invalidate(); await scan(true);
        const skipped = new Set(outcome.skipped.map(row => row.id));
        for (const [id, selected] of selections) selections.set(id, new Set([...selected].filter(id => !skipped.has(id))));
        renderBlocked(outcome.skipped); render();
        say(moved.size ? t('{count} 个案例已移入回收站', { count: moved.size }) : t('案例引用或内容已变化,本次未清理'));
      }
    } catch (error) { say(t(error.message)); if (pendingRequest) execute.textContent = t('重试同一清理'); }
    finally { applying = false; controls.forEach(([el, disabled]) => { el.disabled = disabled; }); updateSelection(); }
  }
  const toolbar = node('div', null, 'dedupe-toolbar'); scopeSelect = node('select'); scopeSelect.setAttribute('aria-label', t('检查范围'));
  for (const [id, title] of [['*', t('全部案例')], ['@selection', t('当前选择')], ...[...projectMap.values()].map(c => [c.id, path(c.id)])]) { const o = node('option', title); o.value = id; scopeSelect.append(o); }
  scopeSelect.value = scope; scopeSelect.addEventListener('change', () => { scope = scopeSelect.value; keepers.clear(); void scan(true); });
  pauseButton = button('暂停', () => { if (scanning) paused = true; else void scan(false); }); checkButton = button('核对原件', () => void checkOriginals());
  rules = node('select'); rules.setAttribute('aria-label', t('保留规则'));
  for (const [value, label] of [['newest', '保留最新入库'], ['oldest', '保留最早入库'], ['edited', '保留最近编辑'], ['project', '优先保留指定项目']]) { const o = node('option', t(label)); o.value = value; rules.append(o); }
  projects = node('select'); projects.hidden = true; projects.setAttribute('aria-label', t('优先保留指定项目'));
  for (const c of projectMap.values()) { const o = node('option', path(c.id)); o.value = c.id; projects.append(o); }
  projects.value = preferredProject || projects.options[0]?.value || ''; preferredProject = projects.value;
  rules.addEventListener('change', () => { rule = rules.value; projects.hidden = rule !== 'project'; prepare(); });
  projects.addEventListener('change', () => { preferredProject = projects.value; prepare(); });
  const options = node('details', null, 'dedupe-options');
  const optionsTrigger = node('summary', null, 'button-secondary'); optionsTrigger.append(node('span', t('清理选项')), createUiIcon('chevron-down'));
  const optionsPanel = node('div'); options.append(optionsTrigger, optionsPanel);
  unbindOptions = bindPopoverMenu(options, optionsPanel);
  for (const [label, change] of [['跨项目一起清理', value => { acrossProjects = value; }], ['仅清理附带资料也一致的副本', value => { onlyMatchingData = value; }]]) {
    const wrap = node('label'), check = node('input'); check.type = 'checkbox'; check.className = 'ui-switch'; check.setAttribute('role', 'switch'); check.addEventListener('change', () => { change(check.checked); activeId = null; prepare(); }); wrap.append(check, node('span', t(label))); optionsPanel.append(wrap);
  }
  projectHint = node('small'); optionsPanel.append(projectHint);
  refreshButton = iconButton('重新比较', 'refresh-cw', () => { state = currentState(); void (initialized ? scan(true) : initialize()); });
  if (heading) toolbar.append(heading);
  toolbar.append(scopeSelect, rules, projects, options, pauseButton, checkButton, refreshButton);
  status = node('p', null, 'dedupe-status'); status.setAttribute('role', 'status'); summary = node('p', null, 'dedupe-summary');
  const main = node('div', null, 'dedupe-main'); list = node('div', null, 'dedupe-groups'); compare = node('div', null, 'dedupe-comparison'); compare.hidden = true; main.append(list, compare);
  pendingPanel = node('details', null, 'dedupe-unverified'); pendingRows = node('div');
  ignoredPanel = node('details', null, 'dedupe-unverified'); ignoredRows = node('div');
  pendingSummary = button('', () => { pendingPanel.open = !pendingPanel.open; ignoredPanel.open = false; renderPending(true); }, 'button-secondary dedupe-review-toggle');
  ignoredSummary = button('', () => { ignoredPanel.open = !ignoredPanel.open; pendingPanel.open = false; renderPending(true); }, 'button-secondary dedupe-review-toggle');
  pendingSummary.dataset.review = 'pending'; ignoredSummary.dataset.review = 'ignored';
  // The result row owns the disclosure controls; unopened rows load no previews.
  pendingPanel.append(node('summary'), pendingRows); ignoredPanel.append(node('summary'), ignoredRows);
  main.prepend(pendingPanel, ignoredPanel);
  const overview = node('div', null, 'dedupe-overview'); overview.append(summary, pendingSummary, ignoredSummary);
  review = node('div', null, 'dedupe-review');
  footer = node('div', null, 'dedupe-footer'); selectionStatus = node('span');
  execute = button('一键清理重复', () => void cleanup(), 'button-primary'); execute.disabled = true;
  footer.append(button('全选所有重复组', () => { selectAll(); render(); }), button('取消全选', () => { selections.clear(); invalidate(); render(); }), selectionStatus, execute);
  const content = node('div', null, 'dedupe-content'); content.append(main, review);
  body.append(toolbar, status, overview, content, footer);

  async function initialize() {
    if (closed || initializing) return;
    initializing = true;
    const controls = [...body.querySelectorAll('button, select, input')].filter(el => !heading?.contains(el));
    controls.forEach(control => { control.disabled = true; });
    footer.hidden = true; rules.hidden = true; pauseButton.hidden = true; checkButton.hidden = true;
    say(t('正在比较案例…'));
    try {
      dismissed = (await storage.get(DEDUPE_REVIEW_KEY))[DEDUPE_REVIEW_KEY] || {};
      if (closed) return;
      initialized = true;
      controls.forEach(control => { control.disabled = false; });
      // Paint the existing settings subview before comparing a large library.
      await new Promise(requestAnimationFrame);
      await scan(true);
    } catch (error) { say(t(error.message)); }
    finally { initializing = false; if (!closed) updateSelection(); }
  }
  void initialize();
  return { dispose() {
    closed = true; paused = true; unbindOptions?.();
    body.querySelectorAll('video,audio').forEach(media => { media.pause(); media.removeAttribute('src'); media.load(); });
    if (headingParent) headingParent.insertBefore(heading, headingNext?.parentNode === headingParent ? headingNext : null);
    body.replaceChildren();
  } };
}