Files
UHD_Media_Tool/apps/web/app/components/library/identity-pool-sheet.tsx
T
rootandClaude Opus 5.5 94fd48bff2 feat(identity): lazy TMDB lookup and bounded identity pool (DEC-1)
RSS/list releases that match no subscription or local work no longer hit
TMDB or open a pending item; they go to the identity pool as `unmatched`.
TMDB is queried only on a local alias hit, a published new-title rule whose
prefilter passes, manual/Agent retry, search results, or when the new
setting identity.eagerTmdbLookup (default off) is on. Mirrors MoviePilot:
torrents are recognised only when matched to a subscription or searched,
and recognition failures are logged, not alerted.

- Pending items only for related releases (ambiguous after lookup, or
  related to a local work but unresolved); same source + normalized title
  merge into one decision ("来源「X」的 N 条资源待识别"), resolve/dismiss
  applies to the whole group, members detach as they get resolved.
- Pool governance: unmatched reviews capped (daily, 3x), title_alias
  insert trigger wakes similar entries, stale unmatched entries archived
  after identity.poolArchiveDays (30); review idempotency keys include the
  due time.
- Migration 0047_identity_pool: reason/outcome `unmatched`,
  identity_candidate.normalized_title (+trgm index), wake trigger, and
  cleanup of open identity_unresolved items with no related work
  (dismissed, resolution=moved_to_pool).
- Inbox: group by type + work/source with collapse, hide info-only items
  by default (minSeverity=warning), badge counts warning+ only; pool sheet
  gets manual TMDB/local-work assign and dismiss; settings card for the
  new identity settings.
- Runbook docs/runbook/identity.md.

Requires rebuild/restart (migration runs on start).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 15:05:39 +08:00

266 lines
10 KiB
TypeScript

import type { IdentityPoolItem, PoolCandidate } from "@umt/contracts";
import { ArrowRight, BellOff, ExternalLink, LoaderCircle, RotateCw } from "lucide-react";
import { useId, useState } from "react";
import { Link } from "react-router";
import { toast } from "sonner";
import { useAssignPool, useDismissPool, useRetryPool } from "~/api/identity.ts";
import { DetailSection, DetailSheet } from "~/components/console/detail-sheet.tsx";
import { FormField } from "~/components/console/form-field.tsx";
import { JsonView } from "~/components/console/json-view.tsx";
import { KvList } from "~/components/console/kv-list.tsx";
import { consolePath } from "~/components/console/nav.ts";
import { EntityPicker, type PickedEntity } from "~/components/library/identity-entity-picker.tsx";
import { Button } from "~/components/ui/button.tsx";
import { Input } from "~/components/ui/input.tsx";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select.tsx";
import { errorMessage } from "~/lib/api.ts";
import { formatDateTime } from "~/lib/utils.ts";
import { EVIDENCE_LEVEL, POOL_REASON, POOL_STATUS } from "./labels.ts";
import { Chip, Tone } from "./parts.tsx";
// 待识别资源详情:候选证据 + 重新识别 + 手动指定。进了待处理的(与订阅相关的歧义 / 无结果)在待处理里选候选;
// 没进待处理的(unmatched:未命中订阅,惰性识别没查 TMDB)在这里手动指定 TMDB ID / 本地作品,或忽略。
/** 与订阅 / 本地作品相关的歧义开"待确认身份"事项,相关却无结果开"待识别"事项(同来源同标题合并);unmatched 不进待处理 */
export function inInbox(item: Pick<IdentityPoolItem, "status" | "reason" | "candidates" | "decisionId">): boolean {
return item.status === "pending" && (item.decisionId !== null || hasCandidates(item));
}
function hasCandidates(item: Pick<IdentityPoolItem, "reason" | "candidates">): boolean {
return (item.reason === "ambiguous" || item.reason === "proposed") && item.candidates.length > 0;
}
export const INBOX_IDENTITY = `${consolePath("inbox")}?kind=identity_ambiguous`;
export const INBOX_UNRESOLVED = `${consolePath("inbox")}?kind=identity_unresolved`;
/** 条目对应的待处理筛选链接 */
export function inboxLink(item: Pick<IdentityPoolItem, "reason" | "candidates">): string {
return hasCandidates(item) ? INBOX_IDENTITY : INBOX_UNRESOLVED;
}
/** query 摘要:标题 / 年份 / 季集 */
export function querySummary(q: Record<string, unknown>): string {
const parts: string[] = [];
if (q.title) parts.push(String(q.title));
if (q.year) parts.push(String(q.year));
if (q.season !== undefined && q.season !== null) parts.push(`S${String(q.season).padStart(2, "0")}`);
if (q.episode !== undefined && q.episode !== null) parts.push(`E${String(q.episode).padStart(2, "0")}`);
if (q.segment) parts.push(String(q.segment));
if (q.cut) parts.push(String(q.cut));
return parts.join(" · ") || "—";
}
function CandidateRow({ c, index }: { c: PoolCandidate; index: number }) {
return (
<li className="min-w-0 rounded-lg border border-border/80 p-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<p className="font-medium break-words text-foreground">
{index + 1}. {c.title}
{c.year ? ` (${c.year})` : ""}
</p>
<p className="font-mono text-meta break-all text-muted-foreground">
{c.provider}:{c.entityType}:{c.externalId}
</p>
</div>
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<Chip>{EVIDENCE_LEVEL[c.level] ?? c.level}</Chip>
{c.localEntityId ? (
<Link
to={consolePath("library", c.localEntityId)}
className="inline-flex items-center gap-1 text-meta text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
本地作品
<ExternalLink className="h-3 w-3" />
</Link>
) : (
<span className="text-meta text-muted-foreground">本地未建档</span>
)}
</div>
{c.evidence.length ? (
<ul className="mt-2 list-disc space-y-0.5 pl-5 text-meta text-muted-foreground">
{c.evidence.map((e) => (
<li key={e} className="break-words">
{e}
</li>
))}
</ul>
) : null}
</li>
);
}
/** 手动指定(复用 /identity-pool/{id}/assign,加人工锁)与忽略 */
function ManualAssign({ item }: { item: IdentityPoolItem }) {
const uid = useId();
const assign = useAssignPool();
const dismiss = useDismissPool();
const [tmdbType, setTmdbType] = useState<"movie" | "tv">(item.query.season != null ? "tv" : "movie");
const [tmdbId, setTmdbId] = useState("");
const [entity, setEntity] = useState<PickedEntity | null>(null);
const tmdbOk = /^\d{1,10}$/.test(tmdbId.trim());
const run = async (body: Parameters<typeof assign.mutateAsync>[0], ok: string) => {
try {
await assign.mutateAsync(body);
toast.success(ok);
} catch (err) {
toast.error(errorMessage(err, "指定失败"));
}
};
return (
<DetailSection title="手动指定">
<div className="grid gap-x-2 sm:grid-cols-[8rem_minmax(0,1fr)_auto] sm:items-end">
<FormField label="类型" htmlFor={`${uid}-type`}>
<Select value={tmdbType} onValueChange={(v) => setTmdbType(v as "movie" | "tv")}>
<SelectTrigger id={`${uid}-type`} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="movie">电影</SelectItem>
<SelectItem value="tv">剧集</SelectItem>
</SelectContent>
</Select>
</FormField>
<FormField label="TMDB ID" htmlFor={`${uid}-tmdb`} hint="纯数字,如 872585">
<Input
id={`${uid}-tmdb`}
inputMode="numeric"
value={tmdbId}
onChange={(e) => setTmdbId(e.target.value)}
aria-invalid={tmdbId.trim() !== "" && !tmdbOk}
/>
</FormField>
<Button
variant="outline"
className="mb-4"
disabled={!tmdbOk || assign.isPending}
onClick={() =>
run(
{
id: item.id,
external: { provider: "tmdb", entityType: tmdbType, externalId: tmdbId.trim() },
lock: true,
},
"已按 TMDB ID 指定",
)
}
>
指定
</Button>
</div>
<div className="grid gap-x-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end">
<FormField label="或选本地作品">
<EntityPicker value={entity} onChange={setEntity} />
</FormField>
<Button
variant="outline"
className="mb-4"
disabled={!entity || assign.isPending}
onClick={() => entity && run({ id: item.id, mediaEntityId: entity.id, lock: true }, "已关联本地作品")}
>
关联
</Button>
</div>
<Button
variant="ghost"
size="sm"
disabled={dismiss.isPending}
onClick={async () => {
try {
await dismiss.mutateAsync({ id: item.id });
toast.success("已忽略");
} catch (err) {
toast.error(errorMessage(err, "操作失败"));
}
}}
>
<BellOff />
忽略此资源
</Button>
</DetailSection>
);
}
export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; onClose: () => void }) {
const retry = useRetryPool();
if (!item) return null;
const queued = inInbox(item);
return (
<DetailSheet
open
width="lg"
onOpenChange={(o) => !o && onClose()}
title={item.release.title}
description={item.release.subtitle ?? undefined}
footer={
<>
<Button
variant="outline"
disabled={retry.isPending}
onClick={async () => {
try {
await retry.mutateAsync(item.id);
toast.success("已重新识别");
} catch (err) {
toast.error(errorMessage(err));
}
}}
>
{retry.isPending ? <LoaderCircle className="animate-spin" /> : <RotateCw />}
重新识别
</Button>
{queued ? (
<Button asChild>
<Link to={inboxLink(item)}>
去待处理
<ArrowRight />
</Link>
</Button>
) : null}
</>
}
>
{queued ? (
<p className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-caption text-warning">
已进待处理,在那里选择候选或忽略。
</p>
) : null}
<KvList
items={[
{ label: "状态", value: <Tone v={POOL_STATUS[item.status]} /> },
{ label: "原因", value: <Tone v={POOL_REASON[item.reason]} /> },
{ label: "解析结果", value: querySummary(item.query), wide: true },
{ label: "站点分类", value: item.release.categoryRaw },
{ label: "首次发现", value: formatDateTime(item.release.firstSeenAt) },
{ label: "尝试次数", value: String(item.attempts) },
{ label: "上次尝试", value: formatDateTime(item.lastAttemptAt) },
{ label: "下次复查", value: item.nextReviewAt ? formatDateTime(item.nextReviewAt) : "不再自动复查" },
{ label: "证据版本", value: item.evidenceVersion, mono: true },
]}
/>
{item.status !== "resolved" && !queued ? <ManualAssign item={item} /> : null}
<DetailSection title={`候选(${item.candidates.length})`}>
{item.candidates.length ? (
<ul className="space-y-2">
{item.candidates.map((c, i) => (
<CandidateRow key={`${c.provider}:${c.entityType}:${c.externalId}`} c={c} index={i} />
))}
</ul>
) : (
<p className="text-caption text-muted-foreground">
{item.reason === "unmatched"
? "没有命中订阅或本地作品,未查询 TMDB。点「重新识别」会查一次 TMDB;新增相近别名时自动重试。"
: "没有候选。有新证据时自动重试。"}
</p>
)}
</DetailSection>
<JsonView label="解析条件(原始)" value={item.query} defaultOpen={false} />
</DetailSheet>
);
}