Skip to content

World's first open-source enterprise world model.

Users, knowledge bases and data sources (#469)

WaylandYang0d86287c13a7
diff --git a/crates/utopia-server/src/api/datasource_routes.rs b/crates/utopia-server/src/api/datasource_routes.rs
index f1434cc1..3409b417 100644
--- a/crates/utopia-server/src/api/datasource_routes.rs
+++ b/crates/utopia-server/src/api/datasource_routes.rs
@@ -96,6 +96,42 @@ pub async fn delete(
Ok(Json(json!({ "ok": true })))
}
+#[derive(Deserialize)]
+pub struct TestConnBody {
+ pub conn_string: String,
+}
+
+/// 存之前先试一次。**这一步不落库**:登记表单里那个「测试连接」按的是它。
+///
+/// 从前只能先存下来再测,测不通还得回头把这条删掉;而 [`test`] 只回 `ok: false`,
+/// 连为什么不通都不说。这里把引擎的报错原样带回去——密码错、库名拼错、
+/// 端口不通,是三件不同的事,人得知道是哪一件。
+pub async fn test_conn(
+ AuthUser(user): AuthUser,
+ Json(body): Json<TestConnBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let engine = crate::query_engine::engine_from_conn(&body.conn_string).ok_or_else(|| {
+ AppError::invalid(
+ "unsupported_conn_scheme",
+ format!(
+ "Connection string must start with one of: postgres://, mysql://, trino://, databricks://, snowflake:// (engines: {})",
+ crate::query_engine::ENGINES.join(", ")
+ ),
+ )
+ })?;
+ // 连接串的形状(缺令牌、缺 warehouse……)与连得上连不上分开报:前者是写错了,
+ // 后者是环境问题,两句话对人的下一步动作不一样
+ let eng = crate::query_engine::engine_for(engine, &body.conn_string)
+ .map_err(|e| AppError::invalid("bad_conn_string", e.to_string()))?;
+ match eng.test().await {
+ Ok(()) => Ok(Json(json!({ "ok": true, "engine": engine }))),
+ Err(e) => Ok(Json(
+ json!({ "ok": false, "engine": engine, "error": e.to_string() }),
+ )),
+ }
+}
+
pub async fn test(
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 76d93474..fd762c37 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -122,6 +122,11 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/admin/data-sources/{id}",
axum::routing::delete(datasource_routes::delete),
)
+ // 静态段排在 `{id}` 前面:存之前先试一次连接,不落库
+ .route(
+ "/admin/data-sources/test",
+ post(datasource_routes::test_conn),
+ )
.route(
"/admin/data-sources/{id}/test",
post(datasource_routes::test),
diff --git a/web/src/api.ts b/web/src/api.ts
index 479128d4..01f00a11 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1283,6 +1283,12 @@ export const api = {
revokeToken: (tokenId: string) =>
request<{ ok: boolean }>(`/api/v1/me/tokens/${tokenId}`, { method: "DELETE" }),
workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
+ /** 这个工作区,以及**我在里面是什么角色**。建库要 Admin+(见 api/kbs.rs
+ * 的 create),而 `GET /workspaces` 那份列表不带角色 */
+ workspaceRole: (workspaceId: string) =>
+ request<{ workspace: Workspace; role: string }>(
+ `/api/v1/workspaces/${workspaceId}`,
+ ),
kbs: (workspaceId: string) =>
request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
@@ -1431,6 +1437,13 @@ export const api = {
request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
method: "DELETE",
}),
+ /** 存之前先试一次:**不落库**。回来的是 ok,连不上时还有一句原因——
+ * 密码错、库名拼错、端口不通是三件不同的事 */
+ adminTestConnString: (conn_string: string) =>
+ request<{ ok: boolean; engine?: string; error?: string }>(
+ "/api/v1/admin/data-sources/test",
+ { method: "POST", body: JSON.stringify({ conn_string }) },
+ ),
adminTestDataSource: (id: string) =>
request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
method: "POST",
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 28bc93dd..c99b4bde 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -113,6 +113,7 @@ export const en = {
language: "Language",
kbsNav: "Knowledge bases",
kbsTitle: "Knowledge bases",
+ kbsFilter: "Filter by name…",
kbOpen: "Open",
kbRestricted: "Restricted",
kbStats: (docs: number, members: number) =>
@@ -997,6 +998,27 @@ export const en = {
"databricks://:TOKEN@host/sql/1.0/warehouses/ID?catalog=main\n" +
"snowflake://:[email protected]/DB/SCHEMA?warehouse=WH",
add: "Add data source",
+ newTitle: "New data source",
+ engine: "Engine",
+ engineRaw: "Connection string",
+ optional: "(optional)",
+ testConn: "Test connection",
+ testing: "Testing…",
+ colConn: "Connection",
+ colStatus: "Status",
+ grantsNoneShort: "Not granted",
+ grantsCount: (n: number) => (n === 1 ? "1 workspace" : `${n} workspaces`),
+ fHost: "Host",
+ fPort: "Port",
+ fDatabase: "Database",
+ fUser: "User",
+ fPassword: "Password",
+ fCatalog: "Catalog",
+ fSchema: "Schema",
+ fToken: "Token",
+ fWarehouse: "Warehouse",
+ fWarehouseId: "Warehouse ID",
+ fAccount: "Account host",
test: "Test",
testOk: "Connected",
testFail: "Failed",
@@ -1005,7 +1027,7 @@ export const en = {
empty: "No data sources registered yet. Register one below.",
grants: "Available to",
grantsHint:
- "Which workspaces may use this source. **Once granted, KB admins in those workspaces choose whether to mount it** — " +
+ "Which workspaces may use this source. Once granted, KB admins in those workspaces choose whether to mount it — " +
"this controls what they can reach, not what they have mounted.",
grantsNone:
"Not granted to any workspace — no knowledge base can mount it.",
@@ -1024,8 +1046,8 @@ export const en = {
defaultChip: "Default",
newKb: "New knowledge base",
packsLabel: "Bundled ontologies",
- packsHint:
- "Optional. Packs declare direction, so subject and object cannot come out reversed. More can be imported later.",
+ packsHint: "Optional, and more can be imported later.",
+ packsPick: "Search packs…",
packsNone: "None — start from the ten seed relations",
packsCount: (c: number, p: number) => `${c} classes · ${p} properties`,
name: "Name",
@@ -1908,8 +1930,16 @@ export const en = {
deactivatedHint:
"They cannot sign in and do not appear in any member list. What they did is still attributed to them — that is why the account is kept rather than deleted.",
reactivate: "Restore",
+ roleLabel: "Role",
+ filterAll: "All users",
+ filterAllRoles: "All roles",
+ statusLabel: "Status",
+ filterActive: "Active",
+ filterDeactivated: "Deactivated",
deactivateConfirm: (name: string) =>
`Deactivate ${name}? They lose access everywhere. Their past decisions stay on record.`,
+ addExisting: "Add existing user",
+ userLabel: "User",
pickUser: "Select a user to add…",
add: "Add",
roles: {
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index f48f600e..78f1aca4 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -102,6 +102,7 @@ export const zh: Strings = {
language: "语言",
kbsNav: "知识库",
kbsTitle: "知识库",
+ kbsFilter: "按名字筛选…",
kbOpen: "公开",
kbRestricted: "受限",
kbStats: (docs: number, members: number) =>
@@ -890,6 +891,27 @@ export const zh: Strings = {
"databricks://:TOKEN@host/sql/1.0/warehouses/ID?catalog=main\n" +
"snowflake://:[email protected]/DB/SCHEMA?warehouse=WH",
add: "添加数据源",
+ newTitle: "登记数据源",
+ engine: "引擎",
+ engineRaw: "连接串",
+ optional: "(可不填)",
+ testConn: "测试连接",
+ testing: "连接中…",
+ colConn: "连接",
+ colStatus: "状态",
+ grantsNoneShort: "未授权",
+ grantsCount: (n: number) => `${n} 个工作区`,
+ fHost: "主机",
+ fPort: "端口",
+ fDatabase: "库",
+ fUser: "用户",
+ fPassword: "密码",
+ fCatalog: "Catalog",
+ fSchema: "Schema",
+ fToken: "令牌",
+ fWarehouse: "Warehouse",
+ fWarehouseId: "Warehouse ID",
+ fAccount: "账号主机",
test: "测试",
testOk: "已连接",
testFail: "失败",
@@ -898,7 +920,7 @@ export const zh: Strings = {
empty: "还没有注册数据源。在下面注册一个。",
grants: "可用于",
grantsHint:
- "授权哪些工作区可以用这个源。**授权之后,那些工作区的知识库管理员自己挑挂不挂**——" +
+ "授权哪些工作区可以用这个源。授权之后,那些工作区的知识库管理员自己挑挂不挂——" +
"这里管的是「能不能拿到」,不是「挂没挂」。",
grantsNone: "还没授权给任何工作区——现在没有知识库挂得上它。",
grantAdd: "授权工作区…",
@@ -913,8 +935,8 @@ export const zh: Strings = {
defaultChip: "默认",
newKb: "新建知识库",
packsLabel: "预置本体",
- packsHint:
- "可不选。包里的谓语带方向声明,主宾颠倒进不来。之后还能再导入。",
+ packsHint: "可不选,之后还能再导入。",
+ packsPick: "搜索本体包…",
packsNone: "不选 —— 从十个种子关系起步",
packsCount: (c: number, p: number) => `${c} 个类 · ${p} 个属性`,
name: "名称",
@@ -1672,8 +1694,16 @@ export const zh: Strings = {
deactivatedHint:
"他们登不进来,也不出现在任何成员列表里。做过的事仍然算在他们名下——账号被保留而不是删除,正是为了这个。",
reactivate: "恢复",
+ roleLabel: "角色",
+ filterAll: "全部用户",
+ filterAllRoles: "全部角色",
+ statusLabel: "状态",
+ filterActive: "在用",
+ filterDeactivated: "已停用",
deactivateConfirm: (name: string) =>
`停用 ${name}?他将无法再登录任何地方,但过往的决定仍然留痕。`,
+ addExisting: "添加已有用户",
+ userLabel: "用户",
pickUser: "选择要添加的用户…",
add: "添加",
roles: {
diff --git a/web/src/pages/Account.tsx b/web/src/pages/Account.tsx
index cf06df73..95da302d 100644
--- a/web/src/pages/Account.tsx
+++ b/web/src/pages/Account.tsx
@@ -53,68 +53,71 @@ export function Account() {
return (
<div className="px-8 py-6">
- <PageHeader title={S.account.profileTitle} />
+ {/* 与管理页同一副身材:内容居中限宽,行长不随窗口拉长 */}
+ <div className="mx-auto w-full max-w-4xl">
+ <PageHeader title={S.account.profileTitle} />
- <div className="glass rounded-panel p-6 mb-4">
- <div className="max-w-xl">
- <div className="flex items-center gap-4 mb-6">
- <Avatar name={me.data.display_name} size={56} />
- <p className="text-small text-ink-2">{S.account.avatarHint}</p>
+ <div className="glass rounded-panel p-6 mb-4">
+ <div className="max-w-xl">
+ <div className="flex items-center gap-4 mb-6">
+ <Avatar name={me.data.display_name} size={56} />
+ <p className="text-small text-ink-2">{S.account.avatarHint}</p>
+ </div>
+
+ {field(
+ S.account.displayName,
+ <div className="flex gap-2">
+ <Input className="flex-1"
+ value={displayName}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Button variant="primary" size="sm"
+ disabled={!nameDirty || saveName.isPending}
+ onClick={() => saveName.mutate(displayName.trim())}
+ >
+ {S.account.save}
+ </Button>
+ </div>,
+ )}
+
+ {field(
+ S.account.email,
+ <div className="text-body text-ink-2 px-1">{me.data.email}</div>,
+ )}
</div>
+ </div>
- {field(
- S.account.displayName,
- <div className="flex gap-2">
- <Input className="flex-1"
- value={displayName}
- onChange={(e) => setName(e.target.value)}
- />
+ <div className="glass rounded-panel p-6">
+ <div className="max-w-xl">
+ <h2 className="text-body font-medium text-ink mb-4">
+ {S.account.passwordTitle}
+ </h2>
+ {field(
+ S.account.currentPassword,
+ <Input className="w-full"
+ type="password"
+ autoComplete="current-password"
+ value={curPw}
+ onChange={(e) => setCurPw(e.target.value)}
+ />,
+ )}
+ {field(
+ S.account.newPassword,
+ <Input className="w-full"
+ type="password"
+ autoComplete="new-password"
+ value={newPw}
+ onChange={(e) => setNewPw(e.target.value)}
+ />,
+ )}
+ <div className="flex justify-end">
<Button variant="primary" size="sm"
- disabled={!nameDirty || saveName.isPending}
- onClick={() => saveName.mutate(displayName.trim())}
+ disabled={!curPw || newPw.length < 8 || changePw.isPending}
+ onClick={() => changePw.mutate()}
>
- {S.account.save}
+ {S.account.changePassword}
</Button>
- </div>,
- )}
-
- {field(
- S.account.email,
- <div className="text-body text-ink-2 px-1">{me.data.email}</div>,
- )}
- </div>
- </div>
-
- <div className="glass rounded-panel p-6">
- <div className="max-w-xl">
- <h2 className="text-body font-medium text-ink mb-4">
- {S.account.passwordTitle}
- </h2>
- {field(
- S.account.currentPassword,
- <Input className="w-full"
- type="password"
- autoComplete="current-password"
- value={curPw}
- onChange={(e) => setCurPw(e.target.value)}
- />,
- )}
- {field(
- S.account.newPassword,
- <Input className="w-full"
- type="password"
- autoComplete="new-password"
- value={newPw}
- onChange={(e) => setNewPw(e.target.value)}
- />,
- )}
- <div className="flex justify-end">
- <Button variant="primary" size="sm"
- disabled={!curPw || newPw.length < 8 || changePw.isPending}
- onClick={() => changePw.mutate()}
- >
- {S.account.changePassword}
- </Button>
+ </div>
</div>
</div>
</div>
diff --git a/web/src/pages/AccountShell.tsx b/web/src/pages/AccountShell.tsx
index 4d404535..48c0b18f 100644
--- a/web/src/pages/AccountShell.tsx
+++ b/web/src/pages/AccountShell.tsx
@@ -16,19 +16,9 @@ import {
rowClass,
SectionMark,
} from "../ui";
-
-/** 管理页的五节。**它们是左栏的第二层,不是正文顶上的一条 tab 带**——
- 与上面四项是同一种东西(去哪儿),只是矮一级;地址里是 `?tab=`,
- 刷新、回退、分享链接都落回同一节 */
-const ADMIN_TABS = [
- ["models", () => S.settings.tabModels],
- ["members", () => S.settings.tabMembers],
- ["kbs", () => S.settings.tabKbs],
- ["datasources", () => S.settings.datasources.tab],
- ["deployment", () => S.settings.tabDeployment],
-] as const;
import { ServerDown } from "./ServerDown";
import { HeaderActions } from "./HeaderActions";
+import { ADMIN_TABS } from "./Settings";
export function AccountShell() {
const navigate = useNavigate();
@@ -105,7 +95,7 @@ export function AccountShell() {
{S.account.administration}
</Link>
{onAdmin &&
- ADMIN_TABS.map(([key, label]) => (
+ ADMIN_TABS.map(({ key, label }) => (
<Link
key={key}
to="/admin"
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 007b8fa9..37d8c0a4 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -18,6 +18,10 @@ import EdgeCurveProgram from "@sigma/edge-curve";
import { NodeSquareShellProgram } from "./squareShellProgram";
import {
drawHoverCard,
+ CANVAS_FONT,
+ CANVAS_LABEL_SIZE,
+ CANVAS_TEXT,
+ CANVAS_TEXT_2,
drawPillLabel,
drawWorldGrid,
hexToRgb,
@@ -704,8 +708,10 @@ export function Graph() {
);
for (const { edge: e, curvature, alsoLabels } of placed.edges) {
g.addEdgeWithKey(e.id, e.source, e.target, {
- // 争议的边标签前置 ⚠:颜色之外再给一个不靠色觉的记号
- label: (e.contested ? "⚠ " : "") + (e.label?.toUpperCase() ?? ""),
+ /* 争议的边标签前置 ⚠:颜色之外再给一个不靠色觉的记号。
+ **谓语照本体里写的样子显示**,不再大写——界面上没有一处大写拉字距,
+ 而本体页列的就是「part of」这个原样 */
+ label: (e.contested ? "⚠ " : "") + (e.label ?? ""),
size: e.blocked ? 0.7 : 1,
color: e.blocked
? EDGE_GHOST
@@ -851,17 +857,19 @@ export function Graph() {
// 边的悬停事件默认是关的。开它是为了 `enterEdge`:并进去的那些说法
// 要有地方看得见(见 edgeReducer)
enableEdgeEvents: true,
- labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',
- labelSize: 11,
- labelColor: { color: "#e5e5e5" },
+ labelFont: CANVAS_FONT,
+ labelSize: CANVAS_LABEL_SIZE,
+ labelColor: { color: CANVAS_TEXT },
labelRenderedSizeThreshold: 6,
labelDensity: 0.7,
labelGridCellSize: 140,
minCameraRatio: 0.04,
maxCameraRatio: 8,
- edgeLabelSize: 9,
- edgeLabelColor: { color: "#a1a1a1" },
- edgeLabelFont: '"Geist", "Inter", sans-serif',
+ /* 边的字与节点同一档(fine)、同一个次要色。从前是 9px/#a1a1a1——
+ 9 比界面里最小的字还小一半,而 #a1a1a1 是上一版的 ink-2 */
+ edgeLabelSize: CANVAS_LABEL_SIZE,
+ edgeLabelColor: { color: CANVAS_TEXT_2 },
+ edgeLabelFont: CANVAS_FONT,
defaultDrawNodeLabel: drawPillLabel,
defaultDrawNodeHover: drawHoverCard,
nodeReducer: (node, attrs) => {
@@ -993,9 +1001,7 @@ export function Graph() {
selectedRef.current === s ||
selectedRef.current === t;
if (focused) {
- res.label = `${attrs.label} ⁻¹ ${also
- .map((l) => l.toUpperCase())
- .join(" / ")}`;
+ res.label = `${attrs.label} ⁻¹ ${also.join(" / ")}`;
}
}
const sk = g.getNodeAttribute(s, "typeKey") as string;
diff --git a/web/src/pages/KbSwitcher.tsx b/web/src/pages/KbSwitcher.tsx
index 42cfebbd..f4c62e48 100644
--- a/web/src/pages/KbSwitcher.tsx
+++ b/web/src/pages/KbSwitcher.tsx
@@ -32,6 +32,11 @@ export function KbSwitcher({
// 建库要系统管理员或工作区 Admin+(见 api/kbs.rs create):没这个权限的人
// 看不到入口,省得点进去吃一个 403
const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ const wsRole = useQuery({
+ queryKey: ["workspaceRole", kb?.workspace_id],
+ queryFn: () => api.workspaceRole(kb!.workspace_id),
+ enabled: !!kb?.workspace_id,
+ });
// 关掉就把查找词丢掉:下次打开是从头挑,不是接着上次的筛选结果
const dismiss = () => {
@@ -115,16 +120,18 @@ export function KbSwitcher({
<p className="px-4 py-3 text-body text-ink-2">{S.nav.noKbMatch}</p>
)}
</div>
- {/* 新建钉在最下面,不混在列里:它不是一个库。去的是建库那一页,
- 带上 create——落地就是表单,不用在设置页里再找一次按钮 */}
- {me.data?.is_admin && (
+ {/* 新建钉在最下面,不混在列里:它不是一个库。去的是「我的知识库」,
+ 带上 create——落地就是表单,不用到了那一页再找一次按钮 */}
+ {(me.data?.is_admin ||
+ wsRole.data?.role === "admin" ||
+ wsRole.data?.role === "owner") && (
<Row
density="menu"
className="gap-3 border-t border-line px-4 py-3 text-body"
icon={<Plus size={14} />}
onClick={() => {
dismiss();
- navigate({ to: "/admin", search: { tab: "kbs", create: true } });
+ navigate({ to: "/account/kbs", search: { create: true } });
}}
>
{S.settings.kbs.newKb}
diff --git a/web/src/pages/Members.tsx b/web/src/pages/Members.tsx
index eb1bbcd0..e51e8ab2 100644
--- a/web/src/pages/Members.tsx
+++ b/web/src/pages/Members.tsx
@@ -1,31 +1,56 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Plus, Search } from "lucide-react";
import { api } from "../api";
import { S } from "../i18n";
-import { toast } from "../toast";
import {
Button,
Chip,
DangerConfirm,
+ Dialog,
Dropdown,
+ Field,
Input,
LinkButton,
Pager,
pageSlice,
SearchSelect,
- SettingsCard,
+ Table,
+ TBody,
+ Td,
+ Th,
+ THead,
+ Tr,
} from "../ui";
const ROLES = ["owner", "admin", "editor", "viewer"] as const;
const ROLE_OPTIONS = ROLES.map((r) => ({ value: r, label: S.members.roles[r] }));
const MEMBER_PAGE = 10;
+/** 名单里的一行。停用的账号也是一行——它没有工作区角色,别的都一样 */
+type Person = {
+ user_id: string;
+ display_name: string;
+ email: string;
+ role: string;
+ is_admin: boolean;
+ deactivated: boolean;
+};
+
export function Members({ workspaceId }: { workspaceId: string }) {
const queryClient = useQueryClient();
const [addUserId, setAddUserId] = useState("");
const [addRole, setAddRole] = useState("viewer");
const [memberPage, setMemberPage] = useState(0);
const [filter, setFilter] = useState("");
+ // 看在用的、看停用的,还是都看。缺省只看在用的:那是这一页平时的问题
+ const [status, setStatus] = useState<"all" | "active" | "deactivated">("active");
+ const [creating, setCreating] = useState(false);
+ const [adding, setAdding] = useState(false);
+ // 角色平时是一行字,点了才变成下拉——同时只有一行在编辑
+ const [editingRole, setEditingRole] = useState<string | null>(null);
+ // 按角色筛
+ const [role, setRole] = useState("all");
const me = useQuery({ queryKey: ["me"], queryFn: api.me });
const [error, setError] = useState<string | null>(null);
@@ -34,6 +59,14 @@ export function Members({ workspaceId }: { workspaceId: string }) {
queryFn: () => api.members(workspaceId),
});
const orgUsers = useQuery({ queryKey: ["orgUsers"], queryFn: api.orgUsers });
+ /* 停用的账号是部署级的,成员表里查不到(停用之后那个人从成员表、选人器、
+ 每一个列表里消失)——所以另取一次,再并进同一份名单。**只有管理员看得到**:
+ 恢复也只有他能做 */
+ const deactivated = useQuery({
+ queryKey: ["deactivatedUsers"],
+ queryFn: api.deactivatedUsers,
+ enabled: !!me.data?.is_admin,
+ });
const refresh = () => {
setError(null);
@@ -41,7 +74,7 @@ export function Members({ workspaceId }: { workspaceId: string }) {
};
const onError = (e: unknown) => setError((e as Error).message);
- const setRole = useMutation({
+ const setRole_ = useMutation({
mutationFn: ({ userId, role }: { userId: string; role: string }) =>
api.setMemberRole(workspaceId, userId, role),
onSuccess: refresh,
@@ -58,121 +91,261 @@ export function Members({ workspaceId }: { workspaceId: string }) {
);
const deactivate = useMutation({
mutationFn: (userId: string) => api.adminDeactivateUser(userId),
- onSuccess: refresh,
+ onSuccess: () => {
+ refresh();
+ queryClient.invalidateQueries({ queryKey: ["deactivatedUsers"] });
+ },
+ onError,
+ });
+ const revive = useMutation({
+ mutationFn: (userId: string) => api.adminReactivateUser(userId),
+ onSuccess: () => {
+ refresh();
+ queryClient.invalidateQueries({ queryKey: ["deactivatedUsers"] });
+ queryClient.invalidateQueries({ queryKey: ["orgUsers"] });
+ },
onError,
});
const memberIds = new Set(members.data?.map((m) => m.user_id));
const addable = orgUsers.data?.filter((u) => !memberIds.has(u.id)) ?? [];
+
+ /* **停用不是另一张表,是这份名单里的一种状态。**
+ 从前它单独一块挂在页尾:同一个人在两个地方各出现一次,而"这个账号还在不在"
+ 恰恰是看名单时最先要问的一件事。合成一份之后,它变成一个可筛的状态 */
+ const people: Person[] = [
+ ...(members.data ?? []).map((m) => ({ ...m, deactivated: false })),
+ ...(deactivated.data ?? []).map((u) => ({
+ user_id: u.id,
+ display_name: u.display_name,
+ email: u.email,
+ role: "",
+ is_admin: u.is_admin,
+ deactivated: true,
+ })),
+ ];
const q = filter.trim().toLowerCase();
- const memberList = (members.data ?? []).filter(
- (m) =>
- !q || m.display_name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q),
- );
+ const memberList = people
+ .filter((p) => status === "all" || (status === "deactivated") === p.deactivated)
+ .filter((p) => role === "all" || p.role === role)
+ .filter(
+ (p) =>
+ !q ||
+ p.display_name.toLowerCase().includes(q) ||
+ p.email.toLowerCase().includes(q),
+ )
+ // 停用的沉底:他们仍然列着,但不该排在还在用的人前面
+ .sort((a, b) => Number(a.deactivated) - Number(b.deactivated));
const { rows: pagedMembers, safe: safeMemberPage } = pageSlice(memberList, memberPage, MEMBER_PAGE);
+ const reset = (fn: () => void) => {
+ fn();
+ setMemberPage(0);
+ };
+
return (
- /* 三张卡:名单、开账号、停用过的账号。从前是一张大面板把三件事装在一起,
- 于是「移出工作区」「停用账号」「新建用户」读起来像同一件事的三个步骤 */
<div className="space-y-4">
- {/* 过滤这个名单的东西在卡外面(DESIGN.md 6):它不是名单的内容,
- 而且筛空了的时候,那张卡要能变成空态,不能把改筛选的唯一办法一起带走 */}
- <div className="flex items-center justify-end">
- <Input size="sm" className="w-56"
+ {/* 筛这份名单的东西在表格外面(DESIGN.md 6):三个筛子同一副身材——
+ 带放大镜的中号输入框 + 两个下拉,与图谱、文库那几页的筛选条一致 */}
+ <div className="flex flex-wrap items-center gap-2">
+ <Input
+ icon={<Search size={13} />}
+ className="w-64"
placeholder={S.settings.searchUsers}
value={filter}
- onChange={(e) => {
- setFilter(e.target.value);
- setMemberPage(0);
- }}
+ onChange={(e) => reset(() => setFilter(e.target.value))}
+ />
+ <Dropdown
+ className="w-32"
+ value={role}
+ onChange={(v) => reset(() => setRole(v))}
+ options={[
+ { value: "all", label: S.members.filterAllRoles },
+ ...ROLE_OPTIONS,
+ ]}
/>
+ {me.data?.is_admin && (
+ <Dropdown
+ className="w-36"
+ value={status}
+ onChange={(v) => reset(() => setStatus(v as typeof status))}
+ options={[
+ { value: "active", label: S.members.filterActive },
+ { value: "deactivated", label: S.members.filterDeactivated },
+ { value: "all", label: S.members.filterAll },
+ ]}
+ />
+ )}
+ <div className="ml-auto flex items-center gap-2">
+ <Button variant="secondary" size="sm" onClick={() => setAdding(true)}>
+ {S.members.addExisting}
+ </Button>
+ {me.data?.is_admin && (
+ <Button variant="primary" size="sm" onClick={() => setCreating(true)}>
+ <Plus size={12} />
+ {S.settings.newUser}
+ </Button>
+ )}
+ </div>
</div>
{error && <p className="text-body text-danger">{error}</p>}
- <SettingsCard
- title={S.members.title}
- note={
- /* picker 常驻。理由同 KbSettings 里那段:控件消失读作"坏了",
- 而不是"没人可加";空列表 SearchSelect 自己会说 */
- <SearchSelect
- className="w-full max-w-sm"
- value={addUserId}
- onChange={setAddUserId}
- placeholder={S.members.pickUser}
- options={addable.map((u) => ({
- value: u.id,
- label: u.display_name,
- hint: u.email,
- }))}
- />
- }
- action={
+ {/* 一张表:每一列宽度定死,角色、动作都在自己那一列里,不再随名字长短漂移 */}
+ <div className="glass rounded-panel overflow-hidden">
+ <Table>
+ <THead>
+ <Tr>
+ <Th>{S.members.userLabel}</Th>
+ <Th>{S.members.roleLabel}</Th>
+ <Th>{S.members.statusLabel}</Th>
+ <Th />
+ </Tr>
+ </THead>
+ <TBody>
+ {pagedMembers.map((m) => (
+ <Tr key={m.user_id} className={m.deactivated ? "opacity-55" : undefined}>
+ <Td>
+ <div className="flex items-center gap-2">
+ <span className="truncate text-body text-ink">{m.display_name}</span>
+ {m.is_admin && <Chip tone="info">{S.members.systemAdmin}</Chip>}
+ </div>
+ <div className="truncate text-small text-ink-2">{m.email}</div>
+ </Td>
+ <Td>
+ {/* 静态文字,点一下才变成下拉:一列下拉框会把一张只读的名单
+ 看成一张待填的表,而改角色是偶尔为之 */}
+ {m.deactivated ? (
+ <span className="text-small text-ink-2">—</span>
+ ) : editingRole === m.user_id ? (
+ <Dropdown
+ size="sm"
+ className="w-24"
+ value={m.role}
+ onChange={(r) => {
+ setEditingRole(null);
+ if (r !== m.role) setRole_.mutate({ userId: m.user_id, role: r });
+ }}
+ options={ROLE_OPTIONS}
+ />
+ ) : (
+ <LinkButton onClick={() => setEditingRole(m.user_id)}>
+ {S.members.roles[m.role as keyof typeof S.members.roles] ?? m.role}
+ </LinkButton>
+ )}
+ </Td>
+ <Td>
+ {m.deactivated ? (
+ <Chip tone="danger">{S.members.filterDeactivated}</Chip>
+ ) : (
+ <span className="text-small text-ink-2">{S.members.filterActive}</span>
+ )}
+ </Td>
+ <Td className="text-right whitespace-nowrap">
+ {m.deactivated ? (
+ <Button variant="secondary" size="sm"
+ disabled={revive.isPending}
+ onClick={() => revive.mutate(m.user_id)}
+ >
+ {S.members.reactivate}
+ </Button>
+ ) : (
+ <span className="flex items-center justify-end gap-3">
+ <LinkButton tone="danger" onClick={() => remove.mutate(m.user_id)}>
+ {S.members.remove}
+ </LinkButton>
+ {/* 停用账号跟「移出工作区」是两件事:前者断掉整个系统的访问,
+ 后者只是这个工作区不再有他。所以分开两个按钮,而且停用
+ 只给管理员看——它的影响面大得多 */}
+ {me.data?.is_admin && me.data.id !== m.user_id && (
+ <LinkButton
+ tone="danger"
+ onClick={() =>
+ setDeactivating({ id: m.user_id, name: m.display_name })
+ }
+ title={S.members.deactivateHint}
+ >
+ {S.members.deactivate}
+ </LinkButton>
+ )}
+ </span>
+ )}
+ </Td>
+ </Tr>
+ ))}
+ </TBody>
+ </Table>
+ {memberList.length === 0 && (
+ <p className="px-4 py-6 text-body text-ink-2">{S.ui.noMatches}</p>
+ )}
+ </div>
+ <Pager
+ total={memberList.length}
+ pageSize={MEMBER_PAGE}
+ page={safeMemberPage}
+ onPage={setMemberPage}
+ />
+
+ {/* 把一个**已有账号**加进这个工作区。与「开账号」是两件事:那个凭空造
+ 一个人,这个只是给已经存在的人一个角色 */}
+ <Dialog
+ open={adding}
+ onOpenChange={setAdding}
+ title={S.members.addExisting}
+ closeLabel={S.ui.close}
+ footer={
<>
- <Dropdown
- className="w-28"
- value={addRole}
- onChange={setAddRole}
- options={ROLE_OPTIONS}
- />
+ <Button variant="secondary" size="sm" onClick={() => setAdding(false)}>
+ {S.members.cancel}
+ </Button>
<Button variant="primary" size="sm"
- onClick={() => addUserId && setRole.mutate({ userId: addUserId, role: addRole })}
- disabled={!addUserId}
+ disabled={!addUserId || setRole_.isPending}
+ onClick={() => {
+ setRole_.mutate({ userId: addUserId, role: addRole });
+ setAdding(false);
+ }}
>
{S.members.add}
</Button>
</>
}
>
- <div className="divide-y divide-line">
- {pagedMembers.map((m) => (
- <div key={m.user_id} className="flex items-center gap-3 py-3 first:pt-0">
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-body text-ink">{m.display_name}</span>
- {m.is_admin && <Chip tone="info">{S.members.systemAdmin}</Chip>}
- </div>
- <div className="truncate text-small text-ink-2">{m.email}</div>
- </div>
- <Dropdown
- size="sm"
- className="w-24"
- value={m.role}
- onChange={(role) => setRole.mutate({ userId: m.user_id, role })}
- options={ROLE_OPTIONS}
- />
- <div className="flex shrink-0 items-center gap-3 whitespace-nowrap">
- <LinkButton tone="danger" onClick={() => remove.mutate(m.user_id)}>
- {S.members.remove}
- </LinkButton>
- {/* 停用账号跟「移出工作区」是两件事:前者断掉整个系统的访问,
- 后者只是这个工作区不再有他。所以分开两个按钮,而且停用
- 只给管理员看——它的影响面大得多 */}
- {me.data?.is_admin && me.data.id !== m.user_id && (
- <LinkButton
- tone="danger"
- onClick={() =>
- setDeactivating({ id: m.user_id, name: m.display_name })
- }
- title={S.members.deactivateHint}
- >
- {S.members.deactivate}
- </LinkButton>
- )}
- </div>
- </div>
- ))}
+ <div className="grid grid-cols-2 gap-3">
+ <Field label={S.members.userLabel} className="mb-0">
+ {/* 空列表由 SearchSelect 自己说(它有 noMatches 空态) */}
+ <SearchSelect
+ className="w-full"
+ value={addUserId}
+ onChange={setAddUserId}
+ placeholder={S.members.pickUser}
+ options={addable.map((u) => ({
+ value: u.id,
+ label: u.display_name,
+ hint: u.email,
+ }))}
+ />
+ </Field>
+ <Field label={S.members.roleLabel} className="mb-0">
+ <Dropdown
+ className="w-full"
+ value={addRole}
+ onChange={setAddRole}
+ options={ROLE_OPTIONS}
+ />
+ </Field>
</div>
- <Pager
- total={memberList.length}
- pageSize={MEMBER_PAGE}
- page={safeMemberPage}
- onPage={setMemberPage}
- />
- </SettingsCard>
+ </Dialog>
- {me.data?.is_admin && <CreateUser onCreated={refresh} />}
- {me.data?.is_admin && <DeactivatedUsers onChanged={refresh} />}
+ {me.data?.is_admin && (
+ <CreateUserDialog
+ open={creating}
+ onOpenChange={setCreating}
+ onCreated={() => {
+ setCreating(false);
+ refresh();
+ }}
+ />
+ )}
{deactivating && (
<DangerConfirm
title={S.members.deactivate}
@@ -191,58 +364,16 @@ export function Members({ workspaceId }: { workspaceId: string }) {
);
}
-/** 已停用的账号,以及恢复它们。
- *
- * **这一块存在的理由是「否则恢复够不着」**:停用之后那个人从成员表、选人器、
- * 每一个列表里消失,管理员拿不到他的 id,而恢复接口要的正是那个 id。
- *
- * 一个都没有时整块不出现——没有停用过的部署不该看到一个永远空的区块。
- */
-function DeactivatedUsers({ onChanged }: { onChanged: () => void }) {
- const list = useQuery({
- queryKey: ["deactivatedUsers"],
- queryFn: api.deactivatedUsers,
- });
- const queryClient = useQueryClient();
- const revive = useMutation({
- mutationFn: (userId: string) => api.adminReactivateUser(userId),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["deactivatedUsers"] });
- onChanged();
- },
- onError: (e: Error) => toast.error(e.message),
- });
-
- const users = list.data ?? [];
- if (users.length === 0) return null;
-
- return (
- <SettingsCard
- title={S.members.deactivatedTitle}
- hint={S.members.deactivatedHint}
- >
- {/* 一人一行:恢复是每一行自己的动作,所以按钮在行里,不在底栏 */}
- <div className="divide-y divide-line">
- {users.map((u) => (
- <div key={u.id} className="flex items-center gap-3 py-3 first:pt-0">
- <div className="min-w-0 flex-1">
- <div className="truncate text-body text-ink-2">{u.display_name}</div>
- <div className="truncate text-small text-ink-2">{u.email}</div>
- </div>
- <Button variant="secondary" size="sm"
- disabled={revive.isPending}
- onClick={() => revive.mutate(u.id)}
- >
- {S.members.reactivate}
- </Button>
- </div>
- ))}
- </div>
- </SettingsCard>
- );
-}
-/** 管理员代开账号(注册关闭后的唯一入口)。 */
-function CreateUser({ onCreated }: { onCreated: () => void }) {
+/** 管理员代开账号(注册关闭后的唯一入口)。开账号是个动作,住在弹窗里 */
+function CreateUserDialog({
+ open,
+ onOpenChange,
+ onCreated,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCreated: () => void;
+}) {
const queryClient = useQueryClient();
const [email, setEmail] = useState("");
const [name, setName] = useState("");
@@ -267,45 +398,67 @@ function CreateUser({ onCreated }: { onCreated: () => void }) {
const valid = email.includes("@") && name.trim() && password.length >= 8;
return (
- <SettingsCard
+ <Dialog
+ open={open}
+ onOpenChange={onOpenChange}
title={S.settings.newUser}
- note={error && <span className="text-danger">{error}</span>}
- action={
- <Button variant="secondary" size="sm"
- disabled={!valid || create.isPending}
- onClick={() => create.mutate()}
- >
- {S.settings.createUserBtn}
- </Button>
+ closeLabel={S.ui.close}
+ footer={
+ <>
+ <Button variant="secondary" size="sm" onClick={() => onOpenChange(false)}>
+ {S.members.cancel}
+ </Button>
+ <Button variant="primary" size="sm"
+ disabled={!valid || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.settings.createUserBtn}
+ </Button>
+ </>
}
>
- <div className="grid grid-cols-2 gap-2">
- <Input
- placeholder={S.login.email}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- />
- <Input
- placeholder={S.login.displayName}
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
- <Input
- type="password"
- placeholder={S.settings.initialPassword}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- />
- <Dropdown
- value={role}
- onChange={setRole}
- options={[
- { value: "admin", label: S.members.roles.admin },
- { value: "editor", label: S.members.roles.editor },
- { value: "viewer", label: S.members.roles.viewer },
- ]}
- />
+ {/* 这是**给别人开账号**,不是登录:浏览器看见「邮箱 + 密码」就把当前
+ 登录的人填进来(管理员打开它,看到的是自己的名字和一串圆点)。
+ `new-password` 让 Chrome 认出这是设新密码而不是回填旧凭据,
+ 上面两格一并关掉自动填充 */}
+ <div className="grid grid-cols-2 gap-3">
+ <Field label={S.login.email} className="mb-0">
+ <Input className="w-full"
+ autoFocus
+ autoComplete="off"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ />
+ </Field>
+ <Field label={S.login.displayName} className="mb-0">
+ <Input className="w-full"
+ autoComplete="off"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Field>
+ <Field label={S.settings.initialPassword} className="mb-0">
+ <Input className="w-full"
+ type="password"
+ autoComplete="new-password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </Field>
+ <Field label={S.members.roleLabel} className="mb-0">
+ <Dropdown
+ className="w-full"
+ value={role}
+ onChange={setRole}
+ options={[
+ { value: "admin", label: S.members.roles.admin },
+ { value: "editor", label: S.members.roles.editor },
+ { value: "viewer", label: S.members.roles.viewer },
+ ]}
+ />
+ </Field>
</div>
- </SettingsCard>
+ {error && <p className="mt-3 text-small text-danger">{error}</p>}
+ </Dialog>
);
}
diff --git a/web/src/pages/MyKbs.tsx b/web/src/pages/MyKbs.tsx
index 9e07354f..fd036dae 100644
--- a/web/src/pages/MyKbs.tsx
+++ b/web/src/pages/MyKbs.tsx
@@ -1,15 +1,23 @@
-/* 账户层"我的知识库":可访问的库 + 我的角色 + 加入信息 + 概览统计。
- 只读全景——建库是管理动作,入口在 System settings › Knowledge bases。 */
-import { useQuery } from "@tanstack/react-query";
-import { useNavigate } from "@tanstack/react-router";
-import { Lock } from "lucide-react";
-import { api, type MyKb } from "../api";
+/* 账户层"我的知识库":可访问的库 + 我的角色 + 加入信息 + 概览统计,**以及建库**。
+ 从前建库的入口在 Administration 里,而那一节只有系统管理员看得见——可建库要的
+ 是工作区 Admin+,于是一个工作区管理员在界面上根本没有建库的门。两处列的又是
+ 同一份数据(都读 `my-kbs`),所以并成这一页。 */
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import { Lock, Plus, Search } from "lucide-react";
+import { api, DEFAULT_ONTOLOGY_PACKS, type MyKb } from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
import {
Button,
+ Checkbox,
Chip,
+ Dialog,
+ Field,
+ Input,
Loading,
+ MultiSearchSelect,
PageHeader,
} from "../ui";
@@ -27,17 +35,40 @@ function joinInfo(row: MyKb): string {
export function MyKbs() {
const navigate = useNavigate();
+ const queryClient = useQueryClient();
const { workspace, setKb } = useKb();
+ // 库切换器最后一行带 ?create=true 过来:落地就开表单
+ const { create: deepLink } = useSearch({ from: "/account/account/kbs" });
+ const [creating, setCreating] = useState(!!deepLink);
+ const [filter, setFilter] = useState("");
const mine = useQuery({
queryKey: ["myKbs", workspace?.id],
queryFn: () => api.myKbs(workspace!.id),
enabled: !!workspace,
});
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ /* 能不能建库:系统管理员,或者在这个工作区里是 Admin+(api/kbs.rs 的 create
+ 就是这么判的)。**editor 不能**——它管的是库里的内容,不是有几个库 */
+ const wsRole = useQuery({
+ queryKey: ["workspaceRole", workspace?.id],
+ queryFn: () => api.workspaceRole(workspace!.id),
+ enabled: !!workspace,
+ });
+ const canCreate =
+ !!me.data?.is_admin ||
+ wsRole.data?.role === "admin" ||
+ wsRole.data?.role === "owner";
if (!workspace || mine.isPending) return <Loading>{S.nav.loading}</Loading>;
- const rows = mine.data?.kbs ?? [];
+ const q = filter.trim().toLowerCase();
+ const rows = (mine.data?.kbs ?? []).filter(
+ (r) =>
+ !q ||
+ r.kb.name.toLowerCase().includes(q) ||
+ (r.kb.description ?? "").toLowerCase().includes(q),
+ );
const openKb = (id: string) => {
setKb(id);
navigate({ to: "/kb/$kbId/graph", params: { kbId: id } });
@@ -45,53 +76,67 @@ export function MyKbs() {
return (
<div className="px-8 py-6">
- <PageHeader title={S.account.kbsTitle} />
-
- {/* 一个面板装多行,不是一行一张卡片(DESIGN.md 6)。卡片阵列会让页面上
- 平铺七八个盒子、层级全平,而且每张卡片既是面板又是可点对象——面板于是
- 需要悬停反馈,可槽本来不该响应指针。收成一个槽之后,悬停归行所有 */}
- <div className="glass rounded-panel divide-y divide-line">
- {rows.map((row) => {
- const canManage = row.my_role === "admin" || row.my_role === "owner";
- return (
- <div key={row.kb.id} className="px-6 py-4">
- <div className="flex items-start gap-3">
+ {/* 与管理页同一副身材:内容居中限宽,行长不随窗口拉长 */}
+ <div className="mx-auto w-full max-w-4xl">
+ <PageHeader
+ title={S.account.kbsTitle}
+ actions={
+ canCreate && (
+ <Button variant="primary" size="sm" onClick={() => setCreating(true)}>
+ <Plus size={12} />
+ {S.settings.kbs.newKb}
+ </Button>
+ )
+ }
+ />
+
+ {/* 筛这份名单的东西在面板外面(DESIGN.md 6) */}
+ <div className="mb-4">
+ <Input
+ icon={<Search size={13} />}
+ className="w-72"
+ placeholder={S.account.kbsFilter}
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ />
+ </div>
+
+ {/* 一个面板装多行,不是一行一张卡片(DESIGN.md 6)。一行说清三件事:
+ 这是哪个库、里面有多少东西、我在里面是什么身份 */}
+ <div className="glass rounded-panel divide-y divide-line">
+ {rows.map((row) => {
+ const canManage = row.my_role === "admin" || row.my_role === "owner";
+ return (
+ <div key={row.kb.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <span className="text-title font-medium text-ink truncate">
- {row.kb.name}
- </span>
- {row.kb.visibility === "restricted" ? (
+ <span className="truncate text-body text-ink">{row.kb.name}</span>
+ {row.kb.is_default && (
+ <Chip tone="neutral">{S.settings.kbs.defaultChip}</Chip>
+ )}
+ {row.kb.visibility === "restricted" && (
<span className="flex items-center gap-1 text-fine text-ink-2">
<Lock size={10} />
{S.account.kbRestricted}
</span>
- ) : (
- <span className="text-fine text-ink-2">{S.account.kbOpen}</span>
+ )}
+ {row.my_role && (
+ <Chip tone={canManage ? "info" : "neutral"}>
+ {S.account.roleNames[row.my_role] ?? row.my_role}
+ </Chip>
)}
</div>
- {row.kb.description && (
- <p className="mt-1 text-small text-ink-2 truncate">
- {row.kb.description}
- </p>
- )}
- <p className="mt-2 text-fine text-ink-2">
- <span className="u-num">{S.account.kbStats(row.doc_count, row.member_count)}</span>
- <span className="mx-2 text-ink-2">·</span>
+ <div className="mt-1 truncate text-small text-ink-2">
+ <span className="u-num">
+ {S.account.kbStats(row.doc_count, row.member_count)}
+ </span>
+ <span className="mx-2">·</span>
{joinInfo(row)}
- </p>
+ </div>
</div>
- <div className="shrink-0 flex items-center gap-2">
- {row.my_role && (
- <Chip tone={canManage ? "info" : "neutral"}>
- {S.account.roleNames[row.my_role] ?? row.my_role}
- </Chip>
- )}
- <Button variant="secondary" size="sm"
- onClick={() => openKb(row.kb.id)}
- >
- {S.account.openKb}
- </Button>
+ {/* 设置在前、打开在后:不是每一行都有设置(要 admin),把总是在的
+ 那个放右端,一列按钮的右缘才不会一行一个样 */}
+ <div className="flex shrink-0 items-center gap-2">
{canManage && (
<Button variant="secondary" size="sm"
onClick={() => {
@@ -102,13 +147,144 @@ export function MyKbs() {
{S.account.kbSettingsBtn}
</Button>
)}
+ <Button variant="secondary" size="sm" onClick={() => openKb(row.kb.id)}>
+ {S.account.openKb}
+ </Button>
</div>
</div>
- </div>
- );
- })}
- </div>
+ );
+ })}
+ {rows.length === 0 && (
+ <p className="px-4 py-6 text-body text-ink-2">{S.ui.noMatches}</p>
+ )}
+ </div>
+ {creating && (
+ <NewKbModal
+ workspaceId={workspace.id}
+ onDone={(id) => {
+ setCreating(false);
+ queryClient.invalidateQueries({ queryKey: ["myKbs", workspace.id] });
+ queryClient.invalidateQueries({ queryKey: ["kbs", workspace.id] });
+ // 建完直达库设置:下一步几乎总是邀人/配置
+ if (id) {
+ setKb(id);
+ navigate({ to: "/kb/$kbId/settings", params: { kbId: id } });
+ }
+ }}
+ />
+ )}
+ </div>
</div>
);
}
+
+/** 新建知识库弹窗:缺省 restricted,不污染全员切换器。
+ **建库不是系统管理员专属**——工作区 Admin 起就能建(见 api/kbs.rs 的
+ create),所以它住在人人都会来的这一页,不在 Administration 里 */
+function NewKbModal({
+ workspaceId,
+ onDone,
+}: {
+ workspaceId: string;
+ onDone: (id?: string) => void;
+}) {
+ const [name, setName] = useState("");
+ const [desc, setDesc] = useState("");
+ const [restricted, setRestricted] = useState(true);
+ // schema.org 默认勾选,可反选(0009)。删掉内置类之后不选任何包的库是真的空,
+ // 而空库仍然能用——但绝大多数人要的是一个已经能认出人、组织、产品的起点。
+ // 一秒装完(0008 的批量插入),所以默认装得起
+ const [packs, setPacks] = useState<string[]>([...DEFAULT_ONTOLOGY_PACKS]);
+
+ const available = useQuery({
+ queryKey: ["ontologyPacks"],
+ queryFn: api.ontologyPacks,
+ });
+
+ // 勾选顺序即安装顺序:第一个包的类会认领同名的种子类,
+ // 后面的撞名才查得到对齐表。所以取消再勾会排到末尾——这是对的
+ const toggle = (id: string) =>
+ setPacks((prev) =>
+ prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id],
+ );
+
+ const create = useMutation({
+ mutationFn: () =>
+ api.createKb(workspaceId, {
+ name: name.trim(),
+ description: desc.trim() || null,
+ visibility: restricted ? "restricted" : "open",
+ ontology_packs: packs,
+ }),
+ onSuccess: (kb) => onDone(kb.id),
+ });
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(o) => !o && onDone()}
+ title={S.settings.kbs.newKb}
+ closeLabel={S.ui.close}
+ width="sm"
+ footer={
+ <>
+ <Button variant="secondary" size="sm" onClick={() => onDone()}>
+ {S.library.cancel}
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={!name.trim() || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.settings.kbs.create}
+ </Button>
+ </>
+ }
+ >
+ <div>
+ <Input className="w-full mb-2"
+ autoFocus
+ placeholder={S.settings.kbs.name}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Input className="w-full mb-3"
+ placeholder={S.settings.kbs.description}
+ value={desc}
+ onChange={(e) => setDesc(e.target.value)}
+ />
+ <Checkbox
+ className="mb-4"
+ checked={restricted}
+ onChange={(e) => setRestricted(e.target.checked)}
+ label={S.settings.kbs.visRestricted}
+ />
+
+ {/* 包是可选的,而且**多半只装一个**:五张卡片铺开占了这张弹窗一多半,
+ 换成搜着选——说明与规模挪进下拉里的次要文案,选中的堆在框上面 */}
+ <Field label={S.settings.kbs.packsLabel} hint={S.settings.kbs.packsHint}>
+ <MultiSearchSelect
+ className="w-full"
+ values={packs}
+ options={(available.data?.packs ?? []).map((p) => ({
+ value: p.id,
+ label: p.name,
+ hint: `${p.summary} · ${S.settings.kbs.packsCount(p.classes, p.properties)}`,
+ }))}
+ placeholder={S.settings.kbs.packsPick}
+ emptyHint={S.settings.kbs.packsNone}
+ onToggle={toggle}
+ />
+ </Field>
+ {create.isError && (
+ <p className="text-small text-danger mb-2">
+ {(create.error as Error).message}
+ </p>
+ )}
+ </div>
+ </Dialog>
+ );
+}
+
diff --git a/web/src/pages/OntologySchemaGraph.tsx b/web/src/pages/OntologySchemaGraph.tsx
index 4ee9db2f..3b849a9b 100644
--- a/web/src/pages/OntologySchemaGraph.tsx
+++ b/web/src/pages/OntologySchemaGraph.tsx
@@ -30,6 +30,10 @@ import { EdgeCurvedArrowProgram } from "@sigma/edge-curve";
import { NodeSquareShellProgram } from "./squareShellProgram";
import {
drawHoverCard,
+ CANVAS_FONT,
+ CANVAS_LABEL_SIZE,
+ CANVAS_TEXT,
+ CANVAS_TEXT_2,
drawPillLabel,
drawWorldGrid,
mix,
@@ -676,18 +680,18 @@ export function OntologySchemaGraph({
},
enableEdgeEvents: true,
minEdgeThickness: MIN_EDGE_THICKNESS,
- labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',
- labelSize: 11,
- labelColor: { color: "#e5e5e5" },
+ labelFont: CANVAS_FONT,
+ labelSize: CANVAS_LABEL_SIZE,
+ labelColor: { color: CANVAS_TEXT },
labelRenderedSizeThreshold: 6,
labelDensity: 0.7,
labelGridCellSize: 140,
minCameraRatio: 0.05,
maxCameraRatio: 6,
- edgeLabelSize: 10,
+ edgeLabelSize: CANVAS_LABEL_SIZE,
// 与 /graph 的边标签同一个灰;只有关系边挂标签,有字的就是关系边
- edgeLabelColor: { color: "#a3a3a3" },
- edgeLabelFont: '"Geist", "Inter", sans-serif',
+ edgeLabelColor: { color: CANVAS_TEXT_2 },
+ edgeLabelFont: CANVAS_FONT,
defaultDrawNodeLabel: drawPillLabel,
defaultDrawNodeHover: drawHoverCard,
nodeReducer: (node, attrs) => {
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 89fdf101..01209b76 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,16 +1,18 @@
import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useNavigate, useSearch } from "@tanstack/react-router";
-import { Lock, Plus, X } from "lucide-react";
-import { api, DEFAULT_ONTOLOGY_PACKS } from "../api";
+import { useSearch } from "@tanstack/react-router";
+import { Plus, X } from "lucide-react";
+import { api, type DataSourceView } from "../api";
import { LANG_NAMES, S } from "../i18n";
import { useKb } from "../kb";
import { toast } from "../toast";
import {
Button,
Checkbox,
- ChoiceCard,
+ Chip,
Dialog,
+ Dropdown,
+ Field,
IconButton,
Input,
LinkButton,
@@ -18,10 +20,28 @@ import {
SearchSelect,
Segmented,
SettingsCard,
+ Table,
+ TBody,
+ Td,
+ Th,
+ THead,
+ Tr,
PageHeader,
} from "../ui";
import { Members } from "./Members";
+/** 管理页的五节。**它们是左栏的第二层,不是正文顶上的一条 tab 带**——
+ 与账户栏那四项是同一种东西(去哪儿),只是矮一级;地址里是 `?tab=`,
+ 刷新、回退、分享链接都落回同一节。左栏(AccountShell)与这一页的标题
+ 读的是同一份,名字只有一处。**label 是函数**:界面语言在运行时可切,
+ 模块顶上取值会把第一次加载时的那门语言焊死 */
+export const ADMIN_TABS = [
+ { key: "models", label: () => S.settings.tabModels },
+ { key: "members", label: () => S.settings.tabMembers },
+ { key: "datasources", label: () => S.settings.datasources.tab },
+ { key: "deployment", label: () => S.settings.tabDeployment },
+] as const;
+
/** 一个源授权给了哪些工作区(0014)。
*
* **授权与挂载是两层**:这里说「这个源可以给谁用」,KB 管理员再在授权过的
@@ -276,51 +296,56 @@ function DeploymentAdmin() {
<span className="text-ink-2 truncate hidden sm:inline">
{m.base_url}
</span>
- <Input size="sm" className="u-input-plain ml-auto w-14 u-num text-center shrink-0"
- type="number"
- min={1}
- max={256}
- value={val}
- onChange={(e) =>
- setPerModel({
- ...perModel,
- [key]: Math.max(1, Math.min(256, Number(e.target.value) || 1)),
- })
- }
- />
- <Button variant="secondary" size="sm" className="shrink-0"
- disabled={save.isPending || perModel[key] === undefined}
- onClick={() =>
- save.mutate({
- open,
- modelLimit: {
- base_url: m.base_url,
- model: m.model,
- max_concurrent: val,
- },
- })
- }
- >
- {S.settings.deployment.workersApply}
- </Button>
- {cur !== null && (
- <Button variant="secondary" size="sm" className="shrink-0"
- disabled={save.isPending}
- title={S.settings.deployment.modelResetHint}
+ {/* 数字框与按钮包成一组,**和底栏那一组同一副几何**
+ (w-16、gap-3):右缘都顶到卡的内距,间距一差 4px,
+ 同一列上下两个框的左缘就错开,看着就是内距没对齐 */}
+ <div className="ml-auto flex shrink-0 items-center gap-3">
+ <Input size="sm" className="u-input-plain w-16 u-num text-center"
+ type="number"
+ min={1}
+ max={256}
+ value={val}
+ onChange={(e) =>
+ setPerModel({
+ ...perModel,
+ [key]: Math.max(1, Math.min(256, Number(e.target.value) || 1)),
+ })
+ }
+ />
+ <Button variant="secondary" size="sm"
+ disabled={save.isPending || perModel[key] === undefined}
onClick={() =>
save.mutate({
open,
modelLimit: {
base_url: m.base_url,
model: m.model,
- max_concurrent: null,
+ max_concurrent: val,
},
})
}
>
- {S.settings.deployment.modelReset}
+ {S.settings.deployment.workersApply}
</Button>
- )}
+ {cur !== null && (
+ <Button variant="secondary" size="sm"
+ disabled={save.isPending}
+ title={S.settings.deployment.modelResetHint}
+ onClick={() =>
+ save.mutate({
+ open,
+ modelLimit: {
+ base_url: m.base_url,
+ model: m.model,
+ max_concurrent: null,
+ },
+ })
+ }
+ >
+ {S.settings.deployment.modelReset}
+ </Button>
+ )}
+ </div>
</div>
);
})}
@@ -336,243 +361,276 @@ function DeploymentAdmin() {
}
/** 知识库管理(部署层):全部库总览 + 新建(建库是管理动作,切换器只切换)。 */
-/** `autoCreate`:从库切换器最后一行过来的,落地就开建库表单 */
-function KbsAdmin({ autoCreate }: { autoCreate?: boolean }) {
- const navigate = useNavigate();
- const queryClient = useQueryClient();
- const { workspace, setKb } = useKb();
- const [creating, setCreating] = useState(!!autoCreate);
- const list = useQuery({
- queryKey: ["myKbs", workspace?.id],
- queryFn: () => api.myKbs(workspace!.id),
- enabled: !!workspace,
- });
- const rows = list.data?.kbs ?? [];
- return (
- <div className="space-y-4">
- <p className="text-small text-ink-2">{S.settings.kbs.hint}</p>
-
- <div className="glass rounded-panel divide-y divide-line">
- {rows.map(({ kb, doc_count, member_count }) => (
- <div key={kb.id} className="px-4 py-3 flex items-center gap-3">
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="text-body text-ink truncate">
- {kb.name}
- </span>
- {kb.is_default && (
- <span className="u-chip u-chip-neutral !text-fine">
- {S.settings.kbs.defaultChip}
- </span>
- )}
- {kb.visibility === "restricted" && (
- <span className="flex items-center gap-1 text-fine text-ink-2">
- <Lock size={10} />
- {S.settings.kbs.visRestricted}
- </span>
- )}
- </div>
- <div className="mt-1 text-small text-ink-2">
- <span className="u-num">
- {S.account.kbStats(doc_count, member_count)}
- </span>
- </div>
- </div>
- <Button variant="secondary" size="sm" className="shrink-0"
- onClick={() => {
- setKb(kb.id);
- navigate({ to: "/kb/$kbId/settings", params: { kbId: kb.id } });
- }}
- >
- {S.settings.kbs.openSettings}
- </Button>
- </div>
- ))}
- {!list.isPending && rows.length === 0 && (
- <p className="px-4 py-6 text-body text-ink-2">{S.settings.kbs.empty}</p>
- )}
- </div>
+/** 系统层数据源注册(问数):凭据只进不出,列表只显示 host:port/db 摘要。 */
+/* ---- 每种引擎问什么,以及那些答案怎么拼成一条连接串 ----
- <Button variant="primary" size="sm" className="flex items-center gap-2"
- onClick={() => setCreating(true)}
- >
- <Plus size={12} />
- {S.settings.kbs.newKb}
- </Button>
-
- {creating && workspace && (
- <NewKbModal
- workspaceId={workspace.id}
- onDone={(id) => {
- setCreating(false);
- queryClient.invalidateQueries({
- queryKey: ["myKbs", workspace.id],
- });
- queryClient.invalidateQueries({ queryKey: ["kbs", workspace.id] });
- // 建完直达库设置:下一步几乎总是邀人/配置
- if (id) {
- setKb(id);
- navigate({ to: "/kb/$kbId/settings", params: { kbId: id } });
- }
- }}
- />
- )}
- </div>
- );
+ **人填的是字段,存的仍然是连接串。** 服务端一直按 scheme 认引擎(见
+ `query_engine::engine_from_conn`),所以这里只是把「写一条 URL」这件事
+ 换成「填几格」——密码里的 @ 和 / 也不用人自己转义了。
+
+ 最后一档是原样的连接串:sslmode、附加参数这类写法拼不出来,得给行家留门。 */
+type DsField = {
+ key: string;
+ label: string;
+ placeholder?: string;
+ optional?: boolean;
+ secret?: boolean;
+};
+type EngineSpec = {
+ id: string;
+ /** 引擎名是专有名词,不翻译 */
+ label: string;
+ fields: DsField[];
+ build: (v: Record<string, string>) => string;
+};
+
+const enc = encodeURIComponent;
+/** `user:pass@` 那一段:两处都可能为空(Trino 允许无密码) */
+const auth = (user: string, pass: string) =>
+ pass ? `${enc(user)}:${enc(pass)}@` : user ? `${enc(user)}@` : "";
+
+function dsSpecs(): EngineSpec[] {
+ const D = S.settings.datasources;
+ return [
+ {
+ id: "postgres",
+ label: "Postgres",
+ fields: [
+ { key: "host", label: D.fHost, placeholder: "db.internal" },
+ { key: "port", label: D.fPort, placeholder: "5432" },
+ { key: "database", label: D.fDatabase, placeholder: "analytics" },
+ { key: "user", label: D.fUser },
+ { key: "password", label: D.fPassword, secret: true },
+ ],
+ build: (v) =>
+ `postgres://${auth(v.user, v.password)}${v.host}:${v.port || "5432"}/${v.database}`,
+ },
+ {
+ id: "mysql",
+ label: "MySQL",
+ fields: [
+ { key: "host", label: D.fHost, placeholder: "db.internal" },
+ { key: "port", label: D.fPort, placeholder: "3306" },
+ { key: "database", label: D.fDatabase },
+ { key: "user", label: D.fUser },
+ { key: "password", label: D.fPassword, secret: true },
+ ],
+ build: (v) =>
+ `mysql://${auth(v.user, v.password)}${v.host}:${v.port || "3306"}/${v.database}`,
+ },
+ {
+ id: "trino",
+ label: "Trino",
+ fields: [
+ { key: "host", label: D.fHost },
+ { key: "port", label: D.fPort, placeholder: "8080" },
+ { key: "catalog", label: D.fCatalog, placeholder: "iceberg" },
+ { key: "schema", label: D.fSchema, optional: true },
+ { key: "user", label: D.fUser },
+ { key: "password", label: D.fPassword, optional: true, secret: true },
+ ],
+ build: (v) =>
+ `trino://${auth(v.user, v.password)}${v.host}:${v.port || "8080"}/${v.catalog}` +
+ (v.schema ? `/${v.schema}` : ""),
+ },
+ {
+ id: "databricks",
+ label: "Databricks",
+ fields: [
+ { key: "host", label: D.fHost, placeholder: "dbc-1234.cloud.databricks.com" },
+ { key: "token", label: D.fToken, secret: true },
+ { key: "warehouse", label: D.fWarehouseId, placeholder: "abc123def456" },
+ { key: "catalog", label: D.fCatalog, optional: true, placeholder: "main" },
+ ],
+ build: (v) =>
+ `databricks://:${enc(v.token)}@${v.host}/sql/1.0/warehouses/${v.warehouse}` +
+ (v.catalog ? `?catalog=${enc(v.catalog)}` : ""),
+ },
+ {
+ id: "snowflake",
+ label: "Snowflake",
+ fields: [
+ {
+ key: "account",
+ label: D.fAccount,
+ placeholder: "acme-xy12345.snowflakecomputing.com",
+ },
+ { key: "token", label: D.fToken, secret: true },
+ { key: "database", label: D.fDatabase },
+ { key: "schema", label: D.fSchema },
+ { key: "warehouse", label: D.fWarehouse },
+ ],
+ build: (v) =>
+ `snowflake://:${enc(v.token)}@${v.account}/${v.database}/${v.schema}` +
+ `?warehouse=${enc(v.warehouse)}`,
+ },
+ {
+ id: "raw",
+ label: D.engineRaw,
+ fields: [{ key: "conn", label: D.connString }],
+ build: (v) => v.conn.trim(),
+ },
+ ];
}
-/** 新建知识库弹窗(管理员):缺省 restricted,不污染全员切换器。 */
-function NewKbModal({
- workspaceId,
- onDone,
+/** 登记一个数据源:选引擎、填几格、**存之前先试一次**。 */
+function NewDataSourceDialog({
+ open,
+ onOpenChange,
+ onCreated,
}: {
- workspaceId: string;
- onDone: (id?: string) => void;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCreated: () => void;
}) {
+ const specs = dsSpecs();
const [name, setName] = useState("");
- const [desc, setDesc] = useState("");
- const [restricted, setRestricted] = useState(true);
- // schema.org 默认勾选,可反选(0009)。删掉内置类之后不选任何包的库是真的空,
- // 而空库仍然能用——但绝大多数人要的是一个已经能认出人、组织、产品的起点。
- // 一秒装完(0008 的批量插入),所以默认装得起
- const [packs, setPacks] = useState<string[]>([...DEFAULT_ONTOLOGY_PACKS]);
-
- const available = useQuery({
- queryKey: ["ontologyPacks"],
- queryFn: api.ontologyPacks,
- });
-
- // 勾选顺序即安装顺序:第一个包的类会认领同名的种子类,
- // 后面的撞名才查得到对齐表。所以取消再勾会排到末尾——这是对的
- const toggle = (id: string) =>
- setPacks((prev) =>
- prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id],
- );
+ const [engineId, setEngineId] = useState(specs[0].id);
+ const [values, setValues] = useState<Record<string, string>>({});
+ const spec = specs.find((s) => s.id === engineId) ?? specs[0];
+ const conn = spec.build(values);
+ const filled = spec.fields.every((f) => f.optional || (values[f.key] ?? "").trim());
+ const ready = !!name.trim() && filled;
+ // 试连不落库,所以换引擎、改字段之后上一次的结果就不作数了
+ const probe = useMutation({
+ mutationFn: () => api.adminTestConnString(conn),
+ });
const create = useMutation({
- mutationFn: () =>
- api.createKb(workspaceId, {
- name: name.trim(),
- description: desc.trim() || null,
- visibility: restricted ? "restricted" : "open",
- ontology_packs: packs,
- }),
- onSuccess: (kb) => onDone(kb.id),
+ mutationFn: () => api.adminCreateDataSource({ name: name.trim(), conn_string: conn }),
+ onSuccess: () => {
+ setName("");
+ setValues({});
+ onCreated();
+ },
});
+ const set = (key: string, v: string) => {
+ probe.reset();
+ setValues((prev) => ({ ...prev, [key]: v }));
+ };
return (
<Dialog
- open
- onOpenChange={(o) => !o && onDone()}
- title={S.settings.kbs.newKb}
+ open={open}
+ onOpenChange={onOpenChange}
+ title={S.settings.datasources.newTitle}
closeLabel={S.ui.close}
- width="sm"
+ width="lg"
footer={
<>
- <Button variant="secondary" size="sm" onClick={() => onDone()}>
- {S.library.cancel}
+ {/* 试连在左边:它不是"完成",是完成之前的那一步 */}
+ <Button variant="secondary" size="sm" className="mr-auto"
+ disabled={!filled || probe.isPending}
+ onClick={() => probe.mutate()}
+ >
+ {probe.isPending
+ ? S.settings.datasources.testing
+ : S.settings.datasources.testConn}
+ </Button>
+ <Button variant="secondary" size="sm" onClick={() => onOpenChange(false)}>
+ {S.members.cancel}
</Button>
- <Button
- variant="primary"
- size="sm"
- disabled={!name.trim() || create.isPending}
+ <Button variant="primary" size="sm"
+ disabled={!ready || create.isPending}
onClick={() => create.mutate()}
>
- {S.settings.kbs.create}
+ {S.settings.datasources.add}
</Button>
</>
}
>
- <div>
- <Input className="w-full mb-2"
- autoFocus
- placeholder={S.settings.kbs.name}
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
- <Input className="w-full mb-3"
- placeholder={S.settings.kbs.description}
- value={desc}
- onChange={(e) => setDesc(e.target.value)}
- />
- <Checkbox
- className="mb-4"
- checked={restricted}
- onChange={(e) => setRestricted(e.target.checked)}
- label={S.settings.kbs.visRestricted}
- />
+ <div className="space-y-3">
+ <div className="grid grid-cols-2 gap-3">
+ <Field label={S.settings.datasources.name} className="mb-0">
+ <Input className="w-full"
+ autoFocus
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Field>
+ <Field label={S.settings.datasources.engine} className="mb-0">
+ <Dropdown
+ className="w-full"
+ value={engineId}
+ onChange={(v) => {
+ setEngineId(v);
+ setValues({});
+ probe.reset();
+ }}
+ options={specs.map((s) => ({ value: s.id, label: s.label }))}
+ />
+ </Field>
+ </div>
- <div className="mb-4">
- <div className="text-small text-ink-2 mb-1">
- {S.settings.kbs.packsLabel}
- </div>
- <p className="text-fine leading-relaxed text-ink-2 mb-2">
- {S.settings.kbs.packsHint}
- </p>
- <div className="grid grid-cols-2 gap-2">
- {available.data?.packs.map((p) => {
- const on = packs.includes(p.id);
- return (
- <ChoiceCard
- key={p.id}
- checked={on}
- onChange={() => toggle(p.id)}
- label={p.name}
- >
- <span className="block text-small text-ink">
- {p.name}
- </span>
- <span className="block text-fine leading-snug text-ink-2">
- {p.summary}
- </span>
- <span className="mt-1 block text-fine text-ink-2">
- {S.settings.kbs.packsCount(p.classes, p.properties)}
- </span>
- </ChoiceCard>
- );
- })}
- </div>
- {packs.length === 0 && (
- <p className="text-fine text-ink-2 mt-2">
- {S.settings.kbs.packsNone}
- </p>
- )}
+ <div className="grid grid-cols-2 gap-3">
+ {spec.fields.map((f) => (
+ <Field
+ key={f.key}
+ className={`mb-0 ${f.key === "conn" ? "col-span-2" : ""}`}
+ label={
+ f.optional
+ ? `${f.label} ${S.settings.datasources.optional}`
+ : f.label
+ }
+ >
+ <Input className="w-full"
+ type={f.secret ? "password" : undefined}
+ autoComplete={f.secret ? "new-password" : "off"}
+ placeholder={f.placeholder}
+ value={values[f.key] ?? ""}
+ onChange={(e) => set(f.key, e.target.value)}
+ />
+ </Field>
+ ))}
</div>
- {create.isError && (
- <p className="text-small text-danger mb-2">
- {(create.error as Error).message}
+
+ {/* 拼出来的那条串给人看一眼——密码位打码。填错端口、库名多一个斜杠,
+ 在这里一眼就看得出来,不必等到试连 */}
+ {engineId !== "raw" && filled && (
+ <p className="truncate font-mono text-fine text-ink-2" title={maskConn(conn)}>
+ {maskConn(conn)}
</p>
)}
+
+ {probe.data && (
+ <p className={`text-small ${probe.data.ok ? "text-ok" : "text-danger"}`}>
+ {probe.data.ok
+ ? S.settings.datasources.testOk
+ : (probe.data.error ?? S.settings.datasources.testFail)}
+ </p>
+ )}
+ {probe.isError && (
+ <p className="text-small text-danger">{(probe.error as Error).message}</p>
+ )}
+ {create.isError && (
+ <p className="text-small text-danger">{(create.error as Error).message}</p>
+ )}
</div>
</Dialog>
);
}
-/** 系统层数据源注册(问数):凭据只进不出,列表只显示 host:port/db 摘要。 */
+/** 回显时把密码位打码:`postgres://user:••••@host/db` */
+function maskConn(conn: string): string {
+ return conn.replace(/:\/\/([^:@/]*):([^@]*)@/, (_m, user: string) =>
+ user ? `://${user}:••••@` : "://:••••@",
+ );
+}
+
function DataSourcesAdmin() {
const queryClient = useQueryClient();
const list = useQuery({
queryKey: ["dataSources"],
queryFn: api.adminDataSources,
});
- const [name, setName] = useState("");
- const [conn, setConn] = useState("");
+ const [creating, setCreating] = useState(false);
+ // 授权是按工作区的,单租户部署里那一个工作区谁也没见过——所以它不占表里一列,
+ // 点「可用于」那一格才展开
+ const [grantsFor, setGrantsFor] = useState<DataSourceView | null>(null);
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ["dataSources"] });
- const create = useMutation({
- mutationFn: () =>
- api.adminCreateDataSource({
- name: name.trim(),
- conn_string: conn.trim(),
- }),
- onSuccess: () => {
- setName("");
- setConn("");
- invalidate();
- },
- });
const remove = useMutation({
mutationFn: (id: string) => api.adminDeleteDataSource(id),
onSettled: invalidate,
@@ -582,99 +640,141 @@ function DataSourcesAdmin() {
onSettled: invalidate,
});
+ const rows = list.data?.data_sources ?? [];
+
return (
<div className="space-y-4">
- <p className="text-small text-ink-2">{S.settings.datasources.hint}</p>
-
- <div className="glass rounded-panel divide-y divide-line">
- {(list.data?.data_sources ?? []).map((d) => (
- <div key={d.id} className="px-4 py-3 space-y-3">
- <div className="flex items-center gap-3">
- <div className="min-w-0 flex-1">
- <div className="text-body text-ink">
- {d.name}
- <span className="ml-2 text-fine text-ink-2">
- {d.engine}
- </span>
- </div>
- <div className="text-small text-ink-2 font-mono truncate">
- {d.summary}
- </div>
- </div>
- <span
- className={`u-chip shrink-0 ${
- d.last_test_ok === true
- ? "u-chip-success"
- : d.last_test_ok === false
- ? "u-chip-danger"
- : "u-chip-neutral"
- }`}
- >
- {d.last_test_ok === true
- ? S.settings.datasources.testOk
- : d.last_test_ok === false
- ? S.settings.datasources.testFail
- : S.settings.datasources.neverTested}
- </span>
- <Button variant="secondary" size="sm" className="shrink-0"
- disabled={test.isPending}
- onClick={() => test.mutate(d.id)}
- >
- {S.settings.datasources.test}
- </Button>
- <LinkButton
- tone="danger"
- className="shrink-0"
- disabled={remove.isPending}
- onClick={() => remove.mutate(d.id)}
- >
- {S.settings.datasources.remove}
- </LinkButton>
- </div>
- <SourceGrants sourceId={d.id} />
- </div>
- ))}
- {list.data?.data_sources.length === 0 && (
- <p className="px-4 py-6 text-body text-ink-2">
- {S.settings.datasources.empty}
- </p>
- )}
+ {/* 登记在名单上面、靠右:动作在内容之前 */}
+ <div className="flex items-start gap-4">
+ <p className="min-w-0 flex-1 text-small text-ink-2">
+ {S.settings.datasources.hint}
+ </p>
+ <Button variant="primary" size="sm" className="shrink-0"
+ onClick={() => setCreating(true)}
+ >
+ <Plus size={12} />
+ {S.settings.datasources.add}
+ </Button>
</div>
- <div className="glass rounded-panel p-4">
- <div className="max-w-xl space-y-2">
- <Input className="w-full"
- placeholder={S.settings.datasources.name}
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
- <Input className="w-full font-mono u-placeholder-sans"
- placeholder={S.settings.datasources.connString}
- value={conn}
- onChange={(e) => setConn(e.target.value)}
- />
- <p className="text-fine leading-5 text-ink-2 font-mono whitespace-pre-line">
- {S.settings.datasources.connSchemes}
- </p>
- <div className="flex items-center gap-3">
- <Button variant="primary" size="sm"
- disabled={!name.trim() || !conn.trim() || create.isPending}
- onClick={() => create.mutate()}
- >
- {S.settings.datasources.add}
- </Button>
- {create.isError && (
- <span className="text-small text-danger">
- {(create.error as Error).message}
- </span>
- )}
- </div>
+ {rows.length === 0 ? (
+ <div className="glass rounded-panel p-8 text-center text-body text-ink-2">
+ {S.settings.datasources.empty}
</div>
- </div>
+ ) : (
+ <div className="glass rounded-panel overflow-hidden">
+ <Table>
+ <THead>
+ <Tr>
+ <Th>{S.settings.datasources.name}</Th>
+ <Th>{S.settings.datasources.engine}</Th>
+ <Th>{S.settings.datasources.colConn}</Th>
+ <Th>{S.settings.datasources.grants}</Th>
+ <Th>{S.settings.datasources.colStatus}</Th>
+ <Th />
+ </Tr>
+ </THead>
+ <TBody>
+ {rows.map((d) => (
+ <Tr key={d.id}>
+ <Td className="text-ink">{d.name}</Td>
+ <Td className="text-small text-ink-2">{d.engine}</Td>
+ <Td
+ className="max-w-xs truncate font-mono text-small text-ink-2"
+ title={d.summary}
+ >
+ {d.summary}
+ </Td>
+ <Td>
+ <GrantsCell sourceId={d.id} onOpen={() => setGrantsFor(d)} />
+ </Td>
+ <Td>
+ <Chip
+ tone={
+ d.last_test_ok === true
+ ? "success"
+ : d.last_test_ok === false
+ ? "danger"
+ : "neutral"
+ }
+ >
+ {d.last_test_ok === true
+ ? S.settings.datasources.testOk
+ : d.last_test_ok === false
+ ? S.settings.datasources.testFail
+ : S.settings.datasources.neverTested}
+ </Chip>
+ </Td>
+ <Td className="whitespace-nowrap text-right">
+ <LinkButton
+ disabled={test.isPending}
+ onClick={() => test.mutate(d.id)}
+ >
+ {S.settings.datasources.test}
+ </LinkButton>
+ <LinkButton
+ tone="danger"
+ className="ml-3"
+ disabled={remove.isPending}
+ onClick={() => remove.mutate(d.id)}
+ >
+ {S.settings.datasources.remove}
+ </LinkButton>
+ </Td>
+ </Tr>
+ ))}
+ </TBody>
+ </Table>
+ </div>
+ )}
+
+ <NewDataSourceDialog
+ open={creating}
+ onOpenChange={setCreating}
+ onCreated={() => {
+ setCreating(false);
+ invalidate();
+ }}
+ />
+ <Dialog
+ open={!!grantsFor}
+ onOpenChange={(o) => !o && setGrantsFor(null)}
+ title={grantsFor?.name ?? ""}
+ description={S.settings.datasources.grantsHint}
+ closeLabel={S.ui.close}
+ >
+ {grantsFor && <SourceGrants sourceId={grantsFor.id} />}
+ </Dialog>
</div>
);
}
+/** 表里那一格:授权给了谁。点它展开授权面板——**没授权要看得见**,
+ 那条源谁也挂不上,而这是它唯一说得出口的地方 */
+function GrantsCell({
+ sourceId,
+ onOpen,
+}: {
+ sourceId: string;
+ onOpen: () => void;
+}) {
+ const grants = useQuery({
+ queryKey: ["dataSourceGrants", sourceId],
+ queryFn: () => api.dataSourceGrants(sourceId),
+ });
+ const names = (grants.data?.workspaces ?? []).map((w) => w.name);
+ // 没授权是个要紧的状态(谁也挂不上它),用警示胶囊;授权过的只是一句事实
+ return names.length === 0 ? (
+ <Chip tone="warn" onClick={onOpen}>
+ {S.settings.datasources.grantsNoneShort}
+ </Chip>
+ ) : (
+ <LinkButton onClick={onOpen} title={names.join(" · ")}>
+ {S.settings.datasources.grantsCount(names.length)}
+ </LinkButton>
+ );
+}
+
const PRESETS: Record<
string,
{ chat: string; embed: string; chatModel: string; embedModel: string }
@@ -716,7 +816,7 @@ export function Settings() {
/* 人在哪一节,**地址说了算**:左栏第二层是一组 Link(见 AccountShell),
刷新、回退、把链接发给同事都落回同一节。从前这里另存一份 state,
于是地址与页面各说各的 */
- const { tab: tabParam, create } = useSearch({ from: "/account/admin" });
+ const { tab: tabParam } = useSearch({ from: "/account/admin" });
const tab = tabParam ?? "models";
const queryClient = useQueryClient();
const settings = useQuery({
@@ -786,10 +886,13 @@ export function Settings() {
<div className="h-full overflow-y-auto u-scroll px-8 py-6">
{/* 同 KbSettings:设置是读一列字段,居中限宽,行长不随窗口拉长 */}
<div className="mx-auto w-full max-w-4xl">
- <PageHeader title={S.settings.title} />
+ {/* 标题是这一节的名字,不是「Administration」——左栏已经说了人在
+ 管理区,页顶再说一遍等于每一节的标题都一样 */}
+ <PageHeader
+ title={ADMIN_TABS.find((t) => t.key === tab)?.label() ?? S.settings.title}
+ />
{tab === "members" && <Members workspaceId={workspace.id} />}
- {tab === "kbs" && <KbsAdmin autoCreate={!!create} />}
{tab === "datasources" && <DataSourcesAdmin />}
{tab === "deployment" && <DeploymentAdmin />}
diff --git a/web/src/pages/Tokens.tsx b/web/src/pages/Tokens.tsx
index e5bdc7ae..c0a0b97b 100644
--- a/web/src/pages/Tokens.tsx
+++ b/web/src/pages/Tokens.tsx
@@ -257,142 +257,145 @@ export function Tokens() {
return (
<div className="px-8 py-6">
- <PageHeader
- title={S.account.tokensTitle}
- sub={S.account.tokensHint}
- actions={
- <Button variant="primary" size="sm" onClick={() => setCreating(true)}>
- <Plus size={12} />
- {S.account.newToken}
- </Button>
- }
- />
+ {/* 与管理页同一副身材:内容居中限宽,行长不随窗口拉长 */}
+ <div className="mx-auto w-full max-w-4xl">
+ <PageHeader
+ title={S.account.tokensTitle}
+ sub={S.account.tokensHint}
+ actions={
+ <Button variant="primary" size="sm" onClick={() => setCreating(true)}>
+ <Plus size={12} />
+ {S.account.newToken}
+ </Button>
+ }
+ />
- {rows.length === 0 ? (
- <div className="glass rounded-panel p-8 text-center text-body text-ink-2">
- {S.account.noTokens}
- </div>
- ) : (
- <div className="glass rounded-panel overflow-hidden">
- <Table>
- <THead>
- <Tr>
- <Th>{S.account.tokenName}</Th>
- <Th>{S.account.tokenScope}</Th>
- <Th>{S.account.tokenKbs}</Th>
- <Th>{S.account.colLastUsed}</Th>
- <Th>{S.account.tokenExpires}</Th>
- <Th>{S.account.colCreated}</Th>
- <Th />
- </Tr>
- </THead>
- <TBody>
- {rows.map((t) => (
- <TokenRow
- key={t.id}
- t={t}
- kbName={kbName}
- busy={revoke.isPending && revoke.variables === t.id}
- onRevoke={() => revoke.mutate(t.id)}
- />
- ))}
- </TBody>
- </Table>
- </div>
- )}
+ {rows.length === 0 ? (
+ <div className="glass rounded-panel p-8 text-center text-body text-ink-2">
+ {S.account.noTokens}
+ </div>
+ ) : (
+ <div className="glass rounded-panel overflow-hidden">
+ <Table>
+ <THead>
+ <Tr>
+ <Th>{S.account.tokenName}</Th>
+ <Th>{S.account.tokenScope}</Th>
+ <Th>{S.account.tokenKbs}</Th>
+ <Th>{S.account.colLastUsed}</Th>
+ <Th>{S.account.tokenExpires}</Th>
+ <Th>{S.account.colCreated}</Th>
+ <Th />
+ </Tr>
+ </THead>
+ <TBody>
+ {rows.map((t) => (
+ <TokenRow
+ key={t.id}
+ t={t}
+ kbName={kbName}
+ busy={revoke.isPending && revoke.variables === t.id}
+ onRevoke={() => revoke.mutate(t.id)}
+ />
+ ))}
+ </TBody>
+ </Table>
+ </div>
+ )}
- {/* 一个窗口两副内容:先是表单,发出来之后是那一枚明文。中间不关窗——
- 关掉就再也看不到它了 */}
- <Dialog
- open={creating || !!issued}
- onOpenChange={(o) => !o && close()}
- width={issued ? "lg" : "md"}
- closeLabel={S.ui.close}
- title={issued ? S.account.issuedTitle : S.account.newToken}
- description={issued ? S.account.issuedHint : undefined}
- footer={
- issued ? (
- <Button variant="primary" size="sm" onClick={close}>
- {S.account.tokenDone}
- </Button>
- ) : (
- <>
- <Button variant="secondary" size="sm" onClick={close}>
- {S.account.cancel}
- </Button>
- <Button variant="primary" size="sm"
- disabled={!name.trim() || issue.isPending}
- onClick={() => issue.mutate()}
- >
- {S.account.issueToken}
+ {/* 一个窗口两副内容:先是表单,发出来之后是那一枚明文。中间不关窗——
+ 关掉就再也看不到它了 */}
+ <Dialog
+ open={creating || !!issued}
+ onOpenChange={(o) => !o && close()}
+ width={issued ? "lg" : "md"}
+ closeLabel={S.ui.close}
+ title={issued ? S.account.issuedTitle : S.account.newToken}
+ description={issued ? S.account.issuedHint : undefined}
+ footer={
+ issued ? (
+ <Button variant="primary" size="sm" onClick={close}>
+ {S.account.tokenDone}
</Button>
- </>
- )
- }
- >
- {issued ? (
- <IssuedBody token={issued.token} info={issued.info} kbs={kbs} />
- ) : (
- <div>
- <Field label={S.account.tokenName}>
- <Input className="w-full"
- autoFocus
- placeholder={S.account.tokenNamePlaceholder}
- value={name}
- maxLength={64}
- onChange={(e) => setName(e.target.value)}
- />
- </Field>
- {/* 范围与有效期并排:两个都是一眼扫过去就定下来的小选择,
- 各占一整行只是把这张表拉长 */}
- <div className="grid grid-cols-2 gap-4">
- {/* 二选一,且两个选项都要读得到——单选按钮,不是一排按钮 */}
- <Field label={S.account.tokenScope} hint={S.account.scopeHint}>
- <div className="flex h-8 items-center gap-4">
- {(["read", "write"] as const).map((s) => (
- <Radio
- key={s}
- name="token-scope"
- checked={scope === s}
- onChange={() => setScope(s)}
- label={s === "read" ? S.account.scopeRead : S.account.scopeWrite}
- />
- ))}
- </div>
+ ) : (
+ <>
+ <Button variant="secondary" size="sm" onClick={close}>
+ {S.account.cancel}
+ </Button>
+ <Button variant="primary" size="sm"
+ disabled={!name.trim() || issue.isPending}
+ onClick={() => issue.mutate()}
+ >
+ {S.account.issueToken}
+ </Button>
+ </>
+ )
+ }
+ >
+ {issued ? (
+ <IssuedBody token={issued.token} info={issued.info} kbs={kbs} />
+ ) : (
+ <div>
+ <Field label={S.account.tokenName}>
+ <Input className="w-full"
+ autoFocus
+ placeholder={S.account.tokenNamePlaceholder}
+ value={name}
+ maxLength={64}
+ onChange={(e) => setName(e.target.value)}
+ />
</Field>
- <Field label={S.account.tokenExpires}>
- <Dropdown
+ {/* 范围与有效期并排:两个都是一眼扫过去就定下来的小选择,
+ 各占一整行只是把这张表拉长 */}
+ <div className="grid grid-cols-2 gap-4">
+ {/* 二选一,且两个选项都要读得到——单选按钮,不是一排按钮 */}
+ <Field label={S.account.tokenScope} hint={S.account.scopeHint}>
+ <div className="flex h-8 items-center gap-4">
+ {(["read", "write"] as const).map((s) => (
+ <Radio
+ key={s}
+ name="token-scope"
+ checked={scope === s}
+ onChange={() => setScope(s)}
+ label={s === "read" ? S.account.scopeRead : S.account.scopeWrite}
+ />
+ ))}
+ </div>
+ </Field>
+ <Field label={S.account.tokenExpires}>
+ <Dropdown
+ className="w-full"
+ value={String(days)}
+ onChange={(v) => setDays(Number(v))}
+ options={EXPIRY_CHOICES.map((d) => ({
+ value: String(d),
+ label: d === 0 ? S.account.expiresNever : S.account.expiresDays(d),
+ }))}
+ />
+ </Field>
+ </div>
+ {/* 库可以很多:搜着选,选中的堆在框上面。芯片墙的高度随库数长,
+ 这个不随。**不再另写一句「不选就是全部」**——控件自己就写着
+ 「All bases」,同一件事说两遍只是把表单拉长 */}
+ <Field label={S.account.tokenKbs} className="mb-0">
+ <MultiSearchSelect
className="w-full"
- value={String(days)}
- onChange={(v) => setDays(Number(v))}
- options={EXPIRY_CHOICES.map((d) => ({
- value: String(d),
- label: d === 0 ? S.account.expiresNever : S.account.expiresDays(d),
- }))}
+ values={Array.from(picked)}
+ options={kbs.map((k) => ({ value: k.id, label: k.name }))}
+ placeholder={S.account.pickBases}
+ emptyHint={S.account.allBases}
+ onToggle={(id) => {
+ const next = new Set(picked);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ setPicked(next);
+ }}
/>
</Field>
</div>
- {/* 库可以很多:搜着选,选中的堆在框上面。芯片墙的高度随库数长,
- 这个不随。**不再另写一句「不选就是全部」**——控件自己就写着
- 「All bases」,同一件事说两遍只是把表单拉长 */}
- <Field label={S.account.tokenKbs} className="mb-0">
- <MultiSearchSelect
- className="w-full"
- values={Array.from(picked)}
- options={kbs.map((k) => ({ value: k.id, label: k.name }))}
- placeholder={S.account.pickBases}
- emptyHint={S.account.allBases}
- onToggle={(id) => {
- const next = new Set(picked);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- setPicked(next);
- }}
- />
- </Field>
- </div>
- )}
- </Dialog>
+ )}
+ </Dialog>
+ </div>
</div>
);
}
diff --git a/web/src/pages/graphVisuals.ts b/web/src/pages/graphVisuals.ts
index 10d091d7..99b24976 100644
--- a/web/src/pages/graphVisuals.ts
+++ b/web/src/pages/graphVisuals.ts
@@ -29,8 +29,19 @@ export const MUTED_SHELL = "#151515";
每划过一个节点就换一次,压到底会让整张画布不停明灭 */
export const HOVER_MUTE = 0.78;
export const PILL_BG = "rgba(12,12,12,0.9)";
-export const PILL_BORDER = "rgba(255,255,255,0.14)";
-export const PILL_TEXT = "#ededed";
+export const PILL_BORDER = "rgba(255,255,255,0.14)"; // --u-line-strong
+export const PILL_TEXT = "#ededed"; // --u-text
+
+/* 画布上的字与界面同一套刻度。**canvas 读不到 CSS 变量**,所以这里镜像一份
+ `styles.css` 的值——它是源头,改那边记得回来改这里。
+ 从前这几个数是自己长出来的(节点 11、边 9、类型行 10、字色 #e5e5e5 /
+ #a1a1a1):字号整体上移一档之后,画布成了全站唯一还在用旧刻度的地方,
+ 而 9px 比界面里最小的字还小一半 */
+export const CANVAS_FONT = '"Geist", "Inter", "Noto Sans SC", sans-serif';
+export const CANVAS_TEXT = "#ededed"; // --u-text
+export const CANVAS_TEXT_2 = "#a8a8a8"; // --u-text-2
+export const CANVAS_LABEL_SIZE = 12; // --text-fine
+export const CANVAS_TITLE_SIZE = 14; // --text-body
export function hexToRgb(hex: string): [number, number, number] {
const m = /^#?([0-9a-f]{6})$/i.exec(hex);
@@ -57,11 +68,13 @@ export function drawPillLabel(
if (!data.label) return;
// hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签
if (data.hideBaseLabel) return;
- // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12
- const size = Math.max(10, Math.min(11, data.size * 0.25));
- ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ /* 与界面上的 chip 同一副身材:字号 fine、内距 8/2、圆角 cell(4)。
+ 从前字号跟着节点大小在 10–11 之间浮动——同一张图里两个节点的名字不一样大,
+ 而它们是同一种东西 */
+ const size = CANVAS_LABEL_SIZE;
+ ctx.font = `500 ${size}px ${CANVAS_FONT}`;
ctx.textBaseline = "middle";
- const padX = 6;
+ const padX = 8;
const padY = 3;
const w = ctx.measureText(data.label).width + padX * 2;
const h = size + padY * 2;
@@ -71,7 +84,7 @@ export function drawPillLabel(
ctx.shadowColor = "rgba(0,0,0,0.6)";
ctx.shadowBlur = 12;
ctx.beginPath();
- ctx.roundRect(x, y, w, h, 6);
+ ctx.roundRect(x, y, w, h, 4);
ctx.fillStyle = PILL_BG;
ctx.fill();
ctx.shadowBlur = 0;
@@ -111,17 +124,18 @@ export function drawHoverCard(
ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);
ctx.fill();
- // 卡片: 标题 700/13 + 类型行 500/10 大写
- const titleSize = 13;
- const metaSize = 10;
+ /* 卡片:标题 body/500、类型行 fine。**类型不再大写**——界面里没有一处
+ 大写拉字距的小标题(表格列头除外),画布也不该自成一套 */
+ const titleSize = CANVAS_TITLE_SIZE;
+ const metaSize = CANVAS_LABEL_SIZE;
const padX = 10;
const padY = 7;
const metaGap = 5;
- const meta = String(data.typeLabel ?? "NODE").toUpperCase();
+ const meta = String(data.typeLabel ?? "");
ctx.textBaseline = "top";
- ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ ctx.font = `500 ${titleSize}px ${CANVAS_FONT}`;
const titleW = ctx.measureText(data.label).width;
- ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
+ ctx.font = `400 ${metaSize}px ${CANVAS_FONT}`;
const metaW = ctx.measureText(meta).width;
const w = Math.max(titleW, metaW) + padX * 2;
const h = padY * 2 + titleSize + metaGap + metaSize;
@@ -131,7 +145,7 @@ export function drawHoverCard(
ctx.shadowColor = "rgba(0,0,0,0.62)";
ctx.shadowBlur = 15;
ctx.beginPath();
- ctx.roundRect(x, y, w, h, 8);
+ ctx.roundRect(x, y, w, h, 8); // --radius-panel
ctx.fillStyle = "rgba(12,12,12,0.94)";
ctx.fill();
ctx.shadowBlur = 0;
@@ -139,11 +153,11 @@ export function drawHoverCard(
ctx.lineWidth = 1;
ctx.stroke();
- ctx.fillStyle = "#f5f5f5";
- ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ ctx.fillStyle = CANVAS_TEXT;
+ ctx.font = `500 ${titleSize}px ${CANVAS_FONT}`;
ctx.fillText(data.label, x + padX, y + padY);
- ctx.fillStyle = "rgba(255,255,255,0.5)";
- ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
+ ctx.fillStyle = CANVAS_TEXT_2;
+ ctx.font = `400 ${metaSize}px ${CANVAS_FONT}`;
ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);
ctx.restore();
}
diff --git a/web/src/router.tsx b/web/src/router.tsx
index 5bd71e9d..dfe5f21e 100644
--- a/web/src/router.tsx
+++ b/web/src/router.tsx
@@ -189,6 +189,10 @@ const accountRoute = createRoute({
const myKbsRoute = createRoute({
getParentRoute: () => accountShellRoute,
path: "/account/kbs",
+ // 建库的入口在别处(顶栏的库切换器最后一行),带着这个参数落地就直接开表单
+ validateSearch: (search: Record<string, unknown>): { create?: true } => ({
+ create: search.create === true || search.create === "true" ? true : undefined,
+ }),
component: MyKbs,
});
@@ -205,20 +209,14 @@ const adminRoute = createRoute({
// 深链指定页签(如 KB 数据节的"注册新连接"直达 Data sources)
validateSearch: (
search: Record<string, unknown>,
- ): {
- tab?: "models" | "members" | "kbs" | "datasources" | "deployment";
- create?: true;
- } => ({
+ ): { tab?: "models" | "members" | "datasources" | "deployment" } => ({
tab:
search.tab === "models" ||
search.tab === "members" ||
- search.tab === "kbs" ||
search.tab === "datasources" ||
search.tab === "deployment"
? search.tab
: undefined,
- // 建库的入口在别处(库切换器的最后一行),带着这个参数落到这里就直接开表单
- create: search.create === true || search.create === "true" ? true : undefined,
}),
component: Settings,
});