Skip to content

World's first open-source enterprise world model.

Entities can be corrected without rebuilding the whole graph (#40)

WaylandYang03048dd16714
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index 1cd302e6..1950e958 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -102,6 +102,73 @@ pub async fn entity_detail(
Ok(Json(json!({ "entity": entity, "facts": facts })))
}
+#[derive(Deserialize)]
+pub struct EntityPatch {
+ #[serde(default)]
+ pub type_id: Option<Uuid>,
+ #[serde(default)]
+ pub canonical_name: Option<String>,
+}
+
+/// 人工修正实体的类型或名字。抽取给的是初判,此前判错只能整库重抽。
+///
+/// 改名撞上同名实体不拦(两个张伟是"宁分勿合"的正当产物),改完把同名的报回去,
+/// 由界面提示是否合并——判定它们是否真是同一个,是人的事。
+pub async fn update_entity(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, entity_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<EntityPatch>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ if req.type_id.is_none() && req.canonical_name.is_none() {
+ return Err(AppError::Validation("Nothing to update".into()).into());
+ }
+ let (before, after) = utopia_store::graph::update_entity(
+ &state.pool,
+ kb_id,
+ entity_id,
+ req.type_id,
+ req.canonical_name.as_deref(),
+ )
+ .await?;
+
+ // 台账快照自包含:类型以后被删掉,这条记录仍然读得懂。
+ // P4 要按 from/to 聚合"一个月里 37 个实体从 Product 挪到 Concept",所以分开记两个动作。
+ if before.type_key != after.type_key {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "entity.retyped",
+ "entity",
+ Some(entity_id),
+ json!({
+ "name": after.name,
+ "from": { "key": before.type_key, "label": before.type_label },
+ "to": { "key": after.type_key, "label": after.type_label },
+ }),
+ )
+ .await;
+ }
+ if before.name != after.name {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "entity.renamed",
+ "entity",
+ Some(entity_id),
+ json!({ "from": before.name, "to": after.name, "type": after.type_label }),
+ )
+ .await;
+ }
+
+ let peers = utopia_store::graph::same_name_peers(&state.pool, kb_id, entity_id).await?;
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "entity": after, "same_name": peers })))
+}
+
pub async fn fact_evidence(
State(state): State<AppState>,
AuthUser(user): AuthUser,
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index d946c5da..989744db 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -162,7 +162,7 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.route("/kbs/{id}/entities", get(graph_routes::search_entities))
.route(
"/kbs/{id}/entities/{entity_id}",
- get(graph_routes::entity_detail),
+ get(graph_routes::entity_detail).patch(graph_routes::update_entity),
)
.route(
"/kbs/{id}/entities/{entity_id}/history",
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 43001c12..cafb8ddf 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -503,6 +503,107 @@ pub async fn entity_detail(
Ok((node, facts))
}
+/// 人工修正实体的类型或名字。返回 (改前快照, 改后状态)——调用方据此记审计台账。
+///
+/// 类型判错、名字抽歪,此前只能整库重抽这把大锤。抽取给的是初判,不是定论。
+///
+/// 同名不拦:同类同名的两个实体是"宁分勿合"的正当产物(两个张伟),
+/// 拦下来就录不进第二个。碰撞由调用方查出后提示合并,见 `same_name_peers`。
+pub async fn update_entity(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+ type_id: Option<Uuid>,
+ canonical_name: Option<&str>,
+) -> AppResult<(GraphNode, GraphNode)> {
+ let before: GraphNode = sqlx::query_as(&format!(
+ "{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2 AND e.merged_into IS NULL"
+ ))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
+
+ let new_name = match canonical_name {
+ Some(raw) => {
+ let n = raw.trim();
+ if n.is_empty() {
+ return Err(AppError::Validation("Name cannot be empty".into()));
+ }
+ // 与抽取侧同一上限:越过这条线的多半是整句被当成了名字
+ if n.chars().count() > 100 {
+ return Err(AppError::Validation("Name is too long (max 100)".into()));
+ }
+ Some(n)
+ }
+ None => None,
+ };
+
+ if let Some(t) = type_id {
+ let exists: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM entity_types WHERE id = $1 AND kb_id = $2")
+ .bind(t)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?;
+ if exists.is_none() {
+ return Err(AppError::Validation(
+ "No such entity type in this KB".into(),
+ ));
+ }
+ }
+
+ sqlx::query(
+ "UPDATE entities
+ SET type_id = COALESCE($3, type_id),
+ canonical_name = COALESCE($4, canonical_name),
+ updated_at = now()
+ WHERE id = $1 AND kb_id = $2 AND merged_into IS NULL",
+ )
+ .bind(entity_id)
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(new_name)
+ .execute(pool)
+ .await?;
+
+ // 消歧后缀依赖名字分组与类型标签(类型标签是它的兜底值),两者都刚被改过。
+ // 改名要刷两组:旧名那组可能掉到 1 个(后缀该清掉),新名那组可能涨到 2 个。
+ if let Some(n) = new_name.filter(|n| !n.eq_ignore_ascii_case(&before.name)) {
+ crate::resolution::refresh_disambiguators(pool, kb_id, &before.name).await?;
+ crate::resolution::refresh_disambiguators(pool, kb_id, n).await?;
+ } else if type_id.is_some() {
+ crate::resolution::refresh_disambiguators(pool, kb_id, &before.name).await?;
+ }
+
+ let after: GraphNode = sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2"))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_one(pool)
+ .await?;
+ Ok((before, after))
+}
+
+/// 与给定实体同名(不区分大小写)的其他存活实体——用于改名后提示"是否合并"。
+/// 只报告,不阻断:判定它们是否真是同一个,是人的事。
+pub async fn same_name_peers(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+) -> AppResult<Vec<GraphNode>> {
+ sqlx::query_as(&format!(
+ "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2
+ AND lower(e.canonical_name) = (SELECT lower(canonical_name) FROM entities WHERE id = $2)
+ ORDER BY degree DESC LIMIT 10"
+ ))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_all(pool)
+ .await
+ .map_err(Into::into)
+}
+
/// 低置信 live 事实(审核页)。
pub async fn low_confidence_facts(
pool: &PgPool,
diff --git a/web/src/api.ts b/web/src/api.ts
index 4c5c66fd..8dafc0fb 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -569,6 +569,17 @@ export const api = {
`/api/v1/kbs/${kbId}/entities/${entityId}`,
),
/** 认知变更历史(记录时间轴):服务端分页 */
+ /** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
+ updateEntity: (
+ kbId: string,
+ entityId: string,
+ body: { type_id?: string; canonical_name?: string },
+ ) =>
+ request<{ entity: GraphNode; same_name: GraphNode[] }>(
+ `/api/v1/kbs/${kbId}/entities/${entityId}`,
+ { method: "PATCH", body: JSON.stringify(body) },
+ ),
+
entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
request<{ events: EntityHistoryEvent[]; total: number }>(
`/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
index 014d7025..54498f45 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n.ts
@@ -413,6 +413,20 @@ export const S = {
staleFactHint:
"All evidence for this fact comes from earlier versions of its source documents — " +
"the current content no longer states it. It may still be true; review it under Review.",
+ /* 实体修正:抽取给的是初判,人可以推翻它 */
+ edit: "Edit",
+ editName: "Name",
+ editType: "Type",
+ editSave: "Save",
+ editCancel: "Cancel",
+ editSaved: "Entity updated",
+ editEmptyName: "Name cannot be empty",
+ /* 同名不是错误——两个张伟可以并存。只提示,不阻断 */
+ sameNameNote: (n: number) =>
+ n === 1
+ ? "One other entity shares this name."
+ : `${n} other entities share this name.`,
+ sameNameHint: "If they are the same thing, merge them under Review.",
viewRelations: "Relations",
viewTimeline: "Timeline",
/* 第三视图:记录时间轴——不是"事情何时发生",而是"我们何时这么认为" */
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 5fd88783..dbf8a949 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, useSearch } from "@tanstack/react-router";
import Graphology from "graphology";
import { circular, circlepack } from "graphology-layout";
@@ -18,6 +18,7 @@ import {
Maximize2,
Orbit,
Pause,
+ Pencil,
Play,
X,
ZoomIn,
@@ -26,6 +27,7 @@ import {
import { api, type EntityFact, type Evidence, type GraphEdge, type GraphNode } from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
+import { toast } from "../toast";
/* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:
Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、
@@ -1184,6 +1186,58 @@ function EntityPanel({
const e: GraphNode | undefined = detail.data?.entity;
+ // 实体修正:抽取给的是初判,判错此前只能整库重抽
+ const qc = useQueryClient();
+ const [editing, setEditing] = useState(false);
+ const [draftName, setDraftName] = useState("");
+ const [draftType, setDraftType] = useState("");
+ const [sameName, setSameName] = useState<GraphNode[]>([]);
+ // 类型下拉要的是全量本体,不是当前视图里出现过的那几个
+ const ontology = useQuery({
+ queryKey: ["ontology", kbId],
+ queryFn: () => api.ontology(kbId),
+ enabled: editing,
+ });
+ const types = ontology.data?.entity_types ?? [];
+
+ const openEdit = () => {
+ if (!e) return;
+ setDraftName(e.name);
+ setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
+ setSameName([]);
+ setEditing(true);
+ };
+ // 本体是异步来的:它到齐时把类型下拉对到当前类型上
+ useEffect(() => {
+ if (editing && !draftType && e)
+ setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
+ }, [editing, draftType, e, types]);
+
+ const save = useMutation({
+ mutationFn: () => {
+ const body: { type_id?: string; canonical_name?: string } = {};
+ if (draftName.trim() && draftName.trim() !== e?.name) body.canonical_name = draftName.trim();
+ const curId = types.find((t) => t.key === e?.type_key)?.id;
+ if (draftType && draftType !== curId) body.type_id = draftType;
+ return api.updateEntity(kbId, entityId, body);
+ },
+ onSuccess: (r) => {
+ setEditing(false);
+ setSameName(r.same_name);
+ toast.success(S.graph.editSaved);
+ // 改了类型/名字,图谱节点与本体计数都要跟着动
+ qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
+ qc.invalidateQueries({ queryKey: ["graph", kbId] });
+ qc.invalidateQueries({ queryKey: ["ontology", kbId] });
+ },
+ onError: (err: Error) => toast.error(err.message),
+ });
+
+ const dirty =
+ !!e &&
+ (draftName.trim() !== e.name ||
+ draftType !== (types.find((t) => t.key === e.type_key)?.id ?? ""));
+
// Relations = 当下有效的快照(as-of now);已闭合的历史只出现在 Timeline。
// 按「方向 + 谓词」分组:实体自身名不再逐行重复,谓词只出现在小节标题里
const { groups, historicalCount } = useMemo(() => {
@@ -1227,18 +1281,118 @@ function EntityPanel({
{e.name}
</span>
</div>
+ {/* 消歧后缀找不到关联事实时兜底成类型标签,那就与后面的类型重复了 */}
<div className="mt-1 text-xs text-neutral-500">
- {e.disambiguator ? `${e.disambiguator} · ` : ""}
+ {e.disambiguator && e.disambiguator !== e.type_label
+ ? `${e.disambiguator} · `
+ : ""}
{e.type_label} · {detail.data?.facts.length ?? 0} {S.graph.facts}
</div>
</>
)}
</div>
- <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200 mt-0.5">
- <X size={15} />
- </button>
+ <div className="flex items-center gap-1.5 mt-0.5">
+ {e && !editing && (
+ <button
+ onClick={openEdit}
+ title={S.graph.edit}
+ className="text-neutral-500 hover:text-neutral-200"
+ >
+ <Pencil size={13} />
+ </button>
+ )}
+ <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
+ <X size={15} />
+ </button>
+ </div>
</div>
+ {editing && e && (
+ <div className="px-4 py-3 border-b border-white/10 space-y-2.5">
+ <label className="block">
+ <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500">
+ {S.graph.editName}
+ </span>
+ <input
+ autoFocus
+ value={draftName}
+ onChange={(ev) => setDraftName(ev.target.value)}
+ onKeyDown={(ev) => {
+ if (ev.key === "Enter" && dirty && draftName.trim()) save.mutate();
+ if (ev.key === "Escape") setEditing(false);
+ }}
+ className="mt-1 w-full bg-white/[0.04] border border-white/10 rounded px-2 py-1 text-sm text-neutral-100 focus:outline-none focus:border-white/25"
+ />
+ </label>
+ <label className="block">
+ <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500">
+ {S.graph.editType}
+ </span>
+ <select
+ value={draftType}
+ onChange={(ev) => setDraftType(ev.target.value)}
+ className="mt-1 w-full bg-white/[0.04] border border-white/10 rounded px-2 py-1 text-sm text-neutral-100 focus:outline-none focus:border-white/25"
+ >
+ {types.map((t) => (
+ <option key={t.id} value={t.id} className="bg-neutral-900">
+ {t.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <div className="flex items-center gap-2 pt-0.5">
+ <button
+ disabled={!dirty || !draftName.trim() || save.isPending}
+ onClick={() => save.mutate()}
+ className="u-pop px-2.5 py-1 text-xs rounded bg-white/10 text-neutral-100 hover:bg-white/15 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {S.graph.editSave}
+ </button>
+ <button
+ onClick={() => setEditing(false)}
+ className="px-2.5 py-1 text-xs rounded text-neutral-500 hover:text-neutral-300"
+ >
+ {S.graph.editCancel}
+ </button>
+ {!draftName.trim() && (
+ <span className="text-[11px] text-[var(--u-danger)]">{S.graph.editEmptyName}</span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* 同名不是错误——两个张伟可以并存。只提示,判定是不是同一个是人的事 */}
+ {sameName.length > 0 && !editing && (
+ <div className="mx-4 mt-2.5 rounded border border-white/10 bg-white/[0.03] px-2.5 py-2">
+ <div className="flex items-start justify-between gap-2">
+ <p className="text-[11px] text-neutral-400">
+ {S.graph.sameNameNote(sameName.length)}{" "}
+ <span className="text-neutral-500">{S.graph.sameNameHint}</span>
+ </p>
+ <button
+ onClick={() => setSameName([])}
+ className="text-neutral-600 hover:text-neutral-300 shrink-0"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ <div className="mt-1.5 flex flex-wrap gap-1">
+ {sameName.map((p) => (
+ <button
+ key={p.id}
+ onClick={() => onNavigate(p.id)}
+ className="text-[11px] px-1.5 py-0.5 rounded bg-white/[0.06] text-neutral-300 hover:bg-white/10"
+ >
+ {p.type_label}
+ {p.disambiguator && p.disambiguator !== p.type_label
+ ? ` · ${p.disambiguator}`
+ : ""}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
{/* 视图切换:Relations(分组)| Timeline(年表) */}
<div className="px-4 pt-2.5">
<div className="flex rounded-lg overflow-hidden border border-white/10 w-fit">