droboticflow-new/src/pages/ObjectSync.tsx
2026-07-28 20:43:46 +08:00

1134 lines
53 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import {
Activity,
AlertTriangle,
Boxes,
CheckCircle2,
ChevronRight,
CircleOff,
CloudUpload,
Download,
FileClock,
Fingerprint,
KeyRound,
Laptop,
Loader2,
PackageCheck,
Plus,
RefreshCw,
RotateCw,
ShieldCheck,
XCircle,
} from "lucide-react";
import { useUser } from "../context/UserContext";
import { useTimeZone } from "../context/TimeZoneContext";
import { getActionErrorMessage } from "../lib/action-errors.js";
import { formatCompactDateTime } from "../lib/datetime";
import { cn } from "../lib/utils";
import {
objectSyncApi,
type ObjectSyncAuditEvent,
type ObjectSyncAuthorization,
type ObjectSyncClientRelease,
type ObjectSyncCredential,
type ObjectSyncDevice,
type ObjectSyncItem,
type ObjectSyncRelease,
type ObjectSyncSession,
type ObjectSyncSpace,
} from "../services/api/object-sync";
import { storageConnectionsApi } from "../services/api/storage-connections";
import type { StorageConnection } from "../types";
type ViewKey = "overview" | "spaces" | "devices" | "sessions" | "conflicts" | "releases" | "audit" | "updates";
const capabilityLabels: Record<string, { label: string; className: string }> = {
unverified: { label: "未探测", className: "text-slate-300 bg-slate-500/10 border-slate-500/20" },
create_only: { label: "仅创建", className: "text-sky-300 bg-sky-500/10 border-sky-500/20" },
update_enabled: { label: "条件更新", className: "text-emerald-300 bg-emerald-500/10 border-emerald-500/20" },
drifted: { label: "发现漂移", className: "text-amber-300 bg-amber-500/10 border-amber-500/20" },
unsupported: { label: "不支持", className: "text-rose-300 bg-rose-500/10 border-rose-500/20" },
};
const statusTone = (status: string) => {
if (["completed", "committed", "published", "active", "approved"].includes(status)) return "text-emerald-300";
if (["failed", "denied", "revoked", "aborted", "drifted"].includes(status)) return "text-rose-300";
if (["conflicted", "kept_both", "partial", "pending"].includes(status)) return "text-amber-300";
return "text-sky-300";
};
const formatBytes = (value: number) => {
if (!value) return "0 B";
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
let unit = 0;
let current = value;
while (current >= 1024 && unit < units.length - 1) {
current /= 1024;
unit += 1;
}
return `${current.toFixed(current >= 10 ? 0 : 1)} ${units[unit]}`;
};
function CapabilityBadge({ state }: { state: string }) {
const tone = capabilityLabels[state] || capabilityLabels.unverified;
return (
<span className={cn("inline-flex rounded-md border px-2 py-1 text-[11px] font-semibold", tone.className)}>
{tone.label}
</span>
);
}
function EmptyState({ title, detail }: { title: string; detail: string }) {
return (
<div className="flex min-h-56 flex-col items-center justify-center border-t border-[#292b30] px-6 text-center">
<CircleOff className="mb-4 h-8 w-8 text-slate-600" />
<p className="text-sm font-semibold text-slate-200">{title}</p>
<p className="mt-1 max-w-lg text-xs leading-5 text-slate-500">{detail}</p>
</div>
);
}
function Metric({
label,
value,
detail,
icon: Icon,
}: {
label: string;
value: string | number;
detail: string;
icon: typeof Activity;
}) {
return (
<div className="border-l border-[#303238] pl-5 first:border-l-0 first:pl-0">
<div className="flex items-center gap-2 text-xs text-slate-500">
<Icon className="h-3.5 w-3.5" />
{label}
</div>
<div className="mt-2 text-2xl font-semibold tracking-tight text-white">{value}</div>
<div className="mt-1 text-xs text-slate-500">{detail}</div>
</div>
);
}
function SectionTitle({ title, detail, action }: { title: string; detail: string; action?: ReactNode }) {
return (
<div className="flex flex-col gap-3 border-b border-[#292b30] px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="text-base font-semibold text-white">{title}</h2>
<p className="mt-1 text-xs leading-5 text-slate-500">{detail}</p>
</div>
{action}
</div>
);
}
export default function ObjectSync() {
const { role } = useUser();
const { timeZone } = useTimeZone();
const [activeView, setActiveView] = useState<ViewKey>("overview");
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState("");
const [actionMessage, setActionMessage] = useState("");
const [busyKey, setBusyKey] = useState("");
const [spaces, setSpaces] = useState<ObjectSyncSpace[]>([]);
const [sessions, setSessions] = useState<ObjectSyncSession[]>([]);
const [conflicts, setConflicts] = useState<ObjectSyncItem[]>([]);
const [devices, setDevices] = useState<ObjectSyncDevice[]>([]);
const [authorizations, setAuthorizations] = useState<ObjectSyncAuthorization[]>([]);
const [credentials, setCredentials] = useState<ObjectSyncCredential[]>([]);
const [releases, setReleases] = useState<ObjectSyncRelease[]>([]);
const [audit, setAudit] = useState<ObjectSyncAuditEvent[]>([]);
const [clientReleases, setClientReleases] = useState<ObjectSyncClientRelease[]>([]);
const [connections, setConnections] = useState<StorageConnection[]>([]);
const [isSpaceFormOpen, setIsSpaceFormOpen] = useState(false);
const [spaceDraft, setSpaceDraft] = useState({
name: "",
description: "",
connectionId: "",
bucket: "",
rootPrefix: "",
});
const [releaseDraft, setReleaseDraft] = useState({ name: "", description: "", sessionIds: "" });
const [pairingCode, setPairingCode] = useState("");
const isAdmin = role === "admin";
const isPipeline = role === "pipeline_engineer" || role === "operator";
const isAuditor = role === "compliance_auditor" || role === "auditor";
const views = useMemo(
() =>
[
{ key: "overview" as const, label: "总览", visible: true },
{ key: "spaces" as const, label: "同步空间", visible: isAdmin },
{ key: "devices" as const, label: "设备与授权", visible: isAdmin },
{ key: "sessions" as const, label: "Session", visible: !isAuditor },
{ key: "conflicts" as const, label: "冲突", visible: !isAuditor },
{ key: "releases" as const, label: "Release", visible: isAdmin || isPipeline },
{ key: "audit" as const, label: "审计", visible: isAdmin || isAuditor },
{ key: "updates" as const, label: "客户端更新", visible: isAdmin },
].filter((item) => item.visible),
[isAdmin, isAuditor, isPipeline],
);
const load = useCallback(
async (silent = false) => {
if (silent) setRefreshing(true);
else setLoading(true);
setError("");
try {
const [
nextSpaces,
nextSessions,
nextDevices,
nextAuthorizations,
nextCredentials,
nextReleases,
nextAudit,
nextClientReleases,
nextConnections,
] = await Promise.all([
objectSyncApi.listSpaces(),
objectSyncApi.listSessions(),
isAdmin ? objectSyncApi.listDevices() : Promise.resolve([]),
isAdmin ? objectSyncApi.listAuthorizations() : Promise.resolve([]),
isAdmin ? objectSyncApi.listCredentials() : Promise.resolve([]),
isAdmin || isPipeline ? objectSyncApi.listReleases() : Promise.resolve([]),
isAdmin || isAuditor ? objectSyncApi.listAudit() : Promise.resolve([]),
isAdmin ? objectSyncApi.listClientReleases() : Promise.resolve([]),
isAdmin ? storageConnectionsApi.list() : Promise.resolve([]),
]);
const conflictSessions = nextSessions.filter(
(item) => item.counts.keptBoth > 0 || item.status === "conflicted",
);
const conflictPages = await Promise.all(
conflictSessions.map((session) => objectSyncApi.getSessionItems(session.id, "kept_both")),
);
setSpaces(nextSpaces);
setSessions(nextSessions);
setConflicts(conflictPages.flatMap((page) => page.items));
setDevices(nextDevices);
setAuthorizations(nextAuthorizations);
setCredentials(nextCredentials);
setReleases(nextReleases);
setAudit(nextAudit);
setClientReleases(nextClientReleases);
setConnections(nextConnections);
setSpaceDraft((previous) => ({
...previous,
connectionId: previous.connectionId || nextConnections[0]?.id || "",
bucket: previous.bucket || nextConnections[0]?.bucket || "",
}));
} catch (loadError) {
setError(getActionErrorMessage(loadError, "加载 drosync 控制面失败"));
} finally {
setLoading(false);
setRefreshing(false);
}
},
[isAdmin, isAuditor, isPipeline],
);
useEffect(() => {
void load();
}, [load]);
const runAction = async (key: string, action: () => Promise<unknown>, message: string) => {
setBusyKey(key);
setError("");
setActionMessage("");
try {
await action();
setActionMessage(message);
await load(true);
} catch (actionError) {
setError(getActionErrorMessage(actionError, "drosync 操作失败"));
} finally {
setBusyKey("");
}
};
const findPairingRequest = async () => {
const normalizedCode = pairingCode.trim().replace(/[-\s]/g, "").toUpperCase();
if (!normalizedCode) return;
setBusyKey("pairing-lookup");
setError("");
setActionMessage("");
try {
const item = await objectSyncApi.findAuthorizationByCode(normalizedCode);
setAuthorizations((previous) => [item, ...previous.filter((candidate) => candidate.id !== item.id)]);
setPairingCode(normalizedCode);
setActionMessage(`已载入设备 ${item.deviceName},请核对后分配同步空间与 scope。`);
} catch (lookupError) {
setError(getActionErrorMessage(lookupError, "未找到可审批的配对短码"));
} finally {
setBusyKey("");
}
};
const pendingApprovals = authorizations.filter((item) => item.status === "pending");
const activeSessions = sessions.filter((item) =>
["collecting_manifest", "planning", "planned", "running"].includes(item.status),
);
const readySpaces = spaces.filter((item) => item.enabled);
const forceOverwriteItemIDs = useMemo(() => {
const sessionsByID = new Map<string, ObjectSyncSession>();
const spacesByID = new Map<string, ObjectSyncSpace>();
for (const item of sessions) sessionsByID.set(item.id, item);
for (const item of spaces) spacesByID.set(item.id, item);
return new Set(
conflicts
.filter((item) => {
const session = sessionsByID.get(item.sessionId);
const space = session ? spacesByID.get(session.syncSpaceId) : undefined;
return (
space?.capability.state === "update_enabled" &&
space.capability.exclusivePrefixConfirmed &&
space.policy?.allowForceOverwrite
);
})
.map((item) => item.id),
);
}, [conflicts, sessions, spaces]);
if (loading) {
return (
<div className="flex min-h-[520px] items-center justify-center text-sm text-slate-400">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
正在加载 drosync…
</div>
);
}
return (
<div className="mx-auto max-w-[1520px] space-y-5 pb-10">
<header className="flex flex-col gap-5 border-b border-[#292b30] pb-6 lg:flex-row lg:items-end lg:justify-between">
<div>
<div className="flex items-center gap-3">
<CloudUpload className="h-7 w-7 text-sky-400" />
<h1 className="text-2xl font-semibold tracking-tight text-white">drosync</h1>
</div>
<p className="mt-2 max-w-3xl text-sm leading-6 text-slate-400">
本地文件到 BOS 的单向增量上传。条件创建未验证时禁止提交,条件更新仅在能力探测与共享 prefix
独占确认同时通过后开放。
</p>
</div>
<button
type="button"
onClick={() => void load(true)}
disabled={refreshing}
className="inline-flex h-9 items-center justify-center gap-2 rounded-md border border-[#34363c] bg-[#1a1b1f] px-3 text-xs font-medium text-slate-200 transition hover:border-sky-500/50 hover:text-white disabled:opacity-50"
>
<RefreshCw className={cn("h-3.5 w-3.5", refreshing && "animate-spin")} />
刷新状态
</button>
</header>
{error ? (
<div className="flex items-start gap-3 rounded-lg border border-rose-500/25 bg-rose-500/8 px-4 py-3 text-sm text-rose-200">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<div>
<div className="font-medium">控制面暂不可用</div>
<div className="mt-1 text-xs leading-5 text-rose-300/80">{error}</div>
</div>
</div>
) : null}
{actionMessage ? (
<div className="flex items-center gap-2 rounded-lg border border-emerald-500/25 bg-emerald-500/8 px-4 py-3 text-sm text-emerald-200">
<CheckCircle2 className="h-4 w-4" />
{actionMessage}
</div>
) : null}
<section className="grid grid-cols-2 gap-y-5 border-y border-[#292b30] py-5 md:grid-cols-5">
<Metric icon={Boxes} label="同步空间" value={spaces.length} detail={`${readySpaces.length} 个已开放`} />
<Metric
icon={Activity}
label="活跃 Session"
value={activeSessions.length}
detail={`${sessions.length} 个总记录`}
/>
<Metric icon={FileClock} label="保留冲突" value={conflicts.length} detail="原对象保持不变" />
<Metric
icon={Laptop}
label="活跃设备"
value={devices.filter((item) => item.status === "active").length}
detail={`${pendingApprovals.length} 个待审批`}
/>
<Metric
icon={PackageCheck}
label="已发布 Release"
value={releases.filter((item) => item.status === "published").length}
detail="NDJSON + SHA-256"
/>
</section>
<nav className="flex gap-1 overflow-x-auto border-b border-[#292b30]" aria-label="drosync sections">
{views.map((view) => (
<button
key={view.key}
type="button"
onClick={() => setActiveView(view.key)}
className={cn(
"relative shrink-0 px-4 py-3 text-xs font-medium transition",
activeView === view.key ? "text-white" : "text-slate-500 hover:text-slate-200",
)}
>
{view.label}
{activeView === view.key ? <span className="absolute inset-x-3 bottom-0 h-0.5 bg-sky-400" /> : null}
</button>
))}
</nav>
{activeView === "overview" ? (
<div className="grid gap-5 lg:grid-cols-[1.25fr_0.75fr]">
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="能力门禁" detail="平台只允许经过真实 BOS 探测的动作;UI 不提供绕过路径。" />
<div className="divide-y divide-[#292b30]">
{spaces.map((space) => (
<button
key={space.id}
type="button"
onClick={() => {
setActiveView("spaces");
}}
className="flex w-full items-center gap-4 px-6 py-4 text-left transition hover:bg-white/[0.025]"
>
<span
className={cn(
"h-2.5 w-2.5 rounded-full",
space.enabled
? "bg-emerald-400"
: space.capability.state === "drifted"
? "bg-amber-400"
: "bg-slate-600",
)}
/>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-slate-100">{space.name}</div>
<div className="mt-1 truncate font-mono text-[11px] text-slate-500">
bos://{space.bucket}/{space.rootPrefix}
</div>
</div>
<CapabilityBadge state={space.capability.state} />
<ChevronRight className="h-4 w-4 text-slate-600" />
</button>
))}
{spaces.length === 0 ? (
<EmptyState title="尚未创建同步空间" detail="管理员需先绑定 BOS 连接并执行专用临时 key 能力探测。" />
) : null}
</div>
</section>
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="安全不变量" detail="服务端强制执行,不依赖客户端声明。" />
<div className="space-y-4 px-6 py-5 text-xs leading-5 text-slate-400">
{[
["条件提交", "未通过 If-None-Match 探测的 space 禁止上传。"],
["Fencing token", "同一逻辑 key 的旧 lease 永远不能重新提交。"],
["Keep-both", "412 冲突写入匿名冲突 key,原对象保持不变。"],
["不可变 Release", "业务对象不改名;发布记录指向带 SHA-256 的 NDJSON。"],
].map(([title, detail]) => (
<div
key={title}
className="grid grid-cols-[100px_1fr] gap-4 border-b border-[#292b30] pb-4 last:border-0 last:pb-0"
>
<span className="font-medium text-slate-200">{title}</span>
<span>{detail}</span>
</div>
))}
</div>
</section>
</div>
) : null}
{activeView === "spaces" && isAdmin ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle
title="同步空间"
detail="每个 space 固定 BOS 连接、bucket、root prefix、配额和条件写能力。"
action={
<button
type="button"
onClick={() => setIsSpaceFormOpen((value) => !value)}
className="inline-flex h-9 items-center gap-2 rounded-md bg-sky-500 px-3 text-xs font-semibold text-slate-950 hover:bg-sky-400"
>
<Plus className="h-3.5 w-3.5" />
新建空间
</button>
}
/>
{isSpaceFormOpen ? (
<form
className="grid gap-3 border-b border-[#292b30] bg-[#101114] p-5 md:grid-cols-2 xl:grid-cols-5"
onSubmit={(event) => {
event.preventDefault();
void runAction(
"create-space",
() => objectSyncApi.createSpace(spaceDraft),
"同步空间已创建,默认保持禁用,等待 BOS 能力探测。",
).then(() => {
setIsSpaceFormOpen(false);
setSpaceDraft((previous) => ({ ...previous, name: "", description: "", rootPrefix: "" }));
});
}}
>
<input
required
value={spaceDraft.name}
onChange={(event) => setSpaceDraft((previous) => ({ ...previous, name: event.target.value }))}
placeholder="空间名称"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 text-xs text-white outline-none focus:border-sky-500"
/>
<select
required
value={spaceDraft.connectionId}
onChange={(event) => {
const connection = connections.find((item) => item.id === event.target.value);
setSpaceDraft((previous) => ({
...previous,
connectionId: event.target.value,
bucket: connection?.bucket || previous.bucket,
}));
}}
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 text-xs text-white outline-none focus:border-sky-500"
>
<option value="">选择 BOS 连接</option>
{connections.map((connection) => (
<option key={connection.id} value={connection.id}>
{connection.name}
</option>
))}
</select>
<input
required
value={spaceDraft.bucket}
onChange={(event) => setSpaceDraft((previous) => ({ ...previous, bucket: event.target.value }))}
placeholder="Bucket"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 font-mono text-xs text-white outline-none focus:border-sky-500"
/>
<input
value={spaceDraft.rootPrefix}
onChange={(event) => setSpaceDraft((previous) => ({ ...previous, rootPrefix: event.target.value }))}
placeholder="Root prefix"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 font-mono text-xs text-white outline-none focus:border-sky-500"
/>
<button
disabled={busyKey === "create-space"}
className="h-9 rounded-md border border-sky-500/40 bg-sky-500/10 text-xs font-semibold text-sky-200 hover:bg-sky-500/15 disabled:opacity-50"
>
{busyKey === "create-space" ? "创建中…" : "创建并保持禁用"}
</button>
</form>
) : null}
<div className="overflow-x-auto">
<table className="w-full min-w-[980px] text-left text-xs">
<thead className="bg-[#101114] text-slate-500">
<tr>
<th className="px-5 py-3 font-medium">空间</th>
<th className="px-5 py-3 font-medium">BOS 目标</th>
<th className="px-5 py-3 font-medium">能力</th>
<th className="px-5 py-3 font-medium">独占确认</th>
<th className="px-5 py-3 font-medium">强制覆盖</th>
<th className="px-5 py-3 font-medium">入口</th>
<th className="px-5 py-3 text-right font-medium">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-[#292b30]">
{spaces.map((space) => (
<tr key={space.id} className="text-slate-300">
<td className="px-5 py-4">
<div className="font-medium text-white">{space.name}</div>
<div className="mt-1 text-[11px] text-slate-500">{space.id}</div>
</td>
<td className="px-5 py-4 font-mono text-[11px]">
bos://{space.bucket}/{space.rootPrefix}
</td>
<td className="px-5 py-4">
<button
type="button"
disabled={space.capability.state !== "update_enabled"}
onClick={() =>
void runAction(
`force-policy-${space.id}`,
() =>
objectSyncApi.updateSpace(space.id, {
allowForceOverwrite: !space.policy?.allowForceOverwrite,
}),
space.policy?.allowForceOverwrite
? "管理员强制覆盖策略已关闭。"
: "管理员强制覆盖策略已开启;每次覆盖仍需单独确认。",
)
}
className={cn(
"rounded-md border px-2 py-1 text-[11px] disabled:cursor-not-allowed disabled:opacity-35",
space.policy?.allowForceOverwrite
? "border-rose-500/30 text-rose-300"
: "border-slate-600 text-slate-400",
)}
>
{space.policy?.allowForceOverwrite ? "已允许" : "默认禁止"}
</button>
</td>
<td className="px-5 py-4">
<CapabilityBadge state={space.capability.state} />
{space.capability.probeError ? (
<div className="mt-2 max-w-xs text-[11px] text-rose-300">{space.capability.probeError}</div>
) : null}
</td>
<td className="px-5 py-4">
<button
type="button"
onClick={() =>
void runAction(
`exclusive-${space.id}`,
() =>
objectSyncApi.updateSpace(space.id, {
exclusivePrefixConfirmed: !space.capability.exclusivePrefixConfirmed,
}),
"共享 prefix 独占确认已更新。",
)
}
className={cn(
"rounded-md border px-2 py-1 text-[11px]",
space.capability.exclusivePrefixConfirmed
? "border-emerald-500/30 text-emerald-300"
: "border-slate-600 text-slate-400",
)}
>
{space.capability.exclusivePrefixConfirmed ? "已确认无外部直写" : "尚未确认"}
</button>
</td>
<td className="px-5 py-4">
<span className={space.enabled ? "text-emerald-300" : "text-slate-500"}>
{space.enabled ? "已开放" : "已关闭"}
</span>
</td>
<td className="px-5 py-4 text-right">
<div className="flex justify-end gap-2">
<button
type="button"
disabled={busyKey === `probe-${space.id}`}
onClick={() =>
void runAction(
`probe-${space.id}`,
() => objectSyncApi.probeSpace(space.id),
"BOS 条件写能力探测完成。",
)
}
className="rounded-md border border-[#34363c] px-2.5 py-1.5 text-[11px] text-slate-300 hover:border-sky-500/50 hover:text-white"
>
探测
</button>
<button
type="button"
disabled={busyKey === `reconcile-${space.id}`}
onClick={() =>
void runAction(
`reconcile-${space.id}`,
() => objectSyncApi.reconcileSpace(space.id),
"远端对象对账任务已进入队列;对账期间入口保持关闭。",
)
}
className="rounded-md border border-[#34363c] px-2.5 py-1.5 text-[11px] text-slate-300 hover:border-amber-500/50 hover:text-white disabled:opacity-35"
>
对账
</button>
<button
type="button"
disabled={
!["create_only", "update_enabled"].includes(space.capability.state) ||
busyKey === `toggle-${space.id}`
}
onClick={() =>
void runAction(
`toggle-${space.id}`,
() => objectSyncApi.updateSpace(space.id, { enabled: !space.enabled }),
space.enabled ? "同步入口已关闭。" : "同步入口已开放。",
)
}
className="rounded-md border border-[#34363c] px-2.5 py-1.5 text-[11px] text-slate-300 hover:border-sky-500/50 hover:text-white disabled:cursor-not-allowed disabled:opacity-35"
>
{space.enabled ? "关闭" : "开放"}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{spaces.length === 0 ? (
<EmptyState title="没有同步空间" detail="先创建空间,再执行真实 BOS capability probe。" />
) : null}
</div>
</section>
) : null}
{activeView === "devices" && isAdmin ? (
<div className="grid gap-5 xl:grid-cols-2">
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="设备审批" detail="浏览器短码只用于配对;管理员批准明确的 space 与 prefix scope。" />
<div className="flex flex-col gap-2 border-b border-[#292b30] px-5 py-4 sm:flex-row">
<input
value={pairingCode}
onChange={(event) => setPairingCode(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") void findPairingRequest();
}}
placeholder="输入客户端显示的配对短码"
aria-label="配对短码"
className="h-9 min-w-0 flex-1 rounded-md border border-[#34363c] bg-[#111214] px-3 font-mono text-xs uppercase text-slate-100 outline-none placeholder:normal-case placeholder:text-slate-600 focus:border-sky-500/60"
/>
<button
type="button"
disabled={!pairingCode.trim() || busyKey === "pairing-lookup"}
onClick={() => void findPairingRequest()}
className="inline-flex h-9 items-center justify-center gap-2 rounded-md border border-sky-500/30 px-3 text-xs font-medium text-sky-300 disabled:cursor-not-allowed disabled:opacity-35"
>
{busyKey === "pairing-lookup" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Fingerprint className="h-3.5 w-3.5" />
)}
查询请求
</button>
</div>
<div className="divide-y divide-[#292b30]">
{authorizations.map((item) => (
<div key={item.id} className="flex items-center gap-4 px-5 py-4">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-sky-500/10 text-sky-300">
<Laptop className="h-4 w-4" />
</div>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-white">{item.deviceName}</div>
<div className="mt-1 text-[11px] text-slate-500">
{item.platform}/{item.architecture} · code {item.userCode}
</div>
</div>
<span className={cn("text-[11px] font-medium", statusTone(item.status))}>{item.status}</span>
{item.status === "pending" ? (
<div className="flex gap-1.5">
<button
type="button"
disabled={spaces.length === 0}
onClick={() =>
void runAction(
`approve-${item.id}`,
() =>
objectSyncApi.decideAuthorization(item.id, "approve", [
{
syncSpaceId: spaces[0].id,
allowedRelativePrefixes: [""],
actions: ["plan", "create", "keep_both"],
},
]),
`设备已批准到 ${spaces[0]?.name || "同步空间"}。`,
)
}
className="rounded-md border border-emerald-500/30 px-2 py-1 text-[11px] text-emerald-300 disabled:opacity-30"
>
批准
</button>
<button
type="button"
onClick={() =>
void runAction(
`deny-${item.id}`,
() => objectSyncApi.decideAuthorization(item.id, "deny", []),
"设备配对请求已拒绝。",
)
}
className="rounded-md border border-rose-500/30 px-2 py-1 text-[11px] text-rose-300"
>
拒绝
</button>
</div>
) : null}
</div>
))}
{authorizations.length === 0 ? (
<EmptyState
title="没有已归属的配对请求"
detail="让客户端执行 drosync auth,然后在上方输入其短码查询。"
/>
) : null}
</div>
</section>
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="设备凭据" detail="长期有效直到管理员撤销;控制面仅展示掩码,不回显 token。" />
<div className="divide-y divide-[#292b30]">
{credentials.map((item) => (
<div key={item.id} className="flex items-center gap-4 px-5 py-4">
<KeyRound className="h-4 w-4 text-slate-500" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-white">{item.name}</div>
<div className="mt-1 font-mono text-[11px] text-slate-500">{item.tokenPreview}</div>
</div>
<span className={item.enabled ? "text-[11px] text-emerald-300" : "text-[11px] text-rose-300"}>
{item.enabled ? "有效" : "已撤销"}
</span>
<button
type="button"
onClick={() =>
void runAction(
`rotate-${item.id}`,
() => objectSyncApi.mutateCredential(item.id, "rotate"),
"凭据已轮换;新 token 仅在本次响应返回。",
)
}
title="轮换"
className="p-1.5 text-slate-500 hover:text-sky-300"
>
<RotateCw className="h-3.5 w-3.5" />
</button>
<button
type="button"
disabled={!item.enabled}
onClick={() =>
void runAction(
`revoke-${item.id}`,
() => objectSyncApi.mutateCredential(item.id, "revoke"),
"凭据已撤销;60 秒内不再接受新控制面请求。",
)
}
title="撤销"
className="p-1.5 text-slate-500 hover:text-rose-300 disabled:opacity-30"
>
<XCircle className="h-3.5 w-3.5" />
</button>
</div>
))}
{credentials.length === 0 ? (
<EmptyState title="没有设备凭据" detail="批准的设备完成配对轮询后才会签发凭据。" />
) : null}
</div>
</section>
</div>
) : null}
{activeView === "sessions" && !isAuditor ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="Session" detail="百万级 item 保存在独立 collection;列表按 opaque cursor 分页。" />
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left text-xs">
<thead className="bg-[#101114] text-slate-500">
<tr>
<th className="px-5 py-3 font-medium">Session</th>
<th className="px-5 py-3 font-medium">状态</th>
<th className="px-5 py-3 font-medium">文件</th>
<th className="px-5 py-3 font-medium">已提交 / 冲突 / 失败</th>
<th className="px-5 py-3 font-medium">数据量</th>
<th className="px-5 py-3 font-medium">更新时间</th>
{isAdmin ? <th className="px-5 py-3 text-right font-medium">操作</th> : null}
</tr>
</thead>
<tbody className="divide-y divide-[#292b30]">
{sessions.map((session) => (
<tr key={session.id}>
<td className="px-5 py-4">
<div className="font-mono text-[11px] text-slate-200">{session.id}</div>
<div className="mt-1 text-[11px] text-slate-500">{session.mappingId || "default mapping"}</div>
</td>
<td className={cn("px-5 py-4 font-medium", statusTone(session.status))}>{session.status}</td>
<td className="px-5 py-4 text-slate-300">{session.counts.manifest.toLocaleString()}</td>
<td className="px-5 py-4 text-slate-300">
{session.counts.committed} / <span className="text-amber-300">{session.counts.keptBoth}</span> /{" "}
<span className="text-rose-300">{session.counts.failed}</span>
</td>
<td className="px-5 py-4 text-slate-400">{formatBytes(session.totalBytes)}</td>
<td className="px-5 py-4 text-slate-500">{formatCompactDateTime(session.updatedAt, timeZone)}</td>
{isAdmin ? (
<td className="px-5 py-4 text-right">
<button
type="button"
disabled={!activeSessions.some((item) => item.id === session.id)}
onClick={() =>
void runAction(
`abort-${session.id}`,
() => objectSyncApi.abortSession(session.id),
"Session 已停止;已提交对象不会回滚。",
)
}
className="text-[11px] text-rose-300 hover:text-rose-200 disabled:opacity-30"
>
停止
</button>
</td>
) : null}
</tr>
))}
</tbody>
</table>
{sessions.length === 0 ? (
<EmptyState title="没有同步 Session" detail="设备上传 manifest 后会在此显示规划与提交进度。" />
) : null}
</div>
</section>
) : null}
{activeView === "conflicts" && !isAuditor ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="Keep-both 冲突" detail="冲突 key 不暴露用户身份;冲突对象不会自动删除。" />
<div className="divide-y divide-[#292b30]">
{conflicts.map((item) => (
<div key={item.id} className="grid gap-3 px-5 py-4 lg:grid-cols-[1fr_1fr_230px]">
<div className="min-w-0">
<div className="truncate text-xs font-medium text-slate-200">
{item.logicalTargetKey || item.relativePath}
</div>
<div className="mt-1 text-[11px] text-slate-500">原逻辑目标</div>
</div>
<div className="min-w-0">
<div className="truncate font-mono text-[11px] text-amber-300">{item.targetKey}</div>
<div className="mt-1 text-[11px] text-slate-500">保留冲突对象</div>
</div>
<div className="flex items-center justify-end gap-3 text-right text-[11px] text-slate-500">
<span>{formatCompactDateTime(item.updatedAt, timeZone)}</span>
{isAdmin ? (
<button
type="button"
disabled={!forceOverwriteItemIDs.has(item.id) || busyKey === `force-overwrite-${item.id}`}
onClick={() => {
if (
!window.confirm(
`确认以保留冲突对象覆盖逻辑目标?\n\n目标:${item.logicalTargetKey}\n来源:${item.targetKey}\n\n操作仍使用最新 ETag 条件写,冲突对象不会删除。`,
)
) {
return;
}
void runAction(
`force-overwrite-${item.id}`,
() => objectSyncApi.forceOverwriteConflict(item.id),
"条件强制覆盖已进入队列;保留冲突对象不会删除。",
);
}}
className="rounded-md border border-rose-500/30 px-2 py-1 text-rose-300 hover:border-rose-400 disabled:cursor-not-allowed disabled:opacity-30"
>
条件覆盖
</button>
) : null}
</div>
</div>
))}
{conflicts.length === 0 ? (
<EmptyState title="没有保留冲突" detail="条件提交 412 时,服务端会自动生成 keep-both key 并在此留痕。" />
) : null}
</div>
</section>
) : null}
{activeView === "releases" && (isAdmin || isPipeline) ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle
title="不可变 Release"
detail="Mongo 保存索引和摘要;带 SHA-256 的 NDJSON manifest 写入内部 release prefix。"
/>
<form
className="grid gap-3 border-b border-[#292b30] bg-[#101114] p-5 md:grid-cols-[1fr_1.5fr_2fr_auto]"
onSubmit={(event) => {
event.preventDefault();
void runAction(
"create-release",
() =>
objectSyncApi.createRelease({
name: releaseDraft.name,
description: releaseDraft.description,
sessionIds: releaseDraft.sessionIds
.split(",")
.map((item) => item.trim())
.filter(Boolean),
}),
"Release 已进入异步发布队列。",
).then(() => setReleaseDraft({ name: "", description: "", sessionIds: "" }));
}}
>
<input
required
value={releaseDraft.name}
onChange={(event) => setReleaseDraft((previous) => ({ ...previous, name: event.target.value }))}
placeholder="Release 名称"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 text-xs text-white outline-none focus:border-sky-500"
/>
<input
value={releaseDraft.description}
onChange={(event) => setReleaseDraft((previous) => ({ ...previous, description: event.target.value }))}
placeholder="说明"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 text-xs text-white outline-none focus:border-sky-500"
/>
<input
required
value={releaseDraft.sessionIds}
onChange={(event) => setReleaseDraft((previous) => ({ ...previous, sessionIds: event.target.value }))}
placeholder="最终态 Session ID,逗号分隔"
className="h-9 rounded-md border border-[#34363c] bg-[#0b0c0e] px-3 font-mono text-xs text-white outline-none focus:border-sky-500"
/>
<button className="h-9 rounded-md bg-sky-500 px-4 text-xs font-semibold text-slate-950 hover:bg-sky-400">
创建
</button>
</form>
<div className="divide-y divide-[#292b30]">
{releases.map((item) => (
<div key={item.id} className="grid gap-3 px-5 py-4 md:grid-cols-[1fr_150px_150px_1.2fr] md:items-center">
<div>
<div className="text-sm font-medium text-white">{item.name}</div>
<div className="mt-1 text-[11px] text-slate-500">{item.id}</div>
</div>
<div className={cn("text-xs font-medium", statusTone(item.status))}>{item.status}</div>
<div className="text-xs text-slate-400">
{item.objectCount || 0} objects · {formatBytes(item.totalBytes)}
</div>
<div className="truncate font-mono text-[11px] text-slate-500">{item.manifestSha256 || "等待发布"}</div>
</div>
))}
{releases.length === 0 ? (
<EmptyState title="没有 Release" detail="仅可从 completed、partial 或 conflicted Session 创建。" />
) : null}
</div>
</section>
) : null}
{activeView === "audit" && (isAdmin || isAuditor) ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle
title="审计哈希链"
detail="按组织串联 previousHash → eventHash;记录保留一年并支持 NDJSON/CSV 导出。"
action={
<div className="flex gap-2">
{(["ndjson", "csv"] as const).map((format) => (
<button
key={format}
type="button"
onClick={() => void objectSyncApi.downloadAudit(format)}
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-[#34363c] px-2.5 text-[11px] text-slate-300 hover:text-white"
>
<Download className="h-3 w-3" />
{format.toUpperCase()}
</button>
))}
</div>
}
/>
<div className="overflow-x-auto">
<table className="w-full min-w-[980px] text-left text-xs">
<thead className="bg-[#101114] text-slate-500">
<tr>
<th className="px-5 py-3 font-medium">时间</th>
<th className="px-5 py-3 font-medium">Actor</th>
<th className="px-5 py-3 font-medium">动作</th>
<th className="px-5 py-3 font-medium">结果</th>
<th className="px-5 py-3 font-medium">Event hash</th>
<th className="px-5 py-3 font-medium">链</th>
</tr>
</thead>
<tbody className="divide-y divide-[#292b30]">
{audit.map((item) => (
<tr key={item.id}>
<td className="px-5 py-4 text-slate-500">{formatCompactDateTime(item.occurredAt, timeZone)}</td>
<td className="px-5 py-4 text-slate-300">
{item.actorType}:{item.actorId}
</td>
<td className="px-5 py-4 text-slate-200">{item.action}</td>
<td className={cn("px-5 py-4", statusTone(item.result))}>{item.result}</td>
<td className="max-w-[260px] truncate px-5 py-4 font-mono text-[11px] text-slate-500">
{item.eventHash}
</td>
<td className="px-5 py-4">
<Fingerprint className="h-4 w-4 text-emerald-400" />
</td>
</tr>
))}
</tbody>
</table>
{audit.length === 0 ? (
<EmptyState
title="没有审计事件"
detail="space、设备、凭据、session、提交和 release 操作都会写入哈希链。"
/>
) : null}
</div>
</section>
) : null}
{activeView === "updates" && isAdmin ? (
<section className="overflow-hidden rounded-xl border border-[#292b30] bg-[#151619]">
<SectionTitle title="客户端更新策略" detail="Ed25519 manifest + SHA-256 + OS 原生签名;上传期间禁止升级。" />
<div className="grid gap-5 border-b border-[#292b30] px-6 py-5 md:grid-cols-3">
{[
["Canary", "5%", "观察 24 小时"],
["Pilot", "20%", "观察 24 小时"],
["Stable", "100%", "全量发布"],
].map(([channel, percent, detail]) => (
<div key={channel} className="border-l border-[#303238] pl-4 first:border-l-0 first:pl-0">
<div className="text-xs text-slate-500">{channel}</div>
<div className="mt-1 text-xl font-semibold text-white">{percent}</div>
<div className="mt-1 text-[11px] text-slate-500">{detail}</div>
</div>
))}
</div>
<div className="divide-y divide-[#292b30]">
{clientReleases.map((item) => (
<div
key={item.id}
className="grid gap-3 px-5 py-4 md:grid-cols-[1fr_100px_100px_minmax(280px,1fr)] md:items-center"
>
<div>
<div className="text-sm font-medium text-white">drosync {item.version}</div>
<div className="mt-1 text-[11px] text-slate-500">{Object.keys(item.artifacts).join(" · ")}</div>
</div>
<div className="text-xs text-slate-300">{item.channel}</div>
<div className="text-xs text-slate-300">{item.paused ? "已暂停" : `${item.rolloutPercent}%`}</div>
<div className="flex flex-wrap items-center gap-2">
{(
[
["canary", 5, "5%"],
["pilot", 20, "20%"],
["stable", 100, "100%"],
] as const
).map(([channel, rolloutPercent, label]) => (
<button
key={channel}
type="button"
disabled={busyKey === `rollout-${item.id}` || (!item.paused && item.channel === channel)}
onClick={() =>
void runAction(
`rollout-${item.id}`,
() => objectSyncApi.saveClientRelease({ ...item, channel, rolloutPercent, paused: false }),
`drosync ${item.version} 已切换到 ${label} 发布阶段`,
)
}
className="rounded border border-[#34363c] px-2 py-1 text-[11px] text-slate-300 transition hover:border-sky-500/50 hover:text-white disabled:opacity-40"
>
{label}
</button>
))}
<button
type="button"
disabled={busyKey === `rollout-${item.id}`}
onClick={() =>
void runAction(
`rollout-${item.id}`,
() => objectSyncApi.saveClientRelease({ ...item, paused: !item.paused }),
`drosync ${item.version} 更新策略已${item.paused ? "恢复" : "暂停"}`,
)
}
className="rounded border border-amber-500/30 px-2 py-1 text-[11px] text-amber-200 transition hover:border-amber-400 disabled:opacity-40"
>
{item.paused ? "恢复" : "暂停"}
</button>
<span className="inline-flex items-center gap-1 text-[11px] text-emerald-300">
<ShieldCheck className="h-3.5 w-3.5" />
签名 manifest
</span>
</div>
</div>
))}
{clientReleases.length === 0 ? (
<EmptyState title="没有签名客户端版本" detail="签名凭据由 CI/密钥库注入,私钥不得进入仓库。" />
) : null}
</div>
</section>
) : null}
</div>
);
}