feat(控制台): 去掉待处理中心,问题回到发生处

- 侧栏与命令面板没有「待处理」;/console/inbox?kind= 按问题类型跳到整理记录「需要处理」、下载面板、运行状态或订阅
- 整理记录加「需要处理」筛选,行内写原因与推荐动作(指定作品 / 重新整理 / 让智能体识别 / 替换·保留两者·跳过 / 忽略),
  详情页同样可处理;处理按钮从原待处理页抽成 components/decisions/decision-actions.tsx 复用
- 铃铛只放等你批准的智能体操作与系统健康;首页「要我处理」与运行状态「需要关注」放汇总计数,运行状态加智能体用量
- 设置 → 智能体:预算卡改为「用量与限制」(只剩单次工具调用与时长,附花费统计),自动调查卡加「整理识别不到作品时叫智能体识别」
- 集数待确认的原因显示在作品页集数映射(可确认建议规则 / 智能体建议)与订阅详情;未识别资源在媒体库「未识别」里直接选候选或指定
- 下载、站点、任务里指向待处理的链接改到对应页面

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Cxwgnn2pbzQ7rXv3rq7fei
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-10-06 16:47:25 +08:00
1 parent 1c1a954703
commit fa76d7563c
36 files changed
+1209 -921

No files matched your search

+1 -5
View File
@@ -30,16 +30,12 @@ const RULES: Rule[] = [
},
{
match: /^\/console\/organize/,
goals: ["这次整理为什么有文件失败", "核对整理后的路径是否符合命名规则", "把失败的文件重新整理一遍"],
goals: ["识别需要处理的整理记录里的作品", "这次整理为什么有文件失败", "把失败的文件重新整理一遍"],
},
{
match: /^\/console\/files/,
goals: ["把下载目录里还没整理的文件整理入库", "找出重复的文件", "看看哪些文件还没被识别"],
},
{
match: /^\/console\/inbox/,
goals: ["逐条说明待处理事项的原因和建议", "先处理最紧急的一项待处理事项", "哪些待处理事项可以直接按建议批量处理"],
},
{
match: /^\/console\/identity/,
goals: ["识别未识别的文件", "找出外部身份可能错误的作品", "补全缺少元数据的作品"],
+94 -87
View File
@@ -1,71 +1,89 @@
import { useQueryClient } from "@tanstack/react-query";
import type { Decision, DecisionKind } from "@umt/contracts";
import type { Decision } from "@umt/contracts";
import { ArrowRight, Bell, CheckCheck } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router";
import { decisionKeys, useDecisionSummary, useDecisions } from "~/api/decisions.ts";
import { useAttention } from "~/api/attention.ts";
import { EmptyState, ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { consolePath } from "~/components/console/nav.ts";
import { SEVERITY } from "~/components/library/labels.ts";
import { Button } from "~/components/ui/button.tsx";
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover.tsx";
import { decisionKindLabel, formatRelative } from "~/lib/labels.ts";
import { useSse } from "~/lib/sse.ts";
import { formatRelative } from "~/lib/labels.ts";
import { cn } from "~/lib/utils.ts";
// 顶栏收件箱(IA-3):待处理不进侧栏,铃铛 + 未决角标;下拉按问题类型列最近事项,点开进待处理页。
// 角标只算需要你处理的事项(警告及以上):"仅信息"类(巡检报告、旧版本待处置等)不计入,在待处理页可展开查看。
// 身份类事项已按来源 + 标题合并,一条事项可能代表多条资源(标题里写明 N 条)。
// 顶栏铃铛(2026-10-06 起只放两类):需要你批准的智能体操作(会话里的审批 / 方案选择、计划审批、原站页面等你接手)
// 与系统健康问题(站点不可达、下载器离线、下载目录读不到容量、磁盘空间不足、媒体库目录离线,恢复后自动消失)。
// 整理问题在整理记录里处理,集数待确认在订阅详情 / 作品页集数映射里看,不进铃铛。
const RECENT = 8;
const RECENT = 6;
const DOT = { info: "bg-muted-foreground/60", warning: "bg-warning", critical: "bg-destructive" } as const;
/** 未决数与最近事项;SSE decision.* 到达时刷新 */
export function useLiveDecisions() {
const qc = useQueryClient();
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useSse(["decision.created", "decision.updated"], () => {
if (timer.current) return;
timer.current = setTimeout(() => {
timer.current = null;
void qc.invalidateQueries({ queryKey: decisionKeys.all });
}, 800);
});
return useDecisionSummary(undefined, "warning");
/** 等你批准的事项点开去哪:智能体会话、下载、下载任务;其余去智能体页 */
export function approvalHref(d: Pick<Decision, "subjectType" | "subjectId" | "agentRunId">): string {
if (d.subjectType === "agent_run" && d.subjectId) return consolePath("agent", d.subjectId);
if (d.agentRunId) return consolePath("agent", d.agentRunId);
if (d.subjectType === "acquisition_plan" && d.subjectId)
return `${consolePath("downloads")}?plan=${encodeURIComponent(d.subjectId)}`;
if (d.subjectType === "download_task" && d.subjectId) return consolePath("downloads", d.subjectId);
return consolePath("agent");
}
export const inboxPath = (kind?: string) => (kind ? `/console/inbox?kind=${kind}` : "/console/inbox");
export const HEALTH_HREF = `${consolePath("status")}#attention`;
function Group({
title,
total,
items,
href,
onGo,
}: {
title: string;
total: number;
items: Decision[];
href: (d: Decision) => string;
onGo: () => void;
}) {
if (!total) return null;
return (
<section className="pt-1">
<p className="flex items-center justify-between gap-2 px-2 py-1.5 text-label font-semibold tracking-[0.18em] text-muted-foreground uppercase">
<span>{title}</span>
<span className="tracking-normal tabular-nums">{total}</span>
</p>
<ul>
{items.slice(0, RECENT).map((d) => (
<li key={d.id}>
<Link
to={href(d)}
onClick={onGo}
className="block rounded-lg px-2 py-2 outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/50"
>
<span className="line-clamp-2 text-body break-words text-foreground">{d.title}</span>
<span className="mt-0.5 flex items-center gap-1.5 text-meta text-muted-foreground">
<span aria-hidden className={cn("h-1.5 w-1.5 shrink-0 rounded-full", DOT[d.severity])} />
{SEVERITY[d.severity].label} · {formatRelative(d.createdAt)}
</span>
</Link>
</li>
))}
</ul>
</section>
);
}
export function InboxBell() {
const summary = useLiveDecisions();
const q = useAttention();
const [open, setOpen] = useState(false);
const list = useDecisions({ minSeverity: "warning" }, open);
const navigate = useNavigate();
const total = summary.data?.total ?? 0;
const groups = useMemo(() => {
const items = (list.data?.pages[0]?.items ?? []).slice(0, RECENT);
const m = new Map<DecisionKind, Decision[]>();
for (const d of items) m.set(d.kind, [...(m.get(d.kind) ?? []), d]);
const counts = new Map<DecisionKind, number>();
for (const g of summary.data?.groups ?? []) counts.set(g.kind, (counts.get(g.kind) ?? 0) + g.count);
return [...m.entries()].map(([kind, ds]) => ({ kind, items: ds, count: counts.get(kind) ?? ds.length }));
}, [list.data, summary.data]);
const go = (to: string) => {
setOpen(false);
navigate(to);
};
const approvals = q.data?.approvals ?? { total: 0, items: [] };
const health = q.data?.health ?? { total: 0, items: [] };
const total = approvals.total + health.total;
const label = total ? `需要你关注 ${total} 项` : "通知";
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
size="icon-sm"
className="relative"
aria-label={total ? `待处理 ${total} 项` : "待处理"}
title={total ? `待处理 ${total} 项` : "待处理"}
>
<Button variant="outline" size="icon-sm" className="relative" aria-label={label} title={label}>
<Bell className="h-4 w-4" />
{total ? (
<span className="absolute -top-0.5 -right-0.5 min-w-4 rounded-full bg-primary px-1 text-center text-micro leading-4 font-semibold text-primary-foreground tabular-nums">
@@ -78,56 +96,45 @@ export function InboxBell() {
align="end"
sideOffset={8}
collisionPadding={16}
aria-label="待处理事项"
aria-label="通知"
className="pg-float-solid flex max-h-[var(--radix-popover-content-available-height)] w-[min(22rem,calc(100vw-2rem))] flex-col overflow-hidden p-2"
>
<div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-2 pt-1 pb-2">
<p className="text-sm font-semibold text-foreground">
待处理
{total ? <span className="ml-1.5 font-normal text-muted-foreground tabular-nums">{total}</span> : null}
</p>
<Button variant="ghost" size="xs" onClick={() => go(inboxPath())}>
查看全部
<p className="text-sm font-semibold text-foreground">通知</p>
<Button
variant="ghost"
size="xs"
onClick={() => {
setOpen(false);
navigate(consolePath("status"));
}}
>
运行状态
<ArrowRight />
</Button>
</div>
{list.isPending ? (
{q.isPending ? (
<LoadingState className="px-4 py-6" />
) : list.isError ? (
) : q.isError ? (
<ErrorState plain error="稍后再试" className="py-8" />
) : groups.length === 0 ? (
<EmptyState plain icon={CheckCheck} title="没有需要处理的事项" className="py-8" />
) : total === 0 ? (
<EmptyState plain icon={CheckCheck} title="没有等你批准的操作,系统运行正常" className="py-8" />
) : (
<div className="min-h-0 overflow-y-auto overscroll-contain pt-1">
{groups.map((g) => (
<section key={g.kind} className="pt-1">
<button
type="button"
onClick={() => go(inboxPath(g.kind))}
className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-label font-semibold tracking-[0.18em] text-muted-foreground uppercase outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
>
<span>{decisionKindLabel(g.kind)}</span>
<span className="tracking-normal tabular-nums">{g.count}</span>
</button>
<ul>
{g.items.map((d) => (
<li key={d.id}>
<Link
to={inboxPath(d.kind)}
onClick={() => setOpen(false)}
className="block rounded-lg px-2 py-2 outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring/50"
>
<span className="line-clamp-2 text-body break-words text-foreground">{d.title}</span>
<span className="mt-0.5 flex items-center gap-1.5 text-meta text-muted-foreground">
<span aria-hidden className={cn("h-1.5 w-1.5 shrink-0 rounded-full", DOT[d.severity])} />
{SEVERITY[d.severity].label} · {formatRelative(d.createdAt)}
</span>
</Link>
</li>
))}
</ul>
</section>
))}
<Group
title="等你批准"
total={approvals.total}
items={approvals.items}
href={approvalHref}
onGo={() => setOpen(false)}
/>
<Group
title="系统健康"
total={health.total}
items={health.items}
href={() => HEALTH_HREF}
onGo={() => setOpen(false)}
/>
</div>
)}
</PopoverContent>
+10 -2
View File
@@ -39,10 +39,18 @@ describe("控制台导航", () => {
expect(NAV_ITEMS.every((i) => i.to.startsWith("/console"))).toBe(true);
});
it("取消的入口不在侧栏:待处理走顶栏收件箱,引擎面板 / 身份并入别处", () => {
it("取消的入口不在侧栏:没有待处理(问题回到发生处),引擎面板 / 身份并入别处", () => {
const paths = NAV_ITEMS.map((i) => i.to);
for (const p of ["/console/inbox", "/console/engine", "/console/identity"]) expect(paths).not.toContain(p);
expect(pageTitle("/console/inbox")).toBe("待处理");
expect(NAV_ITEMS.map((i) => i.label)).not.toContain("待处理");
expect(pageTitle("/console/inbox")).toBeUndefined();
});
it("旧待处理链接按问题类型落到对应页面", () => {
expect(legacyRedirect("/console/inbox", "?kind=path_conflict")).toBe("/console/organize?tab=records&attention=1");
expect(legacyRedirect("/console/inbox", "?kind=download_failed")).toBe("/console/downloads");
expect(legacyRedirect("/console/inbox", "?kind=space_insufficient")).toBe("/console/status#attention");
expect(legacyRedirect("/console/inbox", "?kind=unknown_kind")).toBe("/console/organize?tab=records&attention=1");
});
it("每个导航项都有路由", () => {
+1 -2
View File
@@ -42,7 +42,7 @@ export const ACQUIRE_GROUP_TITLE = "获取";
/**
* 侧栏 4 组 14 项(IA-2,docs/design/console-ia.md):概览 → 获取 → 整理 → 系统。
* 任务归系统;RSS 属于站点(站点详情的 RSS Tab),不再单独占一项。
* 待处理不进侧栏,由顶栏收件箱打开;移动端抽屉用同一份表。
* 没有「待处理」(2026-10-06 取消):问题在发生处处理,铃铛只放等你批准的智能体操作与系统健康;移动端抽屉用同一份表。
*/
export const NAV_GROUPS: NavGroup[] = [
{
@@ -139,7 +139,6 @@ export const NAV_GROUPS: NavGroup[] = [
/** 不在侧栏但有页面的路由:顶栏标题用 */
const EXTRA_TITLES: Record<string, string> = {
"/console/inbox": "待处理",
"/console/preferences": "偏好标签",
"/console/search": "搜索",
};
@@ -0,0 +1,87 @@
import type { AttentionSummary, Decision } from "@umt/contracts";
import { describe, expect, it } from "vitest";
import { approvalHref, HEALTH_HREF } from "../console/inbox-bell.tsx";
import { attentionRows } from "./attention-summary.tsx";
// 首页 / 运行状态的「需要关注」汇总计数与铃铛跳转(2026-10-06 去掉待处理中心后)。
const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
const dec = (n: number, over: Partial<Decision>): Decision =>
({
id: id(n),
kind: "other",
status: "open",
severity: "warning",
title: "t",
summary: null,
subjectType: null,
subjectId: null,
dedupeKey: `k${n}`,
evidence: {},
options: [],
resolution: null,
taskId: null,
agentRunId: null,
attempts: 0,
nextReviewAt: null,
resolvedBy: null,
resolvedAt: null,
createdAt: "2026-10-06T00:00:00.000Z",
updatedAt: "2026-10-06T00:00:00.000Z",
...over,
}) as Decision;
const empty: AttentionSummary = { organize: 0, approvals: { total: 0, items: [] }, health: { total: 0, items: [] } };
describe("需要关注汇总", () => {
it("只列非零项", () => {
expect(attentionRows(empty)).toEqual([]);
expect(attentionRows(undefined)).toEqual([]);
});
it("整理需要处理 / 等你批准 / 系统健康按问题归类,点进去到对应页面", () => {
const rows = attentionRows({
organize: 3,
approvals: {
total: 1,
items: [dec(1, { kind: "approval_required", subjectType: "agent_run", subjectId: id(9) })],
},
health: {
total: 3,
items: [
dec(2, { kind: "source_unreachable" }),
dec(3, { kind: "downloader_offline" }),
dec(4, { kind: "other", dedupeKey: "library_root_offline:x" }),
],
},
});
expect(rows.map((r) => [r.text, r.to])).toEqual([
["3 条整理需要处理", "/console/organize?tab=records&attention=1"],
["1 个操作等你批准", `/console/agent/${id(9)}`],
["1 个站点不可达", HEALTH_HREF],
["1 个下载器离线", HEALTH_HREF],
["1 个媒体库目录离线", HEALTH_HREF],
]);
});
it("健康问题超过列出的条数时补一行", () => {
const rows = attentionRows({ ...empty, health: { total: 5, items: [dec(2, { kind: "space_insufficient" })] } });
expect(rows.map((r) => r.text)).toEqual(["1 个下载盘空间不足", "4 个系统问题"]);
});
});
describe("铃铛跳转", () => {
it("智能体会话 / 下载计划 / 下载任务", () => {
expect(approvalHref({ subjectType: "agent_run", subjectId: id(1), agentRunId: null })).toBe(
`/console/agent/${id(1)}`,
);
expect(approvalHref({ subjectType: "acquisition_plan", subjectId: id(2), agentRunId: null })).toBe(
`/console/downloads?plan=${id(2)}`,
);
expect(approvalHref({ subjectType: "download_task", subjectId: id(3), agentRunId: null })).toBe(
`/console/downloads/${id(3)}`,
);
expect(approvalHref({ subjectType: null, subjectId: null, agentRunId: null })).toBe("/console/agent");
expect(HEALTH_HREF).toBe("/console/status#attention");
});
});
@@ -0,0 +1,78 @@
import type { AttentionSummary, Decision } from "@umt/contracts";
import { ChevronRight } from "lucide-react";
import { Link } from "react-router";
import { approvalHref, HEALTH_HREF } from "~/components/console/inbox-bell.tsx";
import { consolePath } from "~/components/console/nav.ts";
import { ORGANIZE_ATTENTION_PATH } from "~/routes/console/redirects.ts";
// 首页与运行状态共用的「需要关注」汇总计数(2026-10-06 去掉待处理中心后):
// 「3 条整理需要处理」「1 个站点不可达」…,点进去到对应页面;只列非零项。
/** 系统健康事项按问题归类成一句(量词 + 说法) */
function healthKind(d: Pick<Decision, "kind" | "dedupeKey">): { key: string; unit: string } {
if (d.dedupeKey.startsWith("library_root_offline:")) return { key: "library_root", unit: "个媒体库目录离线" };
switch (d.kind) {
case "source_unreachable":
return { key: d.kind, unit: "个站点不可达" };
case "downloader_offline":
return { key: d.kind, unit: "个下载器离线" };
case "cache_volume_unknown":
return { key: d.kind, unit: "个下载目录读不到容量" };
case "space_insufficient":
return { key: d.kind, unit: "个下载盘空间不足" };
default:
return { key: "other", unit: "个系统问题" };
}
}
export interface AttentionRow {
key: string;
text: string;
to: string;
}
/** 汇总 → 一行一类(非零才列) */
export function attentionRows(s: AttentionSummary | undefined): AttentionRow[] {
if (!s) return [];
const rows: AttentionRow[] = [];
if (s.organize) rows.push({ key: "organize", text: `${s.organize} 条整理需要处理`, to: ORGANIZE_ATTENTION_PATH });
if (s.approvals.total) {
const first = s.approvals.items[0];
rows.push({
key: "approvals",
text: `${s.approvals.total} 个操作等你批准`,
to: s.approvals.total === 1 && first ? approvalHref(first) : consolePath("agent"),
});
}
const counts = new Map<string, { unit: string; n: number }>();
for (const d of s.health.items) {
const k = healthKind(d);
const cur = counts.get(k.key);
counts.set(k.key, { unit: k.unit, n: (cur?.n ?? 0) + 1 });
}
const listed = [...counts.values()].reduce((a, x) => a + x.n, 0);
if (s.health.total > listed) {
const cur = counts.get("other");
counts.set("other", { unit: "个系统问题", n: (cur?.n ?? 0) + s.health.total - listed });
}
for (const [key, v] of counts) rows.push({ key, text: `${v.n} ${v.unit}`, to: HEALTH_HREF });
return rows;
}
export function AttentionList({ rows }: { rows: AttentionRow[] }) {
return (
<ul className="divide-y divide-border/60">
{rows.map((r) => (
<li key={r.key}>
<Link
to={r.to}
className="flex min-w-0 items-center justify-between gap-3 py-1.5 text-sm text-foreground hover:underline"
>
<span className="truncate">{r.text}</span>
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
</Link>
</li>
))}
</ul>
);
}
@@ -0,0 +1,199 @@
import type { Decision, DecisionOption } from "@umt/contracts";
import { Search } from "lucide-react";
import { useId, useState } from "react";
import { toast } from "sonner";
import { useResolveDecision } from "~/api/decisions.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
import { FormField } from "~/components/console/form-field.tsx";
import { EntityPicker, type PickedEntity } from "~/components/library/identity-entity-picker.tsx";
import { type AssignedWork, WorkAssignDialog } from "~/components/library/work-assign-dialog.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 { Textarea } from "~/components/ui/textarea.tsx";
import { errorMessage } from "~/lib/api.ts";
// 事项(decision)的处理按钮:待处理中心取消后(2026-10-06),问题在发生处就地处理(整理记录行内等),
// 选项与执行仍走 POST /decisions/{id}/resolve(后端注册的执行钩子:指定作品后重新整理、替换 / 保留两者 / 跳过…)。
/** 处理按钮只用到事项的这几个字段(整理记录里带的是精简版) */
export type DecisionLike = Pick<Decision, "id" | "title" | "options" | "evidence">;
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v : null);
/** 身份类手动指定选项需要的输入(后端在 option.input.requires 标注) */
type Requires = "tmdb" | "mediaEntityId" | null;
function requiresOf(option: DecisionOption): Requires {
const r = option.input?.requires;
return r === "tmdb" || r === "mediaEntityId" ? r : null;
}
/** 「指定作品」两个选项(本地作品 / TMDB)已并进 AssignWorkButton,其余选项各一个按钮 */
export function plainOptions(d: DecisionLike): DecisionOption[] {
return d.options.filter((o) => o.key !== "dismiss" && requiresOf(o) === null);
}
/** 事项带不带「指定作品」(本地作品或 TMDB) */
export function canAssignWork(d: DecisionLike): boolean {
return d.options.some((o) => requiresOf(o) !== null);
}
export function OptionButton({
d,
option,
variant = "outline",
}: {
d: DecisionLike;
option: DecisionOption;
variant?: "outline" | "default";
}) {
const resolve = useResolveDecision();
const uid = useId();
const [note, setNote] = useState("");
const requires = requiresOf(option);
const [tmdbType, setTmdbType] = useState<"movie" | "tv">("movie");
const [tmdbId, setTmdbId] = useState("");
const [entity, setEntity] = useState<PickedEntity | null>(null);
const tmdbOk = /^\d{1,10}$/.test(tmdbId.trim());
const identity =
requires === "tmdb"
? tmdbOk
? { tmdb: { type: tmdbType, id: tmdbId.trim() } }
: null
: requires === "mediaEntityId"
? entity
? { mediaEntityId: entity.id }
: null
: undefined;
return (
<ConfirmDialog
trigger={
<Button variant={variant} size="sm">
{option.label}
</Button>
}
title={option.label}
description={option.description ? `${option.description}。` : undefined}
confirmLabel={option.label}
confirmDisabled={identity === null}
onConfirm={() =>
resolve
.mutateAsync({
id: d.id,
optionKey: option.key,
note: note.trim() || undefined,
...(identity ? { identity } : {}),
})
.then(
() => toast.success(`已处理:${option.label}`),
(err) => {
toast.error(errorMessage(err, "处理失败"));
throw err;
},
)
}
>
{requires === "tmdb" ? (
<div className="grid gap-x-2 sm:grid-cols-[8rem_minmax(0,1fr)]">
<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`} required hint="纯数字,如 872585">
<Input
id={`${uid}-tmdb`}
inputMode="numeric"
value={tmdbId}
onChange={(e) => setTmdbId(e.target.value)}
aria-invalid={tmdbId.trim() !== "" && !tmdbOk}
/>
</FormField>
</div>
) : requires === "mediaEntityId" ? (
<FormField label="本地作品" required>
<EntityPicker value={entity} onChange={setEntity} />
</FormField>
) : null}
<FormField label="备注" htmlFor={`${uid}-note`} hint="可选,记在处理结果里">
<Textarea id={`${uid}-note`} value={note} onChange={(e) => setNote(e.target.value)} rows={2} />
</FormField>
</ConfirmDialog>
);
}
/** 事项里能拿来搜作品的名字:代表资源标题 / 种子名 / 下载名 / 标题冒号后半段 */
export function subjectName(d: DecisionLike): string | null {
const e = d.evidence;
const first = Array.isArray(e.releases) ? (e.releases[0] as { title?: unknown } | undefined) : undefined;
return (
str(first?.title) ??
str(e.torrentName) ??
str(e.title) ??
str(e.name) ??
(d.title.includes(":") ? d.title.split(":").slice(1).join(":") : null)
);
}
/** 搜作品用的关键词:去掉扩展名、分隔符、年份之后的规格串 */
export function queryOf(name: string | null): string {
if (!name) return "";
const base = name.replace(/\.(mkv|mp4|ts|m2ts|iso|avi)$/i, "").replace(/[._]+/g, " ");
const m = base.match(/^(.*?)(?:\b(19|20)\d{2}\b|\bS\d{1,2}E?\d{0,3}\b|\b(2160|1080|720)p\b)/i);
return (m?.[1]?.trim() || base)
.replace(/[[\]()]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 60);
}
/** 「没识别出作品」的主操作:搜作品并指定(本地作品 / TMDB),后端随即按该作品重新整理 */
export function AssignWorkButton({ d, variant = "default" }: { d: DecisionLike; variant?: "default" | "outline" }) {
const resolve = useResolveDecision();
const [open, setOpen] = useState(false);
const local = d.options.find((o) => o.input?.requires === "mediaEntityId");
const tmdb = d.options.find((o) => o.input?.requires === "tmdb");
if (!local && !tmdb) return null;
const name = subjectName(d);
const assign = (w: AssignedWork) => {
const option = "mediaEntityId" in w ? local : tmdb;
if (!option) {
toast.error("mediaEntityId" in w ? "这条记录只能按 TMDB 指定" : "这条记录只能选媒体库里的作品");
return Promise.reject(new Error("unsupported"));
}
return resolve
.mutateAsync({
id: d.id,
optionKey: option.key,
identity: "mediaEntityId" in w ? { mediaEntityId: w.mediaEntityId } : { tmdb: w.tmdb },
})
.then(
() => toast.success(`已指定为「${w.title}」,正在重新整理`),
(err) => {
toast.error(errorMessage(err, "指定失败"));
throw err;
},
);
};
return (
<>
<Button size="sm" variant={variant} onClick={() => setOpen(true)}>
<Search />
指定作品
</Button>
<WorkAssignDialog
open={open}
onOpenChange={setOpen}
subject={name}
initialQuery={queryOf(name)}
onAssign={assign}
/>
</>
);
}
@@ -25,7 +25,7 @@ describe("下载面板展示换算(DL-2)", () => {
expect(formatEta(3 * 86400 + 4 * 3600)).toBe("3 天 4 小时");
});
it("最近一次整理结果:已入库 / 整理中 / 待整理 / 入库失败 / 部分入库;有待处理事项时链到待处理", () => {
it("最近一次整理结果:已入库 / 整理中 / 待整理 / 入库失败 / 部分入库;有问题的链到整理记录就地处理", () => {
expect(organizeState({ status: "completed", organize: null })).toMatchObject({ label: "待整理", to: null });
expect(organizeState({ status: "importing", organize: null })?.label).toBe("整理中");
expect(organizeState({ status: "imported", organize: null })?.label).toBe("已入库");
@@ -48,7 +48,7 @@ describe("下载面板展示换算(DL-2)", () => {
tone: "destructive",
hint: "没识别出作品。指定作品后重新整理",
});
expect(failed?.to).toBe("/console/inbox?kind=identity_unresolved");
expect(failed?.to).toBe(`/console/organize/${RID}`);
expect(organizeState({ status: "completed", organize: rec("failed", { reason: "磁盘已满" }) })?.hint).toBe(
"磁盘已满",
);
@@ -58,7 +58,7 @@ describe("下载面板展示换算(DL-2)", () => {
);
expect(
organizeState({ status: "completed", organize: rec("partial", { reason: "blocked:target_exists" }) })?.hint,
).toBe("媒体库里已有同名文件。在待处理里选择替换或跳过");
).toBe("媒体库里已有同名文件。在整理记录里选择替换、保留两者或跳过");
// 不认识的码不显示
expect(
organizeState({ status: "completed", organize: rec("failed", { reason: "some_new_code" }) })?.hint,
@@ -28,7 +28,7 @@ export function formatEta(sec: number | null | undefined): string {
export type OrganizeState = {
label: string;
tone: "success" | "warning" | "destructive" | "neutral";
/** 点状态去哪:有未关闭的待处理事项去待处理,否则去整理记录;都没有为 null */
/** 点状态去哪:整理记录详情(有问题的在那里就地处理);没整理过为 null */
to: string | null;
/** 失败原因(人话);原因是内部码时不直接给人看 */
hint: string | null;
@@ -48,11 +48,8 @@ export function organizeState(
): OrganizeState | null {
const rec = t.organize;
if (t.managed === false && !rec && t.status !== "importing" && t.status !== "imported") return null;
const to = rec?.decision
? `${consolePath("inbox")}?kind=${rec.decision.kind}`
: rec
? consolePath("organize", rec.recordId)
: null;
// 有问题的整理在整理记录详情里就地处理(待处理中心已取消)
const to = rec ? consolePath("organize", rec.recordId) : null;
if (rec?.status === "succeeded" || (t.status === "imported" && rec?.status !== "failed"))
return { label: "已入库", tone: "success", to, hint: null };
if (rec?.status === "failed") return { label: "入库失败", tone: "destructive", to, hint: reasonHint(rec.reason) };
@@ -252,7 +252,7 @@ function OrganizeBadge({ t }: { t: DownloadBoardItem }) {
<Link
to={s.to}
onClick={(e) => e.stopPropagation()}
title={t.organize?.decision ? "去待处理" : "查看整理记录"}
title={t.organize?.decision ? "去整理记录处理" : "查看整理记录"}
className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{badge}
@@ -144,14 +144,14 @@ export function DownloadDetail({ task, live }: { task: DownloadTask; live?: Down
{importFailed ? (
<p className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-caption text-destructive">
入库失败:{reasonLine(importFailed.reason)}。
<Link to="/console/inbox" className="ml-1 underline underline-offset-4">
去待处理
<Link to={`/console/organize/${importFailed.id}`} className="ml-1 underline underline-offset-4">
去整理记录处理
</Link>
</p>
) : null}
{task.noProgressSince ? (
<p className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-caption text-warning">
自 {formatDateTime(task.noProgressSince)} 起无进展,已记入待处理,不会自动换源。
自 {formatDateTime(task.noProgressSince)} 起无进展,不会自动换源;开了自动调查时智能体会在授权内尝试恢复。
</p>
) : null}
+2 -13
View File
@@ -1,5 +1,5 @@
import type { DownloadBoardPlanItem } from "@umt/contracts";
import { Check, Inbox, X } from "lucide-react";
import { Check, X } from "lucide-react";
import { Link } from "react-router";
import { toast } from "sonner";
import { useDecideApproval, useIsAdminSession } from "~/api/agent.ts";
@@ -147,18 +147,7 @@ export function PlanDetail({ p }: { p: DownloadBoardPlanItem }) {
</div>
</div>
{p.wait === "approval" ? (
<p className="flex flex-wrap items-center gap-1 text-caption text-muted-foreground">
这次下载要你批准后才提交,同一件事也在待处理里。
{p.approval?.decisionId ? (
<Link
to={`${consolePath("inbox")}?kind=approval_required`}
className="inline-flex items-center gap-0.5 underline underline-offset-4"
>
<Inbox className="size-3.5" />
去待处理
</Link>
) : null}
</p>
<p className="text-caption text-muted-foreground">这次下载要你批准后才提交,铃铛里也有提醒。</p>
) : hint ? (
<p className="text-caption text-muted-foreground">{hint}。</p>
) : null}
@@ -20,7 +20,7 @@ import { Switch } from "~/components/ui/switch.tsx";
import { errorMessage } from "~/lib/api.ts";
import { canonicalText, episodeCode, mappingHref, RULE_KIND_LABEL, ruleText, scopeText, sourceText } from "./model.ts";
// 待处理中心里的「集数待确认」(episode_mapping):来源季集、原因、建议规则与它的模拟结果;
// 作品页集数映射里的「集数待确认」(episode_mapping 内部事项):来源季集、原因、建议规则与它的模拟结果;
// 操作「确认」(建建议规则并重算)、「修改」(跳作品页集数映射并预填草稿)、「忽略」(可同时建忽略规则)。
// 智能体建议(批次 5):后台调查没有写规则的授权时,把模拟通过的规则和理由留在事项上,「确认智能体建议」一键建规则
// (服务端建规则前按当前资源再模拟一次)。
@@ -0,0 +1,60 @@
import type { Decision } from "@umt/contracts";
import { useDecisions } from "~/api/decisions.ts";
import { humanizeReason } from "~/lib/reasons.ts";
import { EpisodeDecision } from "./decision.tsx";
// 集数待确认的原因(2026-10-06 去掉待处理中心后):不再作为逐条要处理的条目,
// 同一作品的问题聚合在作品页「集数映射」与订阅详情里显示原因;智能体建议 / 建议规则仍可在这里一键确认。
// 数据来自内部事项 episode_mapping(只给关注中的作品开,见 server sources-identity/service/watched.ts)。
const OPEN = ["open", "investigating", "awaiting_user"];
function entityOf(d: Decision): string | null {
const m = d.evidence.mediaEntityId;
return typeof m === "string" ? m : d.subjectType === "media_entity" ? d.subjectId : null;
}
/** 某作品(可选按来源季)未关闭的集数待确认事项 */
export function useEpisodeIssues(entityId: string | null | undefined, season?: number | null) {
const q = useDecisions({ kind: "episode_mapping" }, !!entityId);
const items = (q.data?.pages.flatMap((p) => p.items) ?? []).filter(
(d) =>
OPEN.includes(d.status) &&
entityOf(d) === entityId &&
(season == null || (d.evidence as { season?: unknown }).season === season),
);
return { ...q, items };
}
/** 作品页集数映射分区:逐组写原因,建议规则 / 智能体建议可确认 */
export function EpisodeIssuesList({ entityId }: { entityId: string }) {
const { items } = useEpisodeIssues(entityId);
if (!items.length) return null;
return (
<div className="space-y-3">
<p className="text-caption font-medium text-foreground">换算不了的资源({items.length} 组)</p>
<ul className="space-y-3">
{items.map((d) => (
<li key={d.id} className="rounded-lg border border-border/80 p-3">
<EpisodeDecision d={d} open />
</li>
))}
</ul>
</div>
);
}
/** 订阅详情:缺集原因一句一组(只读,处理去作品页) */
export function EpisodeIssueReasons({ entityId, season }: { entityId: string; season: number | null }) {
const { items } = useEpisodeIssues(entityId, season);
if (!items.length) return null;
return (
<ul className="mt-2 space-y-1 text-meta text-muted-foreground">
{items.map((d) => (
<li key={d.id} className="break-words">
{d.summary ? humanizeReason(d.summary) : d.title}
</li>
))}
</ul>
);
}
@@ -22,6 +22,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~
import { Textarea } from "~/components/ui/textarea.tsx";
import { errorMessage } from "~/lib/api.ts";
import { actorText } from "~/lib/labels.ts";
import { EpisodeIssuesList } from "./issues.tsx";
import {
agentRuleInfo,
disabledReasonText,
@@ -413,7 +414,7 @@ export function EpisodeMappingPanel({ entityId }: { entityId: string }) {
</ul>
) : (
<p className="text-caption text-muted-foreground">
还没有规则。资源的集数先按原号、绝对集号和播出日期自动判定,对不上的进待处理。
还没有规则。资源的集数先按原号、绝对集号和播出日期自动判定,换算不了的在这里列出原因。
</p>
)}
@@ -440,6 +441,7 @@ export function EpisodeMappingPanel({ entityId }: { entityId: string }) {
) : null}
{preview.data ? <GroupStats groups={preview.data.groups} onUseSuggestion={adoptSuggestion} /> : null}
<EpisodeIssuesList entityId={entityId} />
</Panel>
<Panel
className="mt-3"
@@ -5,6 +5,7 @@ import { useEntityDetail } from "~/api/library.ts";
import { consolePath } from "~/components/console/nav.ts";
import { StatusBadge } from "~/components/console/status-badge.tsx";
import { Panel } from "~/components/library/parts.tsx";
import { EpisodeIssueReasons } from "./issues.tsx";
import { absoluteGroups, groupMethodsText, mappingHref } from "./model.ts";
// 订阅详情的集数映射摘要 + 订阅表单的绝对集号提示(批次 4)。数据来自模拟预览(不带草稿 = 当前规则)。
@@ -54,6 +55,8 @@ export function SubscriptionMappingSummary({
{pending ? (
<div className="mt-2">
<StatusBadge tone="warning">待确认 {pending} 条</StatusBadge>
<p className="mt-1 text-meta text-muted-foreground">这些资源集数对不上,不会下载和整理。</p>
<EpisodeIssueReasons entityId={entityId} season={season} />
</div>
) : null}
</Panel>
@@ -1,5 +1,5 @@
import type { IdentityPoolItem, PoolCandidate } from "@umt/contracts";
import { ArrowRight, BellOff, ExternalLink, LoaderCircle, RotateCw } from "lucide-react";
import { BellOff, ExternalLink, LoaderCircle, RotateCw } from "lucide-react";
import { useId, useState } from "react";
import { Link } from "react-router";
import { toast } from "sonner";
@@ -19,25 +19,8 @@ import { EnrichSection } from "./identity-enrich.tsx";
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;
}
// 未识别资源详情:候选证据 + 重新识别 + 选候选 / 手动指定 / 忽略。
// 2026-10-06 起待处理中心取消:搜索 / RSS 扫进来的未识别资源静默留在这里,不再提示;要处理的直接在这里选。
/** query 摘要:标题 / 年份 / 季集 */
export function querySummary(q: Record<string, unknown>): string {
@@ -51,7 +34,7 @@ export function querySummary(q: Record<string, unknown>): string {
return parts.join(" · ") || "—";
}
function CandidateRow({ c, index }: { c: PoolCandidate; index: number }) {
function CandidateRow({ c, index, onPick }: { c: PoolCandidate; index: number; onPick?: () => void }) {
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">
@@ -67,6 +50,11 @@ function CandidateRow({ c, index }: { c: PoolCandidate; index: number }) {
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<Chip>{EVIDENCE_LEVEL[c.level] ?? c.level}</Chip>
{onPick ? (
<Button variant="outline" size="xs" className="order-last ml-auto" onClick={onPick}>
选这个
</Button>
) : null}
{c.localEntityId ? (
<Link
to={consolePath("library", c.localEntityId)}
@@ -185,8 +173,16 @@ function ManualAssign({ item }: { item: IdentityPoolItem }) {
export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; onClose: () => void }) {
const retry = useRetryPool();
const assign = useAssignPool();
if (!item) return null;
const queued = inInbox(item);
const pick = async (index: number) => {
try {
await assign.mutateAsync({ id: item.id, candidateIndex: index, lock: true });
toast.success("已指定");
} catch (err) {
toast.error(errorMessage(err, "指定失败"));
}
};
return (
<DetailSheet
@@ -196,38 +192,23 @@ export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; on
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}
</>
<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 ? (
<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]} /> },
@@ -242,7 +223,7 @@ export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; on
]}
/>
{item.status !== "resolved" && !queued ? <ManualAssign item={item} /> : null}
{item.status !== "resolved" ? <ManualAssign item={item} /> : null}
{item.status === "pending" && item.reason !== "ambiguous" && item.reason !== "proposed" ? (
<EnrichSection key={item.id} item={item} />
@@ -252,7 +233,12 @@ export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; on
{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} />
<CandidateRow
key={`${c.provider}:${c.entityType}:${c.externalId}`}
c={c}
index={i}
onPick={item.status === "pending" && !assign.isPending ? () => void pick(i) : undefined}
/>
))}
</ul>
) : (
@@ -5,14 +5,13 @@ import type {
IdentityPoolItem,
IdentityStatus,
} from "@umt/contracts";
import { ArrowRight, Fingerprint, Lock, SearchX } from "lucide-react";
import { Fingerprint, Lock, SearchX } from "lucide-react";
import { useEffect, useState } from "react";
import { Link } from "react-router";
import { useExternalIdentities, useIdentityPool } from "~/api/identity.ts";
import { type DataColumn, DataTable } from "~/components/console/data-table.tsx";
import { FilterBar, FilterSelect } from "~/components/console/filter-bar.tsx";
import { ExternalIdentitySheet, identityRef } from "~/components/library/identity-external-sheet.tsx";
import { inboxLink, inInbox, PoolSheet, querySummary } from "~/components/library/identity-pool-sheet.tsx";
import { PoolSheet, querySummary } from "~/components/library/identity-pool-sheet.tsx";
import {
EVIDENCE_LEVEL,
IDENTITY_STATUS,
@@ -24,7 +23,7 @@ import {
import { relTime, Tone } from "~/components/library/parts.tsx";
// 媒体概览的身份视图(原"身份与元数据"页,IA-3 并入 /console/library):待识别资源、外部身份。
// 待识别资源只读;选候选、忽略在待处理里做(docs/design/console-ia.md §3.1 判定只在待处理)。
// 未识别资源:点开详情选候选、手动指定或忽略(2026-10-06 起待处理中心取消,不再转去待处理)。
function useDebounced(v: string, ms = 250) {
const [d, setD] = useState(v);
@@ -69,16 +68,6 @@ export function PoolTab() {
cell: (r) => (
<div className="flex flex-col items-start gap-1">
<Tone v={POOL_REASON[r.reason]} />
{inInbox(r) ? (
<Link
to={inboxLink(r)}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-0.5 text-meta whitespace-nowrap text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
已进待处理
<ArrowRight className="h-3 w-3" />
</Link>
) : null}
</div>
),
},
@@ -0,0 +1,107 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { PublicOrganizationRecord, RecordAttention } from "@umt/contracts";
import { createElement, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import { attentionLine, primaryAction, RecordAttentionActions } from "./record-attention.tsx";
// 整理记录「需要处理」的行内处理(2026-10-06 去掉待处理中心):原因一句话 + 推荐动作,一键执行。
const D = "11111111-1111-4111-8111-111111111111";
const R = "22222222-2222-4222-8222-222222222222";
const render = (node: ReactNode) =>
renderToStaticMarkup(
createElement(QueryClientProvider, { client: new QueryClient() }, createElement(MemoryRouter, null, node)),
);
const decision = (over: Partial<NonNullable<RecordAttention["decision"]>> = {}) => ({
id: D,
kind: "identity_ambiguous" as const,
status: "open" as const,
title: "没识别出作品:Foo.2019.1080p",
summary: null,
options: [
{ key: "candidate_0", label: "Foo (2019)", input: { candidate: { mediaEntityId: R } } },
{ key: "select_entity", label: "选择作品(本地)", input: { requires: "mediaEntityId" } },
{ key: "select_tmdb", label: "选择作品(TMDB)", input: { requires: "tmdb" } },
{ key: "provisional", label: "作为临时作品入库", input: {} },
{ key: "dismiss", label: "忽略" },
],
agentRunId: null,
evidence: { downloadTaskId: R, torrentName: "Foo.2019.1080p" },
...over,
});
type Rec = Pick<PublicOrganizationRecord, "id" | "action" | "status" | "attention" | "reason">;
const rec = (attention: RecordAttention | null, over: Partial<Rec> = {}): Rec => ({
id: R,
action: "copy",
status: "failed",
reason: null,
attention,
...over,
});
const html = (r: Rec) => render(createElement(RecordAttentionActions, { r, onReorganize: () => {} }));
describe("整理记录行内处理", () => {
it("没识别出作品:主操作指定作品,可让智能体识别、重新整理、忽略", () => {
const r = rec({ topic: "identity", decision: decision(), agentIdentify: true });
expect(primaryAction(r)).toBe("assign");
expect(attentionLine(r)).toBe("没识别出作品。指定作品,或让智能体识别");
const out = html(r);
for (const t of ["指定作品", "让智能体识别", "重新整理", "忽略", "Foo (2019)"]) expect(out).toContain(t);
// 「选择作品(本地 / TMDB)」并进「指定作品」,不单列;临时作品不在行内
expect(out).not.toContain("选择作品(本地)");
expect(out).not.toContain("作为临时作品入库");
});
it("智能体识别中:显示进度与会话入口,不再给指定 / 识别按钮", () => {
const r = rec({
topic: "identity",
decision: decision({ status: "investigating", agentRunId: D }),
agentIdentify: true,
});
expect(attentionLine(r)).toContain("智能体正在识别作品");
const out = html(r);
expect(out).toContain("智能体识别中");
expect(out).toContain(`/console/agent/${D}`);
expect(out).not.toContain("让智能体识别");
expect(out).not.toContain("指定作品");
});
it("目标已存在:按事项选项给替换 / 保留两者 / 跳过", () => {
const r = rec({
topic: "conflict",
decision: decision({
kind: "path_conflict",
summary: "媒体库里已有同名文件",
options: [
{ key: "replace", label: "替换" },
{ key: "keep_both", label: "保留两者" },
{ key: "skip", label: "跳过" },
],
}),
agentIdentify: false,
});
expect(primaryAction(r)).toBe("options");
expect(attentionLine(r)).toBe("媒体库里已有同名文件");
const out = html(r);
for (const t of ["替换", "保留两者", "跳过", "忽略"]) expect(out).toContain(t);
expect(out).not.toContain("让智能体识别");
});
it("其它失败:重新整理为主操作", () => {
const r = rec({ topic: "other", decision: null, agentIdentify: false });
expect(primaryAction(r)).toBe("reorganize");
const out = html(r);
expect(out).toContain("重新整理");
expect(out).toContain("忽略");
});
it("不需要处理的记录不渲染", () => {
expect(html(rec(null, { status: "succeeded" }))).toBe("");
expect(attentionLine(rec(null))).toBeNull();
});
});
@@ -0,0 +1,130 @@
import type { PublicOrganizationRecord } from "@umt/contracts";
import { BellOff, Bot, ChevronRight, LoaderCircle, Wand2 } from "lucide-react";
import { Link } from "react-router";
import { toast } from "sonner";
import { useAgentIdentifyRecord, useDismissRecordAttention } from "~/api/records.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
import { consolePath } from "~/components/console/nav.ts";
import {
AssignWorkButton,
canAssignWork,
OptionButton,
plainOptions,
} from "~/components/decisions/decision-actions.tsx";
import { Button } from "~/components/ui/button.tsx";
import { errorMessage } from "~/lib/api.ts";
import { humanizeReason } from "~/lib/reasons.ts";
import { canReorganize } from "./record-parts.ts";
// 整理记录「需要处理」的行内处理(2026-10-06 去掉待处理中心后,整理侧的问题在这里就地处理):
// 没识别出作品 → 指定作品(主操作)/ 让智能体识别 / 忽略;识别中显示进度与会话入口;
// 目标已存在 / 路径冲突 → 事项给的选项(替换 / 保留两者 / 跳过);
// 其余失败 / 部分完成 → 重新整理 / 忽略。执行都走已有端点(/decisions/{id}/resolve、整理向导、忽略)。
type Rec = Pick<PublicOrganizationRecord, "id" | "action" | "status" | "attention" | "reason">;
/** 一句话说清这条记录卡在哪(事项摘要优先,其次记录原因) */
export function attentionLine(r: Rec): string | null {
const a = r.attention;
if (!a) return null;
if (a.decision?.status === "investigating") return "智能体正在识别作品,认出来会自动重新整理";
if (a.topic === "identity") return "没识别出作品。指定作品,或让智能体识别";
return a.decision?.summary ? humanizeReason(a.decision.summary) : null;
}
/** 推荐的主动作(给列表文字提示与测试用):identity → 指定作品;conflict → 事项选项;other → 重新整理 */
export function primaryAction(r: Rec): "assign" | "options" | "reorganize" | null {
const a = r.attention;
if (!a) return null;
if (a.topic === "identity" && a.decision && canAssignWork(a.decision)) return "assign";
if (a.topic === "conflict" && a.decision && plainOptions(a.decision).length) return "options";
return canReorganize(r) ? "reorganize" : null;
}
export function RecordAttentionActions({
r,
onReorganize,
compact = false,
}: {
r: Rec;
onReorganize: () => void;
compact?: boolean;
}) {
const identify = useAgentIdentifyRecord();
const dismiss = useDismissRecordAttention();
const a = r.attention;
if (!a) return null;
const d = a.decision;
const investigating = d?.status === "investigating";
const primary = primaryAction(r);
return (
// 行点击会进详情;按钮区不冒泡
// biome-ignore lint/a11y/noStaticElementInteractions: 只拦截冒泡,不是交互元素
// biome-ignore lint/a11y/useKeyWithClickEvents: 同上
<div className="flex flex-wrap items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
{investigating && d?.agentRunId ? (
<Button asChild variant="ghost" size="sm">
<Link to={consolePath("agent", d.agentRunId)}>
<LoaderCircle className="animate-spin" />
智能体识别中
<ChevronRight />
</Link>
</Button>
) : null}
{primary === "assign" && d && !investigating ? <AssignWorkButton d={d} /> : null}
{primary === "options" && d
? plainOptions(d).map((o, i) => (
<OptionButton key={o.key} d={d} option={o} variant={i === 0 ? "default" : "outline"} />
))
: null}
{a.topic === "identity" && d && !investigating
? plainOptions(d)
.filter((o) => !compact && o.key !== "provisional")
.slice(0, 2)
.map((o) => <OptionButton key={o.key} d={d} option={o} />)
: null}
{canReorganize(r) && !investigating && (!compact || primary === "reorganize") ? (
<Button size="sm" variant={primary === "reorganize" ? "default" : "outline"} onClick={onReorganize}>
<Wand2 />
重新整理
</Button>
) : null}
{a.agentIdentify && !investigating ? (
<Button
size="sm"
variant="outline"
disabled={identify.isPending}
onClick={() =>
identify.mutateAsync(r.id).then(
(x) => toast.success(x.queued ? "已让智能体识别,认出来会自动重新整理" : "智能体已经在识别了"),
(err) => toast.error(errorMessage(err, "操作失败")),
)
}
>
<Bot />
让智能体识别
</Button>
) : null}
<ConfirmDialog
trigger={
<Button variant="ghost" size="sm">
<BellOff />
忽略
</Button>
}
title="忽略这条记录的问题?"
description="不再算需要处理,文件和记录都不动;之后可以随时重新整理。"
confirmLabel="忽略"
onConfirm={() =>
dismiss.mutateAsync(r.id).then(
() => toast.success("已忽略"),
(err) => {
toast.error(errorMessage(err, "操作失败"));
throw err;
},
)
}
/>
</div>
);
}
+22 -28
View File
@@ -1,15 +1,13 @@
import { AgentSpendSummary } from "~/components/status/attention-cards.tsx";
import { kToTokens, tokensToK } from "~/lib/tokens.ts";
import { AgentToolsBlock } from "./agent-tools.tsx";
import { WEBSEARCH_CARD } from "./agent-websearch.tsx";
import { PiUpstreamsBlock } from "./pi-upstreams.tsx";
import type { FieldSpec, FieldValue } from "./resource-section.tsx";
import type { FieldSpec } from "./resource-section.tsx";
import { num, str } from "./resource-section.tsx";
import { type CardSpec, n, SettingsCard, SettingsGate } from "./settings-card.tsx";
// Agent 分区:上游(pi_upstream)+ 上下文与子代理(pi)+ 预算(budget.agent* 与单次上限)+ 自动调查 + 网页搜索 + 高级
/** 可清空的数字:空串 → null */
const nullNum = (v: FieldValue | undefined) => (str(v) === "" ? null : Number(str(v)));
// Agent 分区:上游(pi_upstream)+ 上下文与子代理(pi)+ 用量与限制(单次防跑飞上限 + 花费统计)+ 自动调查 + 网页搜索 + 高级
const RUNTIME_CARD: CardSpec = {
anchor: "runtime",
@@ -50,51 +48,45 @@ const RUNTIME_CARD: CardSpec = {
}),
};
// 2026-10-06:不设每日次数 / 每日花费 / 单次花费 / 单次 token 上限(旧值兼容读取、不生效),
// 只保留单次工具调用次数与时长两个防跑飞限制;花费在这里与运行状态里可见
const BUDGET_CARD: CardSpec = {
anchor: "budget",
title: "预算",
description: "超出每日预算的运行停在「超出预算」,等你放行。",
title: "用量与限制",
description: "不限次数和花费。单次运行只限制工具调用次数和时长,防止跑飞。",
fields: [
{ name: "budget.agentMaxRunsPerDay", label: "每日运行次数", kind: "number" },
{ name: "budget.agentMaxCostUsdPerDay", label: "每日费用(USD)", kind: "number" },
{ name: "agent.maxToolCalls", label: "单次工具调用上限", kind: "number", hint: "1–500" },
{ name: "agent.maxDurationSec", label: "单次时长上限(秒)", kind: "number" },
{
name: "agent.maxTokensPerRun",
label: "单次 token 上限",
kind: "tokens",
tokens: { min: 1 },
hint: "单位 K,留空不限",
},
{ name: "agent.maxCostUsdPerRun", label: "单次费用上限(USD)", kind: "number", hint: "留空不限" },
],
fromSettings: (s) => ({
"budget.agentMaxRunsPerDay": n(s.budget.agentMaxRunsPerDay),
"budget.agentMaxCostUsdPerDay": n(s.budget.agentMaxCostUsdPerDay),
"agent.maxToolCalls": n(s.agent.maxToolCalls),
"agent.maxDurationSec": n(s.agent.maxDurationSec),
"agent.maxTokensPerRun": tokensToK(s.agent.maxTokensPerRun),
"agent.maxCostUsdPerRun": n(s.agent.maxCostUsdPerRun),
}),
toPatch: (v) => ({
budget: {
agentMaxRunsPerDay: num(v["budget.agentMaxRunsPerDay"]),
agentMaxCostUsdPerDay: num(v["budget.agentMaxCostUsdPerDay"]),
},
agent: {
maxToolCalls: num(v["agent.maxToolCalls"]),
maxDurationSec: num(v["agent.maxDurationSec"]),
maxTokensPerRun: kToTokens(str(v["agent.maxTokensPerRun"])) ?? null,
maxCostUsdPerRun: nullNum(v["agent.maxCostUsdPerRun"]),
},
}),
extra: () => (
<div className="border-t border-border/60 pt-4">
<AgentSpendSummary />
</div>
),
};
const INVESTIGATE_CARD: CardSpec = {
anchor: "investigate",
title: "自动调查",
description: "待处理事项(没识别出作品、下载失败等)创建时,自动发起一次有界调查。",
description: "下载完识别不到作品时叫智能体识别;下载失败、集数对不上等问题出现时,自动发起一次有界调查。",
fields: [
{
name: "agent.autoIdentifyOrganize",
label: "整理识别不到作品时叫智能体识别",
kind: "switch",
wide: true,
hint: "认出来自动重新整理;认不出的留在整理记录「需要处理」里",
},
{ name: "agent.autoInvestigate", label: "自动调查", kind: "switch", wide: true },
{
name: "agent.autoInvestigateMode",
@@ -131,6 +123,7 @@ const INVESTIGATE_CARD: CardSpec = {
},
],
fromSettings: (s) => ({
"agent.autoIdentifyOrganize": s.agent.autoIdentifyOrganize,
"agent.autoInvestigate": s.agent.autoInvestigate,
"agent.autoInvestigateMode": s.agent.autoInvestigateMode,
"agent.investigateMaxToolCalls": n(s.agent.investigateMaxToolCalls),
@@ -139,6 +132,7 @@ const INVESTIGATE_CARD: CardSpec = {
}),
toPatch: (v) => ({
agent: {
autoIdentifyOrganize: v["agent.autoIdentifyOrganize"] === true,
autoInvestigate: v["agent.autoInvestigate"] === true,
autoInvestigateMode: v["agent.autoInvestigateMode"] === "recover" ? "recover" : "investigate",
investigateMaxToolCalls: num(v["agent.investigateMaxToolCalls"]),
@@ -172,7 +172,7 @@ function FailureRow({ result, onUseCookie }: { result: SiteLoginResult; onUseCoo
) : null}
{result.decisionId ? (
<Button asChild size="xs" variant="ghost">
<Link to={consolePath("inbox")}>查看待处理</Link>
<Link to={`${consolePath("status")}#attention`}>查看运行状态</Link>
</Button>
) : null}
</span>
+1 -1
View File
@@ -317,7 +317,7 @@ export function loginFailureText(
return { text: "登录失败:站点要求二次验证。填写 TOTP 密钥后重试,或改用 Cookie", suggestCookie: true };
case "challenge":
return {
text: "站点要求人机验证(Cloudflare)。会用浏览器自动过,过不去时在待处理里提醒你",
text: "站点要求人机验证(Cloudflare)。会用浏览器自动过,过不去时在铃铛里提醒你",
suggestCookie: false,
};
case "bad_credentials":
@@ -0,0 +1,129 @@
import type { AgentSpendBucket, AgentSpendKind } from "@umt/contracts";
import { BellRing, Bot } from "lucide-react";
import { Link } from "react-router";
import { useAgentSpend, useAttention } from "~/api/attention.ts";
import { ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { settingsPath } from "~/components/console/nav.ts";
import { AttentionList, attentionRows } from "~/components/dashboard/attention-summary.tsx";
import { formatRelative } from "~/lib/labels.ts";
import { humanizeReason } from "~/lib/reasons.ts";
// 运行状态页(2026-10-06):「需要关注」汇总(整理需要处理、等你批准、系统健康,系统健康逐条列出、恢复后自动消失)
// 与智能体用量(今天 / 最近 7 天按会话类型;不设上限,只展示)。
function Slab({
id,
title,
icon: Icon,
children,
}: {
id?: string;
title: string;
icon: typeof Bot;
children: React.ReactNode;
}) {
return (
<section id={id} className="pg-slab min-w-0 scroll-mt-20 rounded-xl p-5">
<div className="mb-3 flex items-center gap-2">
<Icon className="h-4 w-4 text-muted-foreground" />
<h2 className="text-body font-semibold text-foreground">{title}</h2>
</div>
{children}
</section>
);
}
export function AttentionCard() {
const q = useAttention();
const rows = attentionRows(q.data);
const health = q.data?.health.items ?? [];
return (
<Slab id="attention" title="需要关注" icon={BellRing}>
{q.isPending ? (
<LoadingState rows={2} />
) : q.isError ? (
<ErrorState plain error={q.error} onRetry={() => q.refetch()} />
) : rows.length === 0 ? (
<p className="text-caption text-muted-foreground">
没有需要处理的整理记录,也没有等你批准的操作;站点、下载器和下载目录都正常。
</p>
) : (
<>
<AttentionList rows={rows} />
{health.length ? (
<ul className="mt-3 space-y-2 border-t border-border/60 pt-3">
{health.map((d) => (
<li key={d.id} className="min-w-0 text-caption">
<p className="font-medium break-words text-foreground">{d.title}</p>
{d.summary ? (
<p className="break-words text-meta text-muted-foreground">{humanizeReason(d.summary)}</p>
) : null}
<p className="text-meta text-muted-foreground">{formatRelative(d.createdAt)}起,恢复后自动消失</p>
</li>
))}
</ul>
) : null}
</>
)}
</Slab>
);
}
const KIND_LABEL: Record<AgentSpendKind, string> = {
chat: "对话",
patrol: "巡检",
investigate: "后台调查",
organize_identify: "整理识别",
subagent: "子会话",
};
const usd = (n: number) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
function SpendBlock({ label, b }: { label: string; b: AgentSpendBucket }) {
return (
<div className="min-w-0">
<p className="text-meta text-muted-foreground">{label}</p>
<p className="text-title-sm font-semibold text-foreground tabular-nums">
{usd(b.costUsd)}
<span className="ml-1.5 text-caption font-normal text-muted-foreground">{b.runs} 次</span>
</p>
{b.byKind.length ? (
<ul className="mt-1 space-y-0.5 text-meta text-muted-foreground tabular-nums">
{b.byKind.map((k) => (
<li key={k.kind}>
{KIND_LABEL[k.kind]} {k.runs} 次 · {usd(k.costUsd)}
</li>
))}
</ul>
) : null}
</div>
);
}
/** 智能体用量(设置页「用量与限制」也用) */
export function AgentSpendSummary() {
const q = useAgentSpend();
if (q.isPending) return <LoadingState rows={2} />;
if (q.isError) return <ErrorState plain error={q.error} onRetry={() => q.refetch()} />;
if (!q.data.last7d.runs) return <p className="text-caption text-muted-foreground">最近 7 天智能体没有运行。</p>;
return (
<div className="grid gap-4 sm:grid-cols-2">
<SpendBlock label="今天" b={q.data.today} />
<SpendBlock label="最近 7 天" b={q.data.last7d} />
</div>
);
}
export function AgentSpendCard() {
return (
<Slab title="智能体用量" icon={Bot}>
<AgentSpendSummary />
<p className="mt-3 text-meta text-muted-foreground">
不设次数和花费上限,只限制单次的工具调用次数与时长。
<Link to={settingsPath("agent", "budget")} className="ml-1 underline-offset-4 hover:underline">
调整
</Link>
</p>
</Slab>
);
}
+2 -1
View File
@@ -124,8 +124,9 @@ export function businessLink(b: EngineRun["business"], input?: unknown): { to: s
return { to: `${consolePath("sources")}?feed=${encodeURIComponent(id)}`, label: "RSS" };
case "site":
return { to: `/console/sites/${id}`, label: "站点" };
// 事项是内部机制(2026-10-06 待处理中心取消),不单独链出
case "decision":
return { to: consolePath("inbox"), label: "待处理" };
return null;
case "media":
return { to: `/console/library/${id}`, label: "作品" };
default: