Skip to content

World's first open-source enterprise world model.

An empty page says which step comes next (#321)

WaylandYang90e5c0ab9c9a
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 27283f51..b61817fa 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -808,6 +808,29 @@ pub struct EvidenceView {
pub document_deleted: bool,
}
+/// 这个库走到哪一步了(#313):四个页面的空状态共用同一个判断。
+///
+/// 每个页面此前都各自假设「已经就绪」,于是空状态只会说同一句话:图谱页
+/// 让人去配模型,哪怕文档正在抽取;对话页照常显示问候语,哪怕模型根本没配——
+/// 用户问出第一句才撞墙。
+///
+/// **只回布尔与计数。** 模型那一项来自工作区设置,而那张表要 workspace admin
+/// 才看得到(`settings_routes::get`)。普通成员看不到配置,却需要知道配没配,
+/// 所以这里只说「有没有」,不带 base_url、模型名或任何凭据。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Readiness {
+ /// 工作区配了对话模型。没有它,抽取与对话都跑不起来
+ pub has_chat_model: bool,
+ /// 活文档数(墓碑不算——删掉的文档不构成「库里有东西」)
+ pub documents: i64,
+ /// 正在解析或抽取的文档数
+ pub processing: i64,
+ /// 解析或抽取失败的文档数
+ pub failed: i64,
+ /// 图里的实体数。文档齐了、抽取也跑完了,这个还是 0 说明什么都没抽出来
+ pub entities: i64,
+}
+
/// 时态冲突(S3 自动闭合拿不准的那些):旧事实 vs 新事实,Review 页人裁。
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct ConflictView {
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index 500cfb20..a7cfd483 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -222,6 +222,19 @@ pub async fn delete(
Ok(Json(json!({ "ok": true })))
}
+/// 这个库走到哪一步了(#313):四个页面的空状态共用同一个判断。
+///
+/// Viewer 起步——看得见这个库的人都该知道它是空的还是在跑。回的全是布尔与
+/// 计数,模型那一项只说配没配,所以不需要工作区 admin 那道门。
+pub async fn readiness(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<utopia_core::models::Readiness>> {
+ kb_with_role(&state, &user, id, Role::Viewer).await?;
+ Ok(Json(utopia_store::kbs::readiness(&state.pool, id).await?))
+}
+
// ---------------------------------------------------------------------------
// KB 成员矩阵(库自己的 Settings → Members)
// ---------------------------------------------------------------------------
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 8197fa6f..6e0702c8 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -85,6 +85,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}",
patch(kbs::update).get(kbs::get_one).delete(kbs::delete),
)
+ // 四个页面的空状态共用的一步判断(#313)
+ .route("/kbs/{id}/readiness", get(kbs::readiness))
.route("/kbs/{id}/members", get(kbs::members))
.route("/kbs/{id}/audit", get(kbs::audit_log))
// 失败任务回队列(#216):库内给 Editor,全局给管理员
diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs
index fe8939af..a89b7179 100644
--- a/crates/utopia-store/src/kbs.rs
+++ b/crates/utopia-store/src/kbs.rs
@@ -1,5 +1,5 @@
use sqlx::PgPool;
-use utopia_core::models::KnowledgeBase;
+use utopia_core::models::{KnowledgeBase, Readiness};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -137,6 +137,34 @@ pub async fn update(
.ok_or(AppError::NotFound)
}
+pub async fn readiness(pool: &PgPool, kb_id: Uuid) -> AppResult<Readiness> {
+ // 一次查询拿全,四个页面各发一次请求也只是一次点查
+ let r: Readiness = sqlx::query_as(
+ "SELECT
+ EXISTS (
+ SELECT 1 FROM llm_settings s
+ JOIN knowledge_bases k ON k.workspace_id = s.workspace_id
+ WHERE k.id = $1 AND coalesce(s.chat_model, '') <> ''
+ ) AS has_chat_model,
+ (SELECT count(*) FROM documents
+ WHERE kb_id = $1 AND deleted_at IS NULL) AS documents,
+ -- 两条轴各有各的进行时:内容还没进库(status),或图还没抽完(graph_status)
+ (SELECT count(*) FROM documents
+ WHERE kb_id = $1 AND deleted_at IS NULL
+ AND (status IN ('pending', 'parsing', 'indexing', 'embedding')
+ OR graph_status IN ('queued', 'extracting'))) AS processing,
+ (SELECT count(*) FROM documents
+ WHERE kb_id = $1 AND deleted_at IS NULL
+ AND (status = 'failed' OR graph_status = 'failed')) AS failed,
+ (SELECT count(*) FROM entities
+ WHERE kb_id = $1 AND merged_into IS NULL) AS entities",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(r)
+}
+
pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
let current = get(pool, id).await?;
if current.is_default {
diff --git a/web/src/api.ts b/web/src/api.ts
index 72f0a889..e27de8c9 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -220,6 +220,15 @@ export interface SearchResult {
filename: string;
}
+/** 这个库走到哪一步了(#313)。凭据不出库:模型那项只说配没配 */
+export interface Readiness {
+ has_chat_model: boolean;
+ documents: number;
+ processing: number;
+ failed: number;
+ entities: number;
+}
+
export interface LlmSettingsView {
chat_base_url?: string | null;
chat_model?: string | null;
@@ -1464,6 +1473,10 @@ export const api = {
body: JSON.stringify(body),
}),
+ /** 这个库走到哪一步了(#313):四个页面的空状态共用。只回布尔与计数 */
+ readiness: (kbId: string) =>
+ request<Readiness>(`/api/v1/kbs/${kbId}/readiness`),
+
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/en.ts b/web/src/i18n/en.ts
index 5f6befd0..b2c37820 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -258,6 +258,25 @@ export const en = {
reportIssue: "Report an issue",
refresh: "Refresh",
},
+ /* 空状态的共用文案(#313)。
+ **状态一句话,动作在按钮上,不解释原理。** 从前这里是一整段:
+ 「图是空的。先去 管理 → 模型 配置对话模型,然后在文库上传文档——
+ 实体和关系会自动抽取。」——一句话里塞了状态、两个动作和一段原理,
+ 而盯着空页面的人要的是下一步点哪儿。原理属于文档,不属于空状态 */
+ steps: {
+ noModel: "No chat model yet.",
+ /* 配模型要工作区管理员,别人只能去找人——所以话不同,按钮也不给 */
+ noModelAsk: "No chat model yet. Ask an administrator.",
+ configureModel: "Configure model",
+ noDocs: "No documents yet.",
+ upload: "Upload a document",
+ processing: (n: number) => `Reading ${n} document${n === 1 ? "" : "s"}…`,
+ viewProgress: "View progress",
+ someFailed: (n: number) => `${n} document${n === 1 ? "" : "s"} failed.`,
+ /* 文档齐了、抽取也跑完了,图还是空的:不是「还没开始」,是没抽出东西 */
+ nothingExtracted: "Nothing extracted yet.",
+ openLibrary: "Open Library",
+ },
login: {
signIn: "Sign in",
signUp: "Sign up",
@@ -706,11 +725,6 @@ export const en = {
// 一个实体也抽不出来。先配模型,再传文档
// 管理页在头像菜单里叫 Administration,提示语得叫同一个名字(#267)。
// 能配模型的人和不能配的人看到的不是同一句:后者只能去找管理员
- emptyBody:
- "The graph is empty. Ask an administrator to configure a chat model, then upload documents in the Library — entities and relations are extracted automatically.",
- emptyBodyAdmin:
- "The graph is empty. Configure a chat model under Administration → Models first, then upload documents in the Library — entities and relations are extracted automatically.",
- emptyOpenModels: "Open Administration → Models",
facts: "facts",
noFacts: "No facts for this entity yet",
confidence: "confidence",
@@ -1246,8 +1260,10 @@ export const en = {
/* ---- Schema diagram ---- */
schemaDiagram: "Schema diagram",
schemaSearchPlaceholder: "Search schema…",
- schemaEmpty:
- "No schema to display yet. Add a class on the left, or import an OWL/RDFS/Turtle file to get started.",
+ /* 从前这句把「先加个类或导入 OWL 文件」说成了开始的前提,而本体本来就
+ 从语料里长(0003,默认开)——那句话正是 #313 说的劝退点。现在只说状态,
+ 动作留给左栏本来就有的 New class 与 Import */
+ schemaEmpty: "No classes yet. Extraction adds them as documents arrive.",
schemaFitView: "Fit view",
schemaZoomIn: "Zoom in",
schemaZoomOut: "Zoom out",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 5cf8098e..6c8f211b 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -232,6 +232,19 @@ export const zh: Strings = {
reportIssue: "反馈问题",
refresh: "刷新",
},
+ /* 空状态的共用文案(#313):状态一句话,动作在按钮上,不解释原理 */
+ steps: {
+ noModel: "还没配置对话模型。",
+ noModelAsk: "还没配置对话模型,请联系管理员。",
+ configureModel: "配置模型",
+ noDocs: "还没有文档。",
+ upload: "上传文档",
+ processing: (n: number) => `正在读取 ${n} 份文档…`,
+ viewProgress: "查看进度",
+ someFailed: (n: number) => `${n} 份文档处理失败。`,
+ nothingExtracted: "还没抽取出内容。",
+ openLibrary: "打开文库",
+ },
login: {
signIn: "登录",
signUp: "注册",
@@ -649,11 +662,6 @@ export const zh: Strings = {
searchEntity: "搜索实体…",
searchInSubgraph: "在子图中搜索…",
backToOverview: "← 全图",
- emptyBody:
- "图谱是空的。请管理员先配置对话模型,然后在「文库」中上传文档——实体与关系会被自动抽取。",
- emptyBodyAdmin:
- "图谱是空的。请先在「管理 → 模型」里配置对话模型,然后在「文库」中上传文档——实体与关系会被自动抽取。",
- emptyOpenModels: "打开「管理 → 模型」",
facts: "条事实",
noFacts: "这个实体还没有事实",
confidence: "置信度",
@@ -1104,7 +1112,7 @@ export const zh: Strings = {
/* ---- 模式图 ---- */
schemaDiagram: "模式图",
schemaSearchPlaceholder: "搜索模式…",
- schemaEmpty: "还没有可显示的模式。在左侧新建一个类,或导入一个 OWL/RDFS/Turtle 文件开始。",
+ schemaEmpty: "还没有类。文档进来时会自动补上。",
schemaFitView: "归位",
schemaZoomIn: "放大",
schemaZoomOut: "缩小",
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
index 5aa7901c..443603c2 100644
--- a/web/src/pages/Chat.tsx
+++ b/web/src/pages/Chat.tsx
@@ -25,6 +25,7 @@ import {
} from "lucide-react";
import { ThinkingOrb, type OrbState } from "thinking-orbs";
import {
+ api,
conversationsApi,
reattachChat,
streamChat,
@@ -37,6 +38,7 @@ import { useKb, useKbId } from "../kb";
import { DangerConfirm, RAIL_CLS } from "../ui";
import { liveAnswer, type LiveHandle, type Turn } from "../liveAnswer";
import { NodCard } from "./PendingFacts";
+import { NextStep, nextStep, useReadiness } from "./NextStep";
/* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,
而它必须活得比这个组件长(见那个文件顶上的说明) */
@@ -48,6 +50,18 @@ const DRAFT_KEY = "chat:draft";
export function Chat() {
const kbId = useKbId();
const { kb, kbs, setKb } = useKb();
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ /* **只拦模型这一档。** 空的知识库照样能聊——挂载的数据库查得了,记忆也读得到;
+ 没有对话模型才是真的一句都问不出来,而问候语从前照常显示,用户敲完第一句
+ 才撞墙(#313) */
+ const readiness = useReadiness(kbId);
+ const modelStep = readiness.data?.has_chat_model
+ ? null
+ : nextStep(readiness.data, {
+ kbId,
+ isAdmin: !!me.data?.is_admin,
+ canUpload: kb?.my_role !== "viewer",
+ });
const queryClient = useQueryClient();
const navigate = useNavigate();
// 会话即路由:/chat/$conversationId,URL 是当前会话的唯一事实来源(刷新/回退天然可用)
@@ -574,6 +588,11 @@ export function Chat() {
>
{S.ask.greeting}
</h1>
+ {modelStep && (
+ <div className="mb-6 grid place-items-center">
+ <NextStep {...modelStep} />
+ </div>
+ )}
{composerCard}
</div>
</div>
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index e64b0552..4361c089 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -34,6 +34,7 @@ import {
TRANSPARENT,
} from "./graphVisuals";
import { EntityHistory } from "./EntityHistory";
+import { NextStep, nextStep, useReadiness } from "./NextStep";
import {
ArrowLeft,
ArrowRight,
@@ -357,6 +358,13 @@ export function Graph() {
// 空状态给谁看:管理员能自己去配模型,其他人只能去找管理员。与 Shell 共用同一份缓存
const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ // 空状态说哪一句,取决于这个库走到哪一步了(#313)
+ const readiness = useReadiness(kbId);
+ const step = nextStep(readiness.data, {
+ kbId,
+ isAdmin: !!me.data?.is_admin,
+ canUpload: kb?.my_role !== "viewer",
+ });
const data = useQuery({
queryKey: ["graph", kb?.id, focusEntity, nodeBudget],
queryFn: () =>
@@ -1678,18 +1686,20 @@ export function Graph() {
<div className="absolute inset-0 grid place-items-center pb-20 pointer-events-none">
{/* 不放标题方块:页面本身就是图谱页,tab 条上也写着,
第三遍写"图谱"两个字不带任何信息。空状态该说的是下一步做什么——
- 而"下一步"因人而异:管理员能直接去配模型,别人只能去找管理员(#267) */}
- <div className="text-center text-sm text-neutral-500 max-w-xs pointer-events-auto">
- {me.data?.is_admin ? S.graph.emptyBodyAdmin : S.graph.emptyBody}
- {me.data?.is_admin && (
- <Link
- to="/admin"
- search={{ tab: "models" }}
- className="block mt-3 text-neutral-300 hover:text-white underline underline-offset-4"
- >
- {S.graph.emptyOpenModels}
- </Link>
- )}
+ 而"下一步"因人而异:管理员能直接去配模型,别人只能去找管理员(#267)。
+ 这一步现在由 readiness 统一判定(#313):文档正在抽取时不该还让人去配模型 */}
+ <div className="pointer-events-auto">
+ <NextStep
+ {...(step ?? {
+ // 模型有了、文档也进来了、抽取跑完了,图还是空的
+ line: S.steps.nothingExtracted,
+ action: {
+ label: S.steps.openLibrary,
+ to: "/kb/$kbId/library",
+ params: { kbId },
+ },
+ })}
+ />
</div>
</div>
)}
diff --git a/web/src/pages/NextStep.tsx b/web/src/pages/NextStep.tsx
new file mode 100644
index 00000000..1f4de412
--- /dev/null
+++ b/web/src/pages/NextStep.tsx
@@ -0,0 +1,103 @@
+/* 空状态里的「下一步」(#313)。
+
+ 四个页面此前各自假设「已经就绪」:图谱页无条件让人去配模型,哪怕文档正在
+ 抽取;对话页照常显示问候语,哪怕模型根本没配——用户问出第一句才撞墙。
+ 这里把「这个库走到哪一步」收成一个判断,四个页面共用。
+
+ **写法:状态一句话,动作在按钮上。** 不解释原理——原理属于文档,而盯着
+ 空页面的人要的是下一步点哪儿。 */
+import { useQuery } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
+import { api, type Readiness } from "../api";
+import { S } from "../i18n";
+
+export function useReadiness(kbId: string | undefined) {
+ return useQuery({
+ queryKey: ["readiness", kbId],
+ queryFn: () => api.readiness(kbId!),
+ enabled: !!kbId,
+ // 上传、抽取都会改它,但没必要盯着轮询:页面切回来时重取就够
+ staleTime: 10_000,
+ });
+}
+
+/** 一句话 + 至多一个动作。动作缺省时只剩那句话(权限不够的人不该看到按钮)。 */
+export function NextStep({
+ line,
+ action,
+}: {
+ line: string;
+ action?: { label: string; to: string; params?: Record<string, string>; search?: Record<string, unknown> };
+}) {
+ return (
+ <div className="text-center text-sm text-neutral-500 max-w-xs">
+ {line}
+ {action && (
+ <Link
+ // 路由表是字面量联合类型,这里的目标是运行时算出来的
+ to={action.to as never}
+ params={action.params as never}
+ search={(action.search ?? {}) as never}
+ className="block mt-3 text-neutral-300 hover:text-white underline underline-offset-4"
+ >
+ {action.label}
+ </Link>
+ )}
+ </div>
+ );
+}
+
+/** 这个库的下一步是什么。`canUpload` 交给调用方——它知道自己的角色。 */
+export function nextStep(
+ r: Readiness | undefined,
+ opts: { kbId: string; isAdmin: boolean; canUpload: boolean },
+): { line: string; action?: { label: string; to: string; params?: Record<string, string>; search?: Record<string, unknown> } } | null {
+ if (!r) return null;
+ // 顺序即优先级:没有模型,上传了也抽不出东西;没有文档,谈不上处理中
+ if (!r.has_chat_model) {
+ return opts.isAdmin
+ ? {
+ line: S.steps.noModel,
+ action: {
+ label: S.steps.configureModel,
+ to: "/admin",
+ search: { tab: "models" },
+ },
+ }
+ : { line: S.steps.noModelAsk };
+ }
+ if (r.documents === 0) {
+ return opts.canUpload
+ ? {
+ line: S.steps.noDocs,
+ action: {
+ label: S.steps.upload,
+ to: "/kb/$kbId/library",
+ params: { kbId: opts.kbId },
+ },
+ }
+ : { line: S.steps.noDocs };
+ }
+ if (r.processing > 0) {
+ return {
+ line: S.steps.processing(r.processing),
+ action: {
+ label: S.steps.viewProgress,
+ to: "/kb/$kbId/library",
+ params: { kbId: opts.kbId },
+ },
+ };
+ }
+ // 处理完了却一个失败都没修,值得说一句——否则「什么都没抽出来」会被当成产品坏了
+ if (r.failed > 0 && r.entities === 0) {
+ return {
+ line: S.steps.someFailed(r.failed),
+ action: {
+ label: S.steps.openLibrary,
+ to: "/kb/$kbId/library",
+ params: { kbId: opts.kbId },
+ },
+ };
+ }
+ return null;
+}
diff --git a/web/src/pages/Search.tsx b/web/src/pages/Search.tsx
index 8e3ee123..6285f280 100644
--- a/web/src/pages/Search.tsx
+++ b/web/src/pages/Search.tsx
@@ -5,6 +5,7 @@ import { api } from "../api";
import { S } from "../i18n";
import { useKb, useKbId } from "../kb";
import { Pager, pageSlice } from "../ui";
+import { NextStep, nextStep, useReadiness } from "./NextStep";
const RESULT_PAGE = 10;
@@ -22,6 +23,15 @@ export function Search() {
// 新查询换一批结果,从第一页看起
useEffect(() => setPage(0), [query]);
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ // 搜之前就该说清楚库里有没有东西可搜(#313)
+ const readiness = useReadiness(kbId);
+ const step = nextStep(readiness.data, {
+ kbId,
+ isAdmin: !!me.data?.is_admin,
+ canUpload: kb?.my_role !== "viewer",
+ });
+
const results = useQuery({
queryKey: ["search", kb?.id, query],
queryFn: () => api.search(kb!.id, query!),
@@ -58,6 +68,14 @@ export function Search() {
</button>
</div>
+ {/* 一次都还没搜、而库里本来就没东西:与其等他敲一个词再回"没有结果",
+ 不如现在就说下一步(#313) */}
+ {!query && step && (
+ <div className="py-10 grid place-items-center">
+ <NextStep {...step} />
+ </div>
+ )}
+
{results.isFetching && <p className="text-sm text-neutral-500">{S.search.searching}</p>}
{results.isError && (
<p className="text-sm text-rose-400">{(results.error as Error).message}</p>