Skip to content

World's first open-source enterprise world model.

Deleting a document is an event, and it can be undone (#273)

WaylandYange02f820ff3b7
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 459459fb..5990aa86 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -106,6 +106,9 @@ pub struct Document {
pub external_key: Option<String>,
/// watch_folder 同步时发现源文件已消失(默认保留文档,仅标记)
pub missing_since: Option<DateTime<Utc>>,
+ /// 墓碑(#268):删除是认知轴上的一个事件。行、分块、证据、原始文件都留着,
+ /// 只是不再算活的;撤销、同步撞见、同内容重传都能把它复活
+ pub deleted_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -799,6 +802,8 @@ pub struct EvidenceView {
pub doc_version: i32,
/// 文档已有更新的版本(证据停留在旧版;不代表事实失效)
pub stale: bool,
+ /// 这条证据所在的文档已被删除(#268)。事实若还活着,是因为它另有出处
+ pub document_deleted: bool,
}
/// 时态冲突(S3 自动闭合拿不准的那些):旧事实 vs 新事实,Review 页人裁。
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rs
index 425292e5..08a3f680 100644
--- a/crates/utopia-server/src/api/documents_routes.rs
+++ b/crates/utopia-server/src/api/documents_routes.rs
@@ -223,13 +223,16 @@ pub async fn delete(
let doc = utopia_store::documents::get(&state.pool, id).await?;
utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?;
- utopia_store::documents::delete(&state.pool, id).await?;
+ // 墓碑,不是减法(#268):文档、分块、证据、原始文件都留着;只作废没有别的出处的事实
+ let report = utopia_store::documents::delete(&state.pool, doc.kb_id, id, Some(user.id)).await?;
let search = state.search.clone();
let did = id.to_string();
tokio::task::spawn_blocking(move || search.delete_document(&did))
.await
.map_err(|e| AppError::Other(e.into()))?
.map_err(AppError::Other)?;
+ // 前提作废了,靠它推出来的派生随之失效——不等下一次定时重推
+ settle_derivations(&state, doc.kb_id).await?;
let _ = utopia_store::audit::record(
&state.pool,
Some(doc.kb_id),
@@ -237,12 +240,76 @@ pub async fn delete(
"document.deleted",
"document",
Some(id),
+ json!({
+ "filename": doc.filename,
+ "deletion_id": report.deletion_id,
+ "invalidated_facts": report.invalidated_facts,
+ }),
+ )
+ .await;
+ state.emit_document(doc.kb_id, id);
+ Ok(Json(json!({
+ "ok": true,
+ "deletion_id": report.deletion_id,
+ "invalidated_facts": report.invalidated_facts,
+ })))
+}
+
+/// 撤销删除:文档、分块、这次作废的事实原路复活,索引重建。
+/// 同步撞见墓碑与同内容重传走的是同一个 store 函数,这里只是人按的那一条路
+pub async fn restore(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?;
+ let doc = utopia_store::documents::restore(&state.pool, doc.kb_id, id).await?;
+ reindex(&state, &doc).await?;
+ settle_derivations(&state, doc.kb_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(doc.kb_id),
+ user.id,
+ "document.restored",
+ "document",
+ Some(id),
json!({ "filename": doc.filename }),
)
.await;
+ state.emit_document(doc.kb_id, id);
Ok(Json(json!({ "ok": true })))
}
+/// 复活的文档回到全文索引:分块的正文一直都在,只是重写一遍索引条目
+pub async fn reindex(state: &AppState, doc: &Document) -> utopia_core::AppResult<()> {
+ let chunks =
+ utopia_store::documents::chunks_in_document(&state.pool, doc.kb_id, doc.id).await?;
+ let pairs: Vec<(String, String)> = chunks
+ .into_iter()
+ .map(|c| (c.id.to_string(), c.text))
+ .collect();
+ let search = state.search.clone();
+ let (kb, did) = (doc.kb_id.to_string(), doc.id.to_string());
+ tokio::task::spawn_blocking(move || search.reindex_document(&kb, &did, &pairs))
+ .await
+ .map_err(|e| AppError::Other(e.into()))?
+ .map_err(AppError::Other)?;
+ Ok(())
+}
+
+/// 前提变了就重推一遍,让派生跟上——开关关着的库不推。删除、撤销、同步复活三条路共用
+pub(crate) async fn settle_derivations(
+ state: &AppState,
+ kb_id: Uuid,
+) -> utopia_core::AppResult<()> {
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ if kb.materialize_inferences {
+ utopia_store::reasoning::materialize(&state.pool, kb_id).await?;
+ }
+ Ok(())
+}
+
/// 重新处理(解析器升级/失败重试)。
pub async fn reprocess(
State(state): State<AppState>,
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 2b0ee313..a04b102b 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -3,7 +3,7 @@ mod alerts_routes;
mod auth_routes;
mod chat;
mod datasource_routes;
-mod documents_routes;
+pub(crate) mod documents_routes;
mod events_routes;
mod graph_routes;
mod jobs_routes;
@@ -276,6 +276,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/documents/{id}",
get(documents_routes::detail).delete(documents_routes::delete),
)
+ // 撤销删除(#268):删除是墓碑,所以有得撤
+ .route("/documents/{id}/restore", post(documents_routes::restore))
.route("/documents/{id}/extract", post(graph_routes::extract))
.route("/kbs/{id}/graph/overview", get(graph_routes::overview))
.route(
diff --git a/crates/utopia-server/src/api/sources_routes.rs b/crates/utopia-server/src/api/sources_routes.rs
index 3889a69e..7990b1e6 100644
--- a/crates/utopia-server/src/api/sources_routes.rs
+++ b/crates/utopia-server/src/api/sources_routes.rs
@@ -238,7 +238,7 @@ pub async fn cleanup_missing(
source_in_kb(&state, kb_id, source_id).await?;
let ids = utopia_store::documents::list_missing(&state.pool, source_id).await?;
for id in &ids {
- utopia_store::documents::delete(&state.pool, *id).await?;
+ utopia_store::documents::delete(&state.pool, kb_id, *id, Some(user.id)).await?;
let search = state.search.clone();
let did = id.to_string();
tokio::task::spawn_blocking(move || search.delete_document(&did))
diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs
index a1803d48..983cf5e5 100644
--- a/crates/utopia-server/src/ingest_sources.rs
+++ b/crates/utopia-server/src/ingest_sources.rs
@@ -212,7 +212,30 @@ pub async fn ingest_item(
}
if let Some(doc) = existing {
+ // 同步撞见墓碑:源头还有这篇,本地删除对同步源本来就是暂时的——复活它,
+ // 分块与这次作废的事实原路回来,索引重建(#268)
+ let revived = doc.deleted_at.is_some();
+ if revived {
+ let doc = utopia_store::documents::restore(&state.pool, kb_id, doc.id).await?;
+ crate::api::documents_routes::reindex(state, &doc).await?;
+ crate::api::documents_routes::settle_derivations(state, kb_id).await?;
+ // 引擎做的,没有人:actor 留空,台账写「engine」
+ let _ = utopia_store::audit::record_opt(
+ &state.pool,
+ Some(kb_id),
+ None,
+ "document.restored",
+ "document",
+ Some(doc.id),
+ serde_json::json!({ "filename": doc.filename, "via": "sync" }),
+ )
+ .await;
+ }
if doc.sha256 == sha256 {
+ if revived {
+ state.emit_document(kb_id, doc.id);
+ return Ok(IngestAction::Updated);
+ }
return Ok(IngestAction::Unchanged);
}
// 变更:原地替换,旧版本入 document_versions(blob 内容寻址不删,回放有料)
diff --git a/crates/utopia-store/src/access.rs b/crates/utopia-store/src/access.rs
index 9f57a2c8..bfa4baaa 100644
--- a/crates/utopia-store/src/access.rs
+++ b/crates/utopia-store/src/access.rs
@@ -149,7 +149,8 @@ pub async fn my_kb_infos(
m.role AS member_role,
m.created_at AS joined_at,
inviter.display_name AS added_by_name,
- (SELECT count(*) FROM documents d WHERE d.kb_id = k.id) AS doc_count,
+ (SELECT count(*) FROM documents d
+ WHERE d.kb_id = k.id AND d.deleted_at IS NULL) AS doc_count,
(SELECT count(*) FROM kb_members mm WHERE mm.kb_id = k.id) AS member_count
FROM knowledge_bases k
LEFT JOIN kb_members m ON m.kb_id = k.id AND m.user_id = $2
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
index 3b9f589f..e5328455 100644
--- a/crates/utopia-store/src/documents.rs
+++ b/crates/utopia-store/src/documents.rs
@@ -17,6 +17,18 @@ pub async fn create(
doc_time: Option<chrono::DateTime<chrono::Utc>>,
external_key: Option<&str>,
) -> AppResult<Document> {
+ // 同样的内容回来了,而它只是被删过:复活那一篇,而不是撞 (kb_id, sha256) 的唯一
+ // 索引报「已存在」。撤销删除的一种自然形态——重传就是「我要它回来」(#268)
+ if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
+ "SELECT id FROM documents WHERE kb_id = $1 AND sha256 = $2 AND deleted_at IS NOT NULL",
+ )
+ .bind(kb_id)
+ .bind(sha256)
+ .fetch_optional(pool)
+ .await?
+ {
+ return restore(pool, kb_id, id).await;
+ }
sqlx::query_as(
"INSERT INTO documents (id, kb_id, filename, mime, size_bytes, sha256, source_id,
doc_time, doc_time_source, external_key)
@@ -47,10 +59,12 @@ pub async fn create(
}
pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Document>> {
- let rows = sqlx::query_as("SELECT * FROM documents WHERE kb_id = $1 ORDER BY created_at DESC")
- .bind(kb_id)
- .fetch_all(pool)
- .await?;
+ let rows = sqlx::query_as(
+ "SELECT * FROM documents WHERE kb_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
Ok(rows)
}
@@ -77,7 +91,7 @@ pub async fn page(
// `$2 = 'any'` 那一支是「不按来源筛」,`'none'` 是「只看没有来源的」——
// 用两个哨兵字符串而不是两个可空参数,因为 NULL 在这里有歧义:
// 它既可能是「不筛」,也可能是「筛出 source_id IS NULL 的」
- const WHERE: &str = "WHERE kb_id = $1
+ const WHERE: &str = "WHERE kb_id = $1 AND deleted_at IS NULL
AND ($2 = 'any'
OR ($2 = 'none' AND source_id IS NULL)
OR source_id::text = $2)
@@ -116,7 +130,7 @@ pub async fn page(
count(*) FILTER (WHERE graph_status IN ('queued', 'extracting')),
count(*) FILTER (WHERE graph_status = 'failed')
FROM documents
- WHERE kb_id = $1
+ WHERE kb_id = $1 AND deleted_at IS NULL
AND ($2 = 'any'
OR ($2 = 'none' AND source_id IS NULL)
OR source_id::text = $2)",
@@ -148,7 +162,7 @@ pub async fn failed_ids(
};
Ok(sqlx::query_scalar(
"SELECT id FROM documents
- WHERE kb_id = $1 AND graph_status = 'failed'
+ WHERE kb_id = $1 AND deleted_at IS NULL AND graph_status = 'failed'
AND ($2 = 'any'
OR ($2 = 'none' AND source_id IS NULL)
OR source_id::text = $2)",
@@ -170,13 +184,13 @@ pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Document> {
/// 按 kb 收窄的取文档。**id 由模型给出时只能走这一支**:`get` 只按 id 查,
/// 一个别的库的 id 照样查得到。
pub async fn find_in_kb(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Option<Document>> {
- Ok(
- sqlx::query_as("SELECT * FROM documents WHERE id = $1 AND kb_id = $2")
- .bind(id)
- .bind(kb_id)
- .fetch_optional(pool)
- .await?,
+ Ok(sqlx::query_as(
+ "SELECT * FROM documents WHERE id = $1 AND kb_id = $2 AND deleted_at IS NULL",
)
+ .bind(id)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?)
}
/// 按来源内逻辑身份查文档(同步三路判定用)。
@@ -200,13 +214,14 @@ pub async fn find_by_source_sha(
source_id: Uuid,
sha256: &str,
) -> AppResult<Option<Document>> {
- Ok(
- sqlx::query_as("SELECT * FROM documents WHERE source_id = $1 AND sha256 = $2 LIMIT 1")
- .bind(source_id)
- .bind(sha256)
- .fetch_optional(pool)
- .await?,
+ Ok(sqlx::query_as(
+ "SELECT * FROM documents
+ WHERE source_id = $1 AND sha256 = $2 AND deleted_at IS NULL LIMIT 1",
)
+ .bind(source_id)
+ .bind(sha256)
+ .fetch_optional(pool)
+ .await?)
}
/// 迁移前的历史文档(无 external_key)按文件名认领——0008 之前建的行的一次性兜底。
@@ -217,7 +232,8 @@ pub async fn find_legacy_by_filename(
) -> AppResult<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents
- WHERE source_id = $1 AND external_key IS NULL AND filename = $2 LIMIT 1",
+ WHERE source_id = $1 AND external_key IS NULL AND filename = $2
+ AND deleted_at IS NULL LIMIT 1",
)
.bind(source_id)
.bind(filename)
@@ -355,7 +371,8 @@ pub async fn mark_missing_keys(pool: &PgPool, source_id: Uuid, keys: &[String])
/// 该来源下所有已标记 missing 的文档 id(批量清理用)。
pub async fn list_missing(pool: &PgPool, source_id: Uuid) -> AppResult<Vec<Uuid>> {
let rows: Vec<(Uuid,)> = sqlx::query_as(
- "SELECT id FROM documents WHERE source_id = $1 AND missing_since IS NOT NULL",
+ "SELECT id FROM documents
+ WHERE source_id = $1 AND missing_since IS NOT NULL AND deleted_at IS NULL",
)
.bind(source_id)
.fetch_all(pool)
@@ -396,15 +413,139 @@ pub async fn set_ready(pool: &PgPool, id: Uuid, text_len: i32, chunk_count: i32)
Ok(())
}
-pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
- let res = sqlx::query("DELETE FROM documents WHERE id = $1")
- .bind(id)
- .execute(pool)
- .await?;
- if res.rows_affected() == 0 {
+/// 一次删除的产出,给审计与界面提示用。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DeletionReport {
+ pub deletion_id: Uuid,
+ /// 随之作废的事实:只有「每条出处都已删除」的那些
+ pub invalidated_facts: usize,
+ pub superseded_chunks: usize,
+}
+
+/// 删除一篇文档——**认知轴上的一个事件,不是减法**(#268)。
+///
+/// 从前这里一句 `DELETE`,外键把分块与证据一并级联掉:事实留在图里、活着、却没了
+/// 出处,而隐私政策写着「事实连同其出处保留」。现在文档打墓碑,分块走 `replace_chunks`
+/// 用了很久的 `superseded_at`,**什么内容都不清**——原始文件本来也没删过;只作废
+/// 「每条出处都已删除」的事实。判据看 `documents.deleted_at` 而不是分块的
+/// `superseded_at`:证据停在文档**旧版本**上的事实是 stale,按 `stale_facts` 的规矩
+/// 「没再提 ≠ 不成立」,交给人、不作废;只有源本身没了才作废。
+///
+/// 作废的事实与打标的分块记进 `document_deletions`,[`restore`] 原路读回。
+/// `actor` 为 None = 引擎(来源对账的批量清理)
+pub async fn delete(
+ pool: &PgPool,
+ kb_id: Uuid,
+ id: Uuid,
+ actor: Option<Uuid>,
+) -> AppResult<DeletionReport> {
+ let mut tx = pool.begin().await?;
+ let hit = sqlx::query(
+ "UPDATE documents SET deleted_at = now(), updated_at = now()
+ WHERE id = $1 AND kb_id = $2 AND deleted_at IS NULL",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .execute(&mut *tx)
+ .await?;
+ if hit.rows_affected() == 0 {
return Err(AppError::NotFound);
}
- Ok(())
+ let chunks: Vec<(Uuid,)> = sqlx::query_as(
+ "UPDATE chunks SET superseded_at = now()
+ WHERE document_id = $1 AND superseded_at IS NULL RETURNING id",
+ )
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?;
+ // 先打了墓碑再算:这篇文档此刻已经算「已删除」,所以只剩它作出处的事实才落网;
+ // 另一篇活着的文档里也有证据的一条不动——删一份重复上传不该掀掉半张图
+ let facts: Vec<(Uuid,)> = sqlx::query_as(
+ "UPDATE facts f SET invalidated_at = now()
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND EXISTS (SELECT 1 FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ WHERE fe.fact_id = f.id AND c.document_id = $2)
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ JOIN documents d ON d.id = c.document_id
+ WHERE fe.fact_id = f.id AND d.deleted_at IS NULL)
+ RETURNING f.id",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?;
+ let chunk_ids: Vec<Uuid> = chunks.into_iter().map(|(c,)| c).collect();
+ let fact_ids: Vec<Uuid> = facts.into_iter().map(|(f,)| f).collect();
+ let deletion_id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO document_deletions
+ (id, kb_id, document_id, deleted_by, invalidated_facts, superseded_chunks)
+ VALUES ($1, $2, $3, $4, $5, $6)",
+ )
+ .bind(deletion_id)
+ .bind(kb_id)
+ .bind(id)
+ .bind(actor)
+ .bind(&fact_ids)
+ .bind(&chunk_ids)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(DeletionReport {
+ deletion_id,
+ invalidated_facts: fact_ids.len(),
+ superseded_chunks: chunk_ids.len(),
+ })
+}
+
+/// 撤销一次删除:文档、这次打标的分块、这次作废的事实原路复活,形状照 `revert_merge`。
+///
+/// 只救 `document_deletions` 名单上的——更早版本的旧分块、删除之前就作废的事实
+/// 都不在名单里。三条路都从这里走:人点撤销、同步撞见墓碑、同内容重传
+pub async fn restore(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Document> {
+ let row: Option<(Uuid, Vec<Uuid>, Vec<Uuid>)> = sqlx::query_as(
+ "SELECT id, invalidated_facts, superseded_chunks FROM document_deletions
+ WHERE document_id = $1 AND kb_id = $2 AND reverted_at IS NULL
+ ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?;
+ let Some((deletion_id, fact_ids, chunk_ids)) = row else {
+ return Err(AppError::Conflict("Document is not deleted".into()));
+ };
+ let mut tx = pool.begin().await?;
+ let hit = sqlx::query(
+ "UPDATE documents SET deleted_at = NULL, updated_at = now()
+ WHERE id = $1 AND kb_id = $2 AND deleted_at IS NOT NULL",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .execute(&mut *tx)
+ .await?;
+ if hit.rows_affected() == 0 {
+ return Err(AppError::Conflict("Document is not deleted".into()));
+ }
+ sqlx::query("UPDATE chunks SET superseded_at = NULL WHERE id = ANY($1)")
+ .bind(&chunk_ids)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "UPDATE facts SET invalidated_at = NULL
+ WHERE id = ANY($1) AND invalidated_at IS NOT NULL",
+ )
+ .bind(&fact_ids)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE document_deletions SET reverted_at = now() WHERE id = $1")
+ .bind(deletion_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ get(pool, id).await
}
/// 重建文档分块(事务内,幂等)。返回 (chunk_id, text) 供全文索引。
@@ -661,7 +802,8 @@ pub async fn chunks_by_ids(pool: &PgPool, kb_id: Uuid, ids: &[Uuid]) -> AppResul
let rows: Vec<ChunkView> = sqlx::query_as(
"SELECT c.id, c.document_id, c.seq, c.text, d.filename
FROM chunks c JOIN documents d ON d.id = c.document_id
- WHERE c.kb_id = $1 AND c.id = ANY($2)",
+ WHERE c.kb_id = $1 AND c.id = ANY($2)
+ AND c.superseded_at IS NULL AND d.deleted_at IS NULL",
)
.bind(kb_id)
.bind(ids)
@@ -708,7 +850,8 @@ pub async fn queue_extraction(
let mut tx = pool.begin().await?;
let ids: Vec<(Uuid,)> = sqlx::query_as(
"SELECT id FROM documents
- WHERE kb_id = $1 AND status = 'ready' AND ($2::uuid IS NULL OR source_id = $2)
+ WHERE kb_id = $1 AND deleted_at IS NULL AND status = 'ready'
+ AND ($2::uuid IS NULL OR source_id = $2)
ORDER BY created_at",
)
.bind(kb_id)
@@ -788,7 +931,7 @@ pub async fn extract_epoch(pool: &PgPool, id: Uuid) -> AppResult<i32> {
pub async fn extraction_idle(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
let (pending,): (i64,) = sqlx::query_as(
"SELECT count(*) FROM documents
- WHERE kb_id = $1 AND graph_status IN ('queued', 'extracting')",
+ WHERE kb_id = $1 AND deleted_at IS NULL AND graph_status IN ('queued', 'extracting')",
)
.bind(kb_id)
.fetch_one(pool)
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index fe7689ad..e70b96fd 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -892,7 +892,8 @@ pub async fn fact_evidence(pool: &PgPool, fact_id: Uuid) -> AppResult<Vec<Eviden
c.doc_version,
c.doc_version < COALESCE(
(SELECT MAX(version) FROM document_versions dv
- WHERE dv.document_id = c.document_id), 1) AS stale
+ WHERE dv.document_id = c.document_id), 1) AS stale,
+ d.deleted_at IS NOT NULL AS document_deleted
FROM fact_evidence fe
JOIN chunks c ON c.id = fe.chunk_id
JOIN documents d ON d.id = c.document_id
diff --git a/crates/utopia-store/src/memory.rs b/crates/utopia-store/src/memory.rs
index d188ed4e..eb2fcd32 100644
--- a/crates/utopia-store/src/memory.rs
+++ b/crates/utopia-store/src/memory.rs
@@ -43,7 +43,8 @@ pub async fn get_or_create_memory_source(pool: &PgPool, kb_id: Uuid) -> AppResul
/// 它不是内容寻址的文件,sha256 填哨兵值。
pub async fn get_or_create_memory_doc(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {
if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
- "SELECT id FROM documents WHERE kb_id = $1 AND external_key = $2 LIMIT 1",
+ "SELECT id FROM documents
+ WHERE kb_id = $1 AND external_key = $2 AND deleted_at IS NULL LIMIT 1",
)
.bind(kb_id)
.bind(MEMORY_DOC_KEY)
diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs
index ab7add38..db00ee6a 100644
--- a/crates/utopia-store/src/sources.rs
+++ b/crates/utopia-store/src/sources.rs
@@ -56,9 +56,11 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<SourceView>> {
"SELECT s.id, s.kind, s.name, s.config - $2::text[] AS config, s.icon,
s.sync_interval_minutes, s.sync_cron,
s.last_sync_at, s.last_sync_status, s.last_sync_error, s.last_sync_added,
- (SELECT count(*) FROM documents d WHERE d.source_id = s.id) AS doc_count,
(SELECT count(*) FROM documents d
- WHERE d.source_id = s.id AND d.missing_since IS NOT NULL) AS missing_count
+ WHERE d.source_id = s.id AND d.deleted_at IS NULL) AS doc_count,
+ (SELECT count(*) FROM documents d
+ WHERE d.source_id = s.id AND d.missing_since IS NOT NULL
+ AND d.deleted_at IS NULL) AS missing_count
FROM sources s WHERE s.kb_id = $1 ORDER BY s.created_at",
)
.bind(kb_id)
@@ -323,12 +325,14 @@ pub async fn set_document_tags(
/// 同步用去重:该 KB 是否已有同内容文档。
pub async fn document_exists_by_sha(pool: &PgPool, kb_id: Uuid, sha256: &str) -> AppResult<bool> {
- let row: Option<(Uuid,)> =
- sqlx::query_as("SELECT id FROM documents WHERE kb_id = $1 AND sha256 = $2 LIMIT 1")
- .bind(kb_id)
- .bind(sha256)
- .fetch_optional(pool)
- .await?;
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM documents
+ WHERE kb_id = $1 AND sha256 = $2 AND deleted_at IS NULL LIMIT 1",
+ )
+ .bind(kb_id)
+ .bind(sha256)
+ .fetch_optional(pool)
+ .await?;
Ok(row.is_some())
}
diff --git a/crates/utopia-store/tests/a_deletion_is_an_event.rs b/crates/utopia-store/tests/a_deletion_is_an_event.rs
new file mode 100644
index 00000000..8e2a21f1
--- /dev/null
+++ b/crates/utopia-store/tests/a_deletion_is_an_event.rs
@@ -0,0 +1,311 @@
+//! #268:删除文档是认知轴上的一个事件,不是减法。
+//!
+//! 此前 `documents::delete` 一句 DELETE,外键把分块与证据一并级联掉:事实留在图里、
+//! 活着、却没了出处。现在文档打墓碑,分块打标,**什么内容都不清**,只作废「每条出处
+//! 都已删除」的事实。这里守五件事:
+//!
+//! 1. **只作废没有别的出处的。** 甲乙两篇都作证的事实,删甲不动它;只有甲作证的作废。
+//! 分块打了标但正文还在;文档不再出现在列表里。
+//! 2. **删两次报错。**
+//! 3. **撤销原路回来。** 文档、这次打标的分块、这次作废的事实复活;删之前就已作废的
+//! 事实不在名单上,不会被误救。撤销一篇没删的报错。
+//! 4. **同内容重传复活墓碑**:同一个 id 回来,而不是撞唯一索引报「已存在」。
+//! 5. **判据看文档,不看分块。** 停在旧版分块上的证据是 stale,不是没了源——不作废。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use utopia_store::documents;
+use uuid::Uuid;
+
+struct Fx {
+ org: Uuid,
+ user: Uuid,
+ kb: Uuid,
+ src: Uuid,
+ etype: Uuid,
+ rel: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fx> {
+ let (org, ws, kb, user) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ let (src, etype, rel) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'deletion-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'deletion-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash)
+ VALUES ($1, $2, $1 || '@deletion.test', 'd', 'x')",
+ )
+ .bind(user)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'deletion-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO sources (id, kb_id, kind, name) VALUES ($1, $2, 'folder', 'f')")
+ .bind(src)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'knows', 'knows')",
+ )
+ .bind(rel)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ Ok(Fx {
+ org,
+ user,
+ kb,
+ src,
+ etype,
+ rel,
+ })
+}
+
+async fn document(pool: &PgPool, f: &Fx, name: &str, sha: &str) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status)
+ VALUES ($1, $2, $3, $4, $5, 'ready')",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.src)
+ .bind(name)
+ .bind(sha)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn chunk(pool: &PgPool, f: &Fx, doc: Uuid, version: i32) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text, doc_version, superseded_at)
+ VALUES ($1, $2, $3, 0, 'the text stays', $4, CASE WHEN $4 = 1 THEN NULL ELSE now() END)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(doc)
+ .bind(version)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn entity(pool: &PgPool, f: &Fx, name: &str) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 一条事实,出处是给定的几个分块
+async fn fact(pool: &PgPool, f: &Fx, s: Uuid, o: Uuid, evidence: &[Uuid]) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
+ VALUES ($1, $2, $3, $4, $5, 0.9)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(s)
+ .bind(f.rel)
+ .bind(o)
+ .execute(pool)
+ .await?;
+ for c in evidence {
+ sqlx::query("INSERT INTO fact_evidence (fact_id, chunk_id, quote) VALUES ($1, $2, 'q')")
+ .bind(id)
+ .bind(c)
+ .execute(pool)
+ .await?;
+ }
+ Ok(id)
+}
+
+async fn live(pool: &PgPool, id: Uuid) -> anyhow::Result<bool> {
+ Ok(
+ sqlx::query_scalar("SELECT invalidated_at IS NULL FROM facts WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?,
+ )
+}
+
+async fn chunk_live(pool: &PgPool, id: Uuid) -> anyhow::Result<(bool, String)> {
+ Ok(
+ sqlx::query_as("SELECT superseded_at IS NULL, text FROM chunks WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?,
+ )
+}
+
+async fn listed(pool: &PgPool, f: &Fx, id: Uuid) -> anyhow::Result<bool> {
+ Ok(documents::list(pool, f.kb)
+ .await?
+ .iter()
+ .any(|d| d.id == id))
+}
+
+#[tokio::test]
+async fn a_deletion_is_an_event() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let a = document(&pool, &f, "a.md", "sha-a").await?;
+ let b = document(&pool, &f, "b.md", "sha-b").await?;
+ let a1 = chunk(&pool, &f, a, 1).await?;
+ let b1 = chunk(&pool, &f, b, 1).await?;
+ let (x, y, z, w) = (
+ entity(&pool, &f, "X").await?,
+ entity(&pool, &f, "Y").await?,
+ entity(&pool, &f, "Z").await?,
+ entity(&pool, &f, "W").await?,
+ );
+ // 只有甲作证;甲乙都作证;甲作证但删之前就作废了
+ let only_a = fact(&pool, &f, x, y, &[a1]).await?;
+ let both = fact(&pool, &f, x, z, &[a1, b1]).await?;
+ let already_gone = fact(&pool, &f, x, w, &[a1]).await?;
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(already_gone)
+ .execute(&pool)
+ .await?;
+
+ // 1. 删甲
+ let report = documents::delete(&pool, f.kb, a, Some(f.user)).await?;
+ assert_eq!(
+ report.invalidated_facts, 1,
+ "only the fact with no other source"
+ );
+ assert_eq!(report.superseded_chunks, 1);
+ assert!(!live(&pool, only_a).await?);
+ assert!(live(&pool, both).await?, "b still vouches for it");
+ assert!(!listed(&pool, &f, a).await?, "gone from the library");
+ assert!(listed(&pool, &f, b).await?);
+ let (a1_live, text) = chunk_live(&pool, a1).await?;
+ assert!(!a1_live);
+ assert_eq!(text, "the text stays", "nothing is cleared");
+ assert!(
+ documents::get(&pool, a).await?.deleted_at.is_some(),
+ "a tombstone, not a hole"
+ );
+ let (facts, chunks, reverted): (
+ Vec<Uuid>,
+ Vec<Uuid>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ ) = sqlx::query_as(
+ "SELECT invalidated_facts, superseded_chunks, reverted_at
+ FROM document_deletions WHERE document_id = $1",
+ )
+ .bind(a)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(facts, vec![only_a]);
+ assert_eq!(chunks, vec![a1]);
+ assert!(reverted.is_none());
+
+ // 2. 删两次
+ assert!(documents::delete(&pool, f.kb, a, Some(f.user))
+ .await
+ .is_err());
+
+ // 3. 撤销原路回来;删之前就作废的不被误救
+ let doc = documents::restore(&pool, f.kb, a).await?;
+ assert!(doc.deleted_at.is_none());
+ assert!(live(&pool, only_a).await?);
+ assert!(live(&pool, both).await?);
+ assert!(
+ !live(&pool, already_gone).await?,
+ "retired before the deletion, so not on the list"
+ );
+ assert!(chunk_live(&pool, a1).await?.0);
+ assert!(listed(&pool, &f, a).await?);
+ let reverted: Option<chrono::DateTime<chrono::Utc>> =
+ sqlx::query_scalar("SELECT reverted_at FROM document_deletions WHERE document_id = $1")
+ .bind(a)
+ .fetch_one(&pool)
+ .await?;
+ assert!(reverted.is_some());
+ assert!(documents::restore(&pool, f.kb, a).await.is_err());
+
+ // 4. 删掉再传同一份内容:同一个 id 回来
+ documents::delete(&pool, f.kb, a, Some(f.user)).await?;
+ assert!(!live(&pool, only_a).await?);
+ let back = documents::create(
+ &pool,
+ f.kb,
+ "a-again.md",
+ "text/markdown",
+ 14,
+ "sha-a",
+ Some(f.src),
+ None,
+ None,
+ )
+ .await?;
+ assert_eq!(back.id, a, "the same document, revived");
+ assert!(back.deleted_at.is_none());
+ assert!(live(&pool, only_a).await?);
+ assert!(chunk_live(&pool, a1).await?.0);
+
+ // 5. 判据看文档:乙的证据停在旧版分块上,删甲时乙还活着,事实不作废
+ let b0 = chunk(&pool, &f, b, 0).await?;
+ let stale_but_sourced = fact(&pool, &f, y, z, &[a1, b0]).await?;
+ let report = documents::delete(&pool, f.kb, a, Some(f.user)).await?;
+ assert_eq!(
+ report.invalidated_facts, 1,
+ "only_a again; the stale one keeps its source"
+ );
+ assert!(
+ live(&pool, stale_but_sourced).await?,
+ "an old version of b is still b, not a missing source"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await;
+ run
+}
diff --git a/migrations/0022_deleting_is_an_event.sql b/migrations/0022_deleting_is_an_event.sql
new file mode 100644
index 00000000..fa085546
--- /dev/null
+++ b/migrations/0022_deleting_is_an_event.sql
@@ -0,0 +1,29 @@
+-- 删除文档是认知轴上的一个事件,不是减法(#268)。
+--
+-- 此前 `documents::delete` 一句 DELETE,外键把 chunks 与 fact_evidence 一并级联掉:
+-- 事实留在图里、活着、却没了出处——而隐私政策写着「事实连同其出处保留」。原始文件
+-- 反倒从来没删(BlobStore 没有 delete)。同步源的文档删掉之后下一次同步按 external_key
+-- 找不到,建一篇新的再抽一遍,旧事实又从没作废,同一条断言落两遍。
+--
+-- 现在:文档打墓碑(deleted_at),分块走已有的 superseded_at,**什么内容都不清**——
+-- 内容留到显式的 purge(另一条路,未做);只作废「每条出处都已删除」的事实;这次
+-- 作废了哪些事实、打标了哪些分块记在 document_deletions 里,撤销、同步复活、同内容
+-- 重传复活都从那里原路读回,不多不少。形状照 entity_merges / revert_merge。
+ALTER TABLE documents ADD COLUMN deleted_at TIMESTAMPTZ;
+-- 文库列表与各处计数只看活的
+CREATE INDEX documents_live_idx ON documents (kb_id, created_at DESC) WHERE deleted_at IS NULL;
+
+CREATE TABLE document_deletions (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
+ -- NULL = 引擎(来源对账的批量清理)
+ deleted_by UUID REFERENCES users(id),
+ -- 这次删除作废的事实与打标的分块。撤销时只复活这两份名单里的:之前就已作废的
+ -- 事实、更早版本的旧分块,都不在名单里,也就不会被误救
+ invalidated_facts UUID[] NOT NULL DEFAULT '{}',
+ superseded_chunks UUID[] NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ reverted_at TIMESTAMPTZ
+);
+CREATE INDEX document_deletions_doc_idx ON document_deletions (document_id, created_at DESC);
diff --git a/web/src/api.ts b/web/src/api.ts
index 71263e1e..ef086f1c 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -164,6 +164,8 @@ export interface Doc {
* `migrations/0002_ingest.sql` 的 `tags` 列上 */
tags: string[];
missing_since: string | null;
+ /** 墓碑(#268):删了但留着,可撤销 */
+ deleted_at: string | null;
created_at: string;
}
@@ -745,6 +747,8 @@ export interface Evidence {
doc_version: number;
/** 文档已有更新版本(证据停留在旧版;不代表事实失效) */
stale: boolean;
+ /** 这条证据的文档已被删除;事实还活着是因为另有出处(#268) */
+ document_deleted: boolean;
}
export interface ChunkFull {
@@ -1345,7 +1349,13 @@ export const api = {
);
},
deleteDocument: (id: string) =>
- request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
+ request<{ ok: boolean; deletion_id: string; invalidated_facts: number }>(
+ `/api/v1/documents/${id}`,
+ { method: "DELETE" },
+ ),
+ /** 撤销删除(#268):文档、分块、随之作废的事实原路复活 */
+ restoreDocument: (id: string) =>
+ request<{ ok: boolean }>(`/api/v1/documents/${id}/restore`, { method: "POST" }),
search: (kbId: string, q: string) =>
request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 5200b196..1f23c13d 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -311,7 +311,7 @@ export const en = {
{
h: "Retention and deletion",
body: [
- "Deleting a document removes its stored content and index entries. Facts already extracted into the knowledge graph remain, with their provenance, until removed through Review. Deleting a knowledge base permanently removes its documents, graph and sources.",
+ "Deleting a document removes it from the base and retires the facts that had no other source; facts with another source keep it as provenance. The content is kept so the deletion can be undone; a deleted document can be restored, and a re-upload of the same file restores it too. Deleting a knowledge base permanently removes its documents, graph and sources.",
],
},
{
@@ -363,6 +363,15 @@ export const en = {
},
},
library: {
+ /** 删除是墓碑(#268):说清作废了几条事实,并给撤销 */
+ deletedWithFacts: (n: number) =>
+ n === 0
+ ? "Document deleted"
+ : n === 1
+ ? "Document deleted · 1 fact retired with it"
+ : `Document deleted · ${n} facts retired with it`,
+ undo: "Undo",
+ restored: "Document restored",
title: "Library",
upload: "Upload files",
uploading: "Uploading…",
@@ -614,8 +623,8 @@ export const en = {
cleanupTitle: "Delete missing documents",
cleanupHint: (n: number, name: string) =>
`${n} document${n === 1 ? "" : "s"} in “${name}” ${n === 1 ? "is" : "are"} no longer ` +
- "present in the source. Deleting removes their content and search entries permanently. " +
- "Facts already extracted into the graph remain, with their provenance.",
+ "present in the source. Deleting removes them from the base and retires the facts that " +
+ "had no other source. Their content is kept, and a deleted document can be restored.",
cleanupConfirm: "Delete them",
deleteSourceTitle: "Delete this source",
deleteSourceBody: (name: string) =>
@@ -706,6 +715,10 @@ export const en = {
sectionRef: (filename: string, seq: number) =>
`${filename} · section ${seq} →`,
fromVersion: (v: number) => `v${v}`,
+ /** 证据所在的文档已删(#268):事实还在是因为另有出处 */
+ sourceDeleted: "source deleted",
+ sourceDeletedHint:
+ "The document this quote came from was deleted. The fact stays because it has another source.",
staleEvidenceHint:
"This evidence comes from an earlier version of the document. " +
"The document has since been updated; the fact itself is unaffected.",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index d316f6f0..ed9f6033 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -284,7 +284,7 @@ export const zh: Strings = {
{
h: "留存与删除",
body: [
- "删除一篇文档会移除它的存储内容与索引条目。已经抽取进知识图谱的事实连同其出处仍会保留,直到在「审阅」中被移除。删除一个知识库会永久移除它的文档、图谱与来源。",
+ "删除一篇文档会把它移出知识库,并让只以它为出处的事实一并失效;另有出处的事实保留,出处照旧。内容会留着以便撤销:删除可以恢复,重新上传同一份文件也会恢复它。删除一个知识库会永久移除它的文档、图谱与来源。",
],
},
{
@@ -336,6 +336,10 @@ export const zh: Strings = {
},
},
library: {
+ deletedWithFacts: (n: number) =>
+ n === 0 ? "文档已删除" : `文档已删除 · 随之失效 ${n} 条事实`,
+ undo: "撤销",
+ restored: "文档已恢复",
title: "文库",
upload: "上传文件",
uploading: "上传中…",
@@ -573,8 +577,8 @@ export const zh: Strings = {
cleanupTitle: "删除缺失的文档",
cleanupHint: (n: number, name: string) =>
`「${name}」中有 ${n} 篇文档已不在来源里。` +
- "删除会永久移除它们的内容与检索条目。" +
- "已经抽取进图谱的事实连同出处仍会保留。",
+ "删除会把它们移出知识库,只以它们为出处的事实随之失效;" +
+ "内容会留着,删掉的文档可以恢复。",
cleanupConfirm: "删除它们",
deleteSourceTitle: "删除这个来源",
deleteSourceBody: (name: string) =>
@@ -652,6 +656,8 @@ export const zh: Strings = {
sectionRef: (filename: string, seq: number) =>
`${filename} · 第 ${seq} 段 →`,
fromVersion: (v: number) => `v${v}`,
+ sourceDeleted: "出处已删",
+ sourceDeletedHint: "这句引文所在的文档已被删除。事实还在,因为它另有出处。",
staleEvidenceHint:
"这条证据来自文档的较早版本。文档此后已更新;事实本身不受影响。",
staleFactChip: "未确认",
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index e4f61e1b..9637ccb7 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -2635,6 +2635,14 @@ function ProofSteps({ kbId, steps }: { kbId: string; steps: ProofStep[] }) {
{S.graph.fromVersion(ev.doc_version)}
</span>
)}
+ {ev.document_deleted && (
+ <span
+ className="ml-1.5 text-[10px] text-[var(--u-contest)]"
+ title={S.graph.sourceDeletedHint}
+ >
+ {S.graph.sourceDeleted}
+ </span>
+ )}
</div>
</Link>
))}
@@ -3592,6 +3600,14 @@ function EvidenceList({ kbId, fact }: { kbId: string; fact: EntityFact }) {
{S.graph.fromVersion(ev.doc_version)}
</span>
)}
+ {ev.document_deleted && (
+ <span
+ className="ml-1.5 text-[10px] text-[var(--u-contest)]"
+ title={S.graph.sourceDeletedHint}
+ >
+ {S.graph.sourceDeleted}
+ </span>
+ )}
</div>
</Link>
))}
diff --git a/web/src/pages/Library.tsx b/web/src/pages/Library.tsx
index 5a379737..8fdb893a 100644
--- a/web/src/pages/Library.tsx
+++ b/web/src/pages/Library.tsx
@@ -417,7 +417,25 @@ export function Library() {
},
onSuccess: invalidate,
});
- const remove = useMutation({ mutationFn: (id: string) => api.deleteDocument(id), onSuccess: invalidate });
+ // 删除是墓碑(#268):提示里给一个「撤销」,点了原路复活
+ const restore = useMutation({
+ mutationFn: (id: string) => api.restoreDocument(id),
+ onSuccess: () => {
+ toast.success(S.library.restored);
+ invalidate();
+ },
+ onError: (e) => toast.error(String(e)),
+ });
+ const remove = useMutation({
+ mutationFn: (id: string) => api.deleteDocument(id),
+ onSuccess: (r, id) => {
+ toast.info(S.library.deletedWithFacts(r.invalidated_facts), {
+ label: S.library.undo,
+ onClick: () => restore.mutate(id),
+ });
+ invalidate();
+ },
+ });
const extract = useMutation({ mutationFn: (id: string) => api.extractDocument(id), onSuccess: invalidate });
const reprocess = useMutation({
mutationFn: (id: string) => api.reprocessDocument(id),
diff --git a/web/src/toast.tsx b/web/src/toast.tsx
index 3d673dbf..ebe2e15a 100644
--- a/web/src/toast.tsx
+++ b/web/src/toast.tsx
@@ -1,11 +1,13 @@
/* 全局消息(toast):模块级单例 + <ToastHost/>(挂在应用根部一次)。
任何模块 `import { toast } from "./toast"` 即可弹消息,无需 context 接线。
- 右下角堆叠,success/info 3.8s、error 6s 自动消失,可手动关闭。 */
+ 右下角堆叠,success/info 3.8s、error 6s 自动消失,可手动关闭。
+ 可带一个动作(如「撤销」):带动作的留 8s,点了动作即关闭。 */
import { useEffect, useState } from "react";
import { AlertCircle, CheckCircle2, Info, X } from "lucide-react";
type Kind = "success" | "error" | "info";
-type Item = { id: number; kind: Kind; text: string };
+type Action = { label: string; onClick: () => void };
+type Item = { id: number; kind: Kind; text: string; action?: Action };
let nextId = 1;
let items: Item[] = [];
@@ -16,17 +18,19 @@ function dismiss(id: number) {
listener?.(items);
}
-function push(kind: Kind, text: string) {
+function push(kind: Kind, text: string, action?: Action) {
const id = nextId++;
- items = [...items, { id, kind, text }];
+ items = [...items, { id, kind, text, action }];
listener?.(items);
- window.setTimeout(() => dismiss(id), kind === "error" ? 6000 : 3800);
+ // 带动作的多留一会儿:「撤销」要给人看清楚再点的时间
+ const ttl = kind === "error" ? 6000 : action ? 8000 : 3800;
+ window.setTimeout(() => dismiss(id), ttl);
}
export const toast = {
- success: (text: string) => push("success", text),
+ success: (text: string, action?: Action) => push("success", text, action),
error: (text: string) => push("error", text),
- info: (text: string) => push("info", text),
+ info: (text: string, action?: Action) => push("info", text, action),
};
const ICON = { success: CheckCircle2, error: AlertCircle, info: Info } as const;
@@ -56,6 +60,17 @@ export function ToastHost() {
>
<Icon size={15} className={`shrink-0 ${ICON_COLOR[t.kind]}`} />
<span className="max-w-xs">{t.text}</span>
+ {t.action && (
+ <button
+ onClick={() => {
+ t.action?.onClick();
+ dismiss(t.id);
+ }}
+ className="u-link shrink-0 text-xs"
+ >
+ {t.action.label}
+ </button>
+ )}
<button
onClick={() => dismiss(t.id)}
className="text-neutral-600 hover:text-neutral-300"