feat(settings): 数据源配置改成「列出来、勾选、变成来源」,并去掉文件格式筛选

用户对 系统设置 → 数据源配置 的四条要求:
① 这里不要做文件格式筛选(格式归目录级标注决定);
② 列出我账号下能看到的知识库;③ 列出钉盘能看到哪些;④ 勾选那些作为来源。

① 来源卡片不再渲染 FilenameFilterEditor(目录级筛选仍在「来源与目录」里,按目录就近覆盖)。
②③ 新端点 GET /api/v1/dingtalk-spaces/available(管理员,只读):用 dws 列举
   - 知识库:wiki +space-list --type orgWikiSpace/myWikiSpace(实测 17 + 1 个)
   - 钉盘:wiki space list --type mySpace/orgSpace(实测 我的文件 + 6 个组织空间)
   实测约束写进命令形态:--limit 上限是 50;翻页必须 --page-all(--max-items 兜底),
   否则超过一页的知识库会被静默截断(被截断时页面显示"可能不全"而不是假装列全)。
   列不出来 ≠ 空列表:dws 未登录/权限不足 → 503 + 原因;某一类失败只丢那一类。
④ 面板勾选后走既有登记路径(/api/v1/dingtalk-spaces),首次目录扫描自动排队;
   已登记的按空间名标「已是来源」并禁用勾选;扫码会话失效时直接弹二维码,扫完自动重试。

基础设施:api 与 worker 共享同一份 dws 状态(bind mount 同一份,refresh token 是轮换制,
不能各留一份)。子进程 HOME 必须指向 DWS_HOME —— 这条是实测踩出来的:漏了会报"未登录",
已有回归测试钉住。dws 子进程沿用白名单环境,库口令等变量不进子进程。

测试:新包 internal/dingtalkdiscovery(fixture 用真实 dws 输出形状):paging 约束、
截断提示、一类失败不连带、全部失败→ErrUnavailable、子进程环境;httpapi 侧 401/501/503/500
与不泄漏内部错误;OpenAPI 契约(400/503 组件)通过。前端 189 条 + tsc 干净。

面板实测:知识库(18)/钉盘(7)都列出来,已有三条钉钉来源自动标「已是来源」;
勾选「视觉文档」→ 加入为来源 → 新来源 sc-8a4be5b8293d1c9a048c3c7e9b194155(dingtalk,enabled)
+ source.catalog.refresh 已完成。
This commit is contained in:
姚章浩
2026-10-10 16:46:39 +08:00
parent eca7fee5a8
commit e00cab2f70
17 changed files with 1177 additions and 2 deletions
+40
View File
@@ -3292,6 +3292,36 @@
}
}
}
},
"/api/v1/dingtalk-spaces/available": {
"get": {
"tags": [
"Source connections"
],
"operationId": "listAvailableDingtalkSources",
"summary": "列举当前钉钉账号可见的知识库与钉盘空间(管理员,只读)",
"description": "用平台持有的钉钉凭据(dws)只读列举租户目录:知识库与钉盘空间。钉盘列举在某些租户下会被拒,这时返回 drive_notice;接口整体不可用时返回 503,不会伪装成空列表。",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"$ref": "#/components/responses/ServiceUnavailable"
}
}
}
}
},
"components": {
@@ -3479,6 +3509,16 @@
}
}
}
},
"ServiceUnavailable": {
"description": "依赖的第三方或本地工具当前不可用(例如 dws 未登录/权限不足)。",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
},
"schemas": {
+12
View File
@@ -15,6 +15,7 @@ import (
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/backuphost"
"knowledge-governance/internal/dingtalkdiscovery"
"knowledge-governance/internal/httpapi"
"knowledge-governance/internal/monitoring"
postgresstore "knowledge-governance/internal/platform/postgres"
@@ -22,6 +23,15 @@ import (
"knowledge-governance/internal/serviceverify"
)
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
// 钉盘空间。它跑在 api 进程里,但用的是与 worker 共享的同一份 dws 状态目录
// (见 compose.yaml 的 /data/dws 与文件型 keychain 挂载)——凭据只有一份。
type dingtalkSourceLister struct{}
func (dingtalkSourceLister) ListAvailableDingtalkSources(ctx context.Context) (dingtalkdiscovery.Result, error) {
return dingtalkdiscovery.Discover(ctx, dingtalkdiscovery.ExecRunner{})
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
@@ -126,6 +136,8 @@ func run(ctx context.Context, getenv func(string) string) error {
ProductionBackupRestoreVerified: config.ProductionBackupRestoreVerified,
ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef,
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
DingtalkSources: dingtalkSourceLister{},
BackupSchedule: postgresstore.NewStore(pool),
BackupHost: backuphost.New(backuphost.Config{
SSHConfig: config.BackupHostSSHConfig,
+10
View File
@@ -51,9 +51,19 @@ services:
PRODUCTION_WEKNORA_BASE_URL: "${PRODUCTION_WEKNORA_BASE_URL:-}"
PRODUCTION_WEKNORA_API_KEY_FILE: "${PRODUCTION_WEKNORA_API_KEY_FILE:-}"
PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP: "${PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
# 数据源发现(系统设置 → 数据源配置):api 用 dws 只读列举钉钉知识库与钉盘空间。
DWS_BIN: /usr/local/bin/dws
DWS_CONFIG_DIR: /data/dws
DWS_HOME: /data/home
DWS_DISABLE_KEYCHAIN: "1"
secrets:
- pgpass
- test_weknora_api_key
volumes:
# 与 worker 共用同一份 dws 状态:refresh token 是轮换制,绝不能在两处各留一份。
- /home/zheromiku/.dws:/data/dws
# dws 的文件型 keychain 必须有 $HOME/.local/share/dws-cli,故挂到 DWS_HOME 下。
- /home/zheromiku/.local/share/dws-cli:/data/home/.local/share/dws-cli
depends_on:
postgres:
condition: service_healthy
+233
View File
@@ -0,0 +1,233 @@
// Package dingtalkdiscovery 用 dws CLI 枚举「我账号下能看到的数据源」:
// 钉钉知识库(组织知识库 + 我的知识库)与钉盘空间(我的文件 / 组织空间)。
//
// 只读:本包只运行 dws 的列举命令并解析 JSON,不写任何远端对象,也不碰凭据值。
//
// 两条实测约束决定了命令形态:--limit 只能是 1-50;翻页必须靠 --page-all(带 --max-items
// 兜底),否则超过一页的知识库会被静默截断。
//
// dws 的令牌是轮换制,因此运行它的进程必须与 worker 共享同一份状态目录(见 compose.yaml),
// 且子进程的 HOME 必须指向 DWS_HOME(文件型 keychain 在 $HOME/.local/share/dws-cli)。
package dingtalkdiscovery
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
type KnowledgeBase struct {
Name string `json:"name"`
SpaceID string `json:"space_id"`
SpaceType string `json:"space_type"`
URL string `json:"url"`
Description string `json:"description,omitempty"`
}
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
type DriveSpace struct {
Name string `json:"name"`
SpaceID string `json:"space_id"`
RootFolderID string `json:"root_folder_id,omitempty"`
SpaceType string `json:"space_type"`
}
// Result 是一次发现的结果。
type Result struct {
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
DriveSpaces []DriveSpace `json:"drive_spaces"`
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
// 列不出某一类是常见状态(租户权限差异),页面照常显示能列出来的那部分,只在这里给原因。
KnowledgeNotice string `json:"knowledge_notice,omitempty"`
DriveNotice string `json:"drive_notice,omitempty"`
FetchedAt time.Time `json:"fetched_at"`
}
// Runner 执行一条 dws 命令并返回 stdout。实现要求:非零退出码也要把 stdout 交回
// (dws 把错误 JSON 写在那里),并且超时即失败,绝不返回半截 JSON。
type Runner interface {
RunDWS(ctx context.Context, args ...string) ([]byte, error)
}
// ErrUnavailable 表示 dws 不可用(二进制缺失、未登录、权限不足、输出不可解析):
// 调用方应把它映射成「探测不可用」而不是 500 —— 这是环境问题,不是平台缺陷。
var ErrUnavailable = errors.New("dws unavailable")
// knowledgeSpaceTypes 是知识库的两个范围:组织知识库与我的知识库。
var knowledgeSpaceTypes = []string{"orgWikiSpace", "myWikiSpace"}
// SpaceListArgs 是知识库列举的固定命令形态:一次取完,最多 200 条(4 页 × 50)。
func SpaceListArgs(spaceType string) []string {
return []string{"wiki", "+space-list", "--type", spaceType, "--page-all", "--max-items", "200", "--page-limit", "4", "--limit", "50"}
}
// Discover 枚举知识库与钉盘空间。
//
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
func Discover(ctx context.Context, runner Runner) (Result, error) {
result := Result{FetchedAt: time.Now().UTC()}
failures := make([]string, 0, len(knowledgeSpaceTypes))
seenKnowledge := map[string]bool{}
for _, spaceType := range knowledgeSpaceTypes {
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
if err != nil {
failures = append(failures, describe(spaceType, err))
continue
}
bases, notice, err := parseKnowledgeBases(raw, spaceType)
if err != nil {
failures = append(failures, describe(spaceType, err))
continue
}
if notice != "" {
result.KnowledgeNotice = notice
}
for _, base := range bases {
if seenKnowledge[base.SpaceID] {
continue
}
seenKnowledge[base.SpaceID] = true
result.KnowledgeBases = append(result.KnowledgeBases, base)
}
}
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
}
if len(failures) > 0 {
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
}
seenDrive := map[string]bool{}
for _, spaceType := range []string{"mySpace", "orgSpace"} {
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
if err != nil {
result.DriveNotice = err.Error()
continue
}
spaces, err := parseDriveSpaces(raw, spaceType)
if err != nil {
result.DriveNotice = err.Error()
continue
}
for _, space := range spaces {
if seenDrive[space.SpaceType+":"+space.SpaceID] {
continue
}
seenDrive[space.SpaceType+":"+space.SpaceID] = true
result.DriveSpaces = append(result.DriveSpaces, space)
}
}
return result, nil
}
func describe(scope string, err error) string {
return scope + ":" + err.Error()
}
// parseKnowledgeBases 解析 `dws wiki +space-list`:
// {"ok":true,"data":{"count":17,"hasMore":false,"autoPageComplete":true,"spaces":[{name,url,workspaceId}]}}
// 第二个返回值是「结果不完整」的说明(被 --max-items 截断)。
func parseKnowledgeBases(raw []byte, spaceType string) ([]KnowledgeBase, string, error) {
var payload struct {
OK bool `json:"ok"`
Data struct {
Count int `json:"count"`
HasMore bool `json:"hasMore"`
AutoPageComplete bool `json:"autoPageComplete"`
Spaces []struct {
Name string `json:"name"`
URL string `json:"url"`
WorkspaceID string `json:"workspaceId"`
Description string `json:"description"`
} `json:"spaces"`
} `json:"data"`
Error *struct {
Message string `json:"message"`
Type string `json:"type"`
} `json:"error"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return nil, "", fmt.Errorf("parse knowledge base list: %w", err)
}
if !payload.OK {
message := "dws reported failure"
if payload.Error != nil && payload.Error.Message != "" {
message = payload.Error.Message
}
return nil, "", errors.New(message)
}
out := make([]KnowledgeBase, 0, len(payload.Data.Spaces))
for _, space := range payload.Data.Spaces {
name := strings.TrimSpace(space.Name)
id := strings.TrimSpace(space.WorkspaceID)
if name == "" || id == "" {
continue
}
url := strings.TrimSpace(space.URL)
if url == "" {
url = SpaceURL(id)
}
out = append(out, KnowledgeBase{Name: name, SpaceID: id, SpaceType: spaceType, URL: url, Description: strings.TrimSpace(space.Description)})
}
notice := ""
if payload.Data.HasMore && !payload.Data.AutoPageComplete {
notice = fmt.Sprintf("%s 结果超过上限,只列出前 %d 个知识库。", spaceType, len(out))
}
return out, notice, nil
}
// parseDriveSpaces 解析 `dws wiki space list --type …`:
// {"success":true,"result":{"items":[{spaceId,spaceName,spaceType,rootFolderId}]}}
func parseDriveSpaces(raw []byte, spaceType string) ([]DriveSpace, error) {
var payload struct {
Success bool `json:"success"`
ErrorMsg string `json:"errorMsg"`
ErrorCode string `json:"errorCode"`
Result struct {
Items []struct {
SpaceID json.Number `json:"spaceId"`
SpaceName string `json:"spaceName"`
SpaceType string `json:"spaceType"`
RootFolderID string `json:"rootFolderId"`
} `json:"items"`
} `json:"result"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("parse drive space list: %w", err)
}
if !payload.Success {
message := strings.TrimSpace(payload.ErrorMsg)
if message == "" {
message = strings.TrimSpace(payload.ErrorCode)
}
if message == "" {
message = "dws reported failure"
}
return nil, errors.New(message)
}
out := make([]DriveSpace, 0, len(payload.Result.Items))
for _, item := range payload.Result.Items {
name := strings.TrimSpace(item.SpaceName)
id := strings.TrimSpace(item.SpaceID.String())
if name == "" || id == "" {
continue
}
kind := strings.TrimSpace(item.SpaceType)
if kind == "" {
kind = spaceType
}
out = append(out, DriveSpace{Name: name, SpaceID: id, SpaceType: kind, RootFolderID: strings.TrimSpace(item.RootFolderID)})
}
return out, nil
}
// SpaceURL 由空间 id 拼出 alidocs 链接:登记来源走的就是这个形态。
func SpaceURL(spaceID string) string {
return "https://alidocs.dingtalk.com/i/spaces/" + spaceID + "/overview"
}
@@ -0,0 +1,201 @@
package dingtalkdiscovery
import (
"context"
"errors"
"strings"
"testing"
)
// fakeRunner 按命令行返回预设 stdout —— fixture 用的是 dws 真实输出形状(已实跑核对)。
type fakeRunner struct {
responses map[string]string
failures map[string]error
seen []string
}
func (f *fakeRunner) RunDWS(_ context.Context, args ...string) ([]byte, error) {
key := strings.Join(args, " ")
f.seen = append(f.seen, key)
if err, ok := f.failures[key]; ok {
return nil, err
}
if body, ok := f.responses[key]; ok {
return []byte(body), nil
}
return []byte(`{"ok":true,"data":{"spaces":[]}}`), nil
}
func kbKey(spaceType string) string { return strings.Join(SpaceListArgs(spaceType), " ") }
const orgKnowledgeFixture = `{
"ok": true,
"outcome": "success",
"data": {
"autoPageComplete": true,
"count": 3,
"hasMore": false,
"pagesFetched": 1,
"requestedType": "orgWikiSpace",
"spaces": [
{"createTime": 1753837670187, "description": "", "name": "ATOM知识库",
"url": "https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview", "workspaceId": "9JOGOQneRgkneX4Q"},
{"createTime": 1770260286344, "description": "公司级知识库,是公司统一口径、可被 AI 使用、可持续维护的权威知识中心。",
"name": "公司级技术支持知识库", "url": "https://alidocs.dingtalk.com/i/spaces/9JOGO6332vlBnm4Q/overview", "workspaceId": "9JOGO6332vlBnm4Q"},
{"createTime": 1, "description": "", "name": "没有链接的空间", "url": "", "workspaceId": "9JOGO0000000000Q"}
]
}
}`
const myKnowledgeFixture = `{"ok": true, "data": {"autoPageComplete": true, "count": 1, "hasMore": false, "requestedType": "myWikiSpace",
"spaces": [{"description": "", "name": "我的文档", "url": "https://alidocs.dingtalk.com/i/spaces/9JOGOxeo90ybnz4Q/overview", "workspaceId": "9JOGOxeo90ybnz4Q"}]}}`
const mySpaceFixture = `{"success": true, "result": {"items": [
{"createTime": 1768373459000, "modifyTime": 1768374168000, "rootFolderId": "65Y1OQX0akWmxN7DYGwUw8GlDd3mERZq",
"spaceId": "28122692916", "spaceName": "我的文件", "spaceType": "mySpace"}
]}}`
const orgSpaceFixture = `{"success": true, "result": {"items": [
{"createTime": 1453221947000, "modifyTime": 1782304977000, "rootFolderId": "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a",
"spaceId": "102571304", "spaceName": "全员文件夹", "spaceType": "orgSpace"},
{"createTime": 1773248364000, "modifyTime": 1791620354000, "rootFolderId": "DElyQod3RxJKGnaQ61nIAJkb4Mw9r5vq",
"spaceId": "28459418500", "spaceName": "公司级营销资料管理", "spaceType": "orgSpace"}
]}}`
func fullRunner() *fakeRunner {
return &fakeRunner{responses: map[string]string{
kbKey("orgWikiSpace"): orgKnowledgeFixture,
kbKey("myWikiSpace"): myKnowledgeFixture,
"wiki space list --type mySpace": mySpaceFixture,
"wiki space list --type orgSpace": orgSpaceFixture,
}}
}
func TestDiscoverParsesKnowledgeBasesAndDriveSpaces(t *testing.T) {
runner := fullRunner()
result, err := Discover(context.Background(), runner)
if err != nil {
t.Fatalf("discover: %v", err)
}
if len(result.KnowledgeBases) != 4 {
t.Fatalf("knowledge bases = %d, want 4(组织 3 + 我的 1)", len(result.KnowledgeBases))
}
// 缺 url 的空间由空间 id 拼链接,保证勾选后仍能登记。
missingURL := result.KnowledgeBases[2]
if missingURL.URL != "https://alidocs.dingtalk.com/i/spaces/9JOGO0000000000Q/overview" {
t.Fatalf("synthesised url = %q", missingURL.URL)
}
if result.KnowledgeBases[0].SpaceType != "orgWikiSpace" || result.KnowledgeBases[3].SpaceType != "myWikiSpace" {
t.Fatalf("space types = %q / %q", result.KnowledgeBases[0].SpaceType, result.KnowledgeBases[3].SpaceType)
}
if len(result.DriveSpaces) != 3 {
t.Fatalf("drive spaces = %d, want 3 (%+v)", len(result.DriveSpaces), result.DriveSpaces)
}
if result.DriveSpaces[1].SpaceType != "orgSpace" || result.DriveSpaces[1].RootFolderID == "" {
t.Fatalf("org space = %+v", result.DriveSpaces[1])
}
if result.DriveNotice != "" || result.KnowledgeNotice != "" {
t.Fatalf("unexpected notices: %q / %q", result.KnowledgeNotice, result.DriveNotice)
}
// 两条实测约束:--limit 上限是 50,且必须 --page-all,否则知识库会被静默截断。
for _, call := range runner.seen {
if strings.HasPrefix(call, "wiki +space-list") {
if !strings.Contains(call, "--page-all") || !strings.Contains(call, "--limit 50") {
t.Fatalf("knowledge list call misses paging constraints: %q", call)
}
if strings.Contains(call, "--limit 200") {
t.Fatalf("--limit above the CLI cap is rejected at runtime: %q", call)
}
}
}
}
// 钉盘列举被拒(租户权限)时,知识库必须照常返回,只带一条原因 —— 否则页面上什么都看不到。
func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
runner := fullRunner()
runner.failures = map[string]error{
"wiki space list --type mySpace": errors.New("permission denied (operation: drive/list_spaces)"),
"wiki space list --type orgSpace": errors.New("permission denied (operation: drive/list_spaces)"),
}
result, err := Discover(context.Background(), runner)
if err != nil {
t.Fatalf("discover should tolerate drive failure, got %v", err)
}
if len(result.KnowledgeBases) != 4 {
t.Fatalf("knowledge bases = %d, want 4", len(result.KnowledgeBases))
}
if len(result.DriveSpaces) != 0 {
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
}
if !strings.Contains(result.DriveNotice, "permission denied") {
t.Fatalf("drive notice = %q", result.DriveNotice)
}
}
// 一类知识库失败(例如个人知识库无权限)不该连带组织知识库一起消失。
func TestDiscoverKeepsOneKnowledgeScopeWhenTheOtherFails(t *testing.T) {
runner := fullRunner()
runner.failures = map[string]error{kbKey("myWikiSpace"): errors.New("[AUTH_PERMISSION_DENIED] Permission denied")}
result, err := Discover(context.Background(), runner)
if err != nil {
t.Fatalf("discover: %v", err)
}
if len(result.KnowledgeBases) != 3 {
t.Fatalf("knowledge bases = %d, want the org scope only", len(result.KnowledgeBases))
}
if !strings.Contains(result.KnowledgeNotice, "myWikiSpace") {
t.Fatalf("notice should name the failed scope: %q", result.KnowledgeNotice)
}
}
// 被 --max-items 截断时必须留下提示,不能假装列出了全部。
func TestDiscoverReportsTruncatedKnowledgeList(t *testing.T) {
runner := fullRunner()
runner.responses[kbKey("orgWikiSpace")] = `{"ok":true,"data":{"autoPageComplete":false,"count":50,"hasMore":true,
"spaces":[{"name":"只列出一部分","url":"","workspaceId":"9JOGO1111111111Q"}]}}`
result, err := Discover(context.Background(), runner)
if err != nil {
t.Fatalf("discover: %v", err)
}
if !strings.Contains(result.KnowledgeNotice, "上限") {
t.Fatalf("expected a truncation notice, got %q", result.KnowledgeNotice)
}
}
// 知识库是主列表:两个范围都列不出来时按「环境不可用」上报,页面显示提示而不是空列表。
func TestDiscoverReportsUnavailableWhenEveryKnowledgeScopeFails(t *testing.T) {
for name, body := range map[string]string{
"not logged in": `{"ok":false,"outcome":"failure","error":{"type":"auth","message":"dws: 未登录,请先执行 dws auth login"}}`,
"permission": `{"ok":false,"outcome":"failure","error":{"type":"permission","message":"[AUTH_PERMISSION_DENIED] Permission denied"}}`,
"garbage output": `not json at all`,
"bad flag": `{"ok":false,"outcome":"failure","error":{"type":"internal","message":"--limit 必须是 1-50 之间的整数"}}`,
} {
t.Run(name, func(t *testing.T) {
runner := &fakeRunner{responses: map[string]string{kbKey("orgWikiSpace"): body, kbKey("myWikiSpace"): body}}
_, err := Discover(context.Background(), runner)
if err == nil {
t.Fatal("expected an error")
}
if !errors.Is(err, ErrUnavailable) {
t.Fatalf("err = %v, want ErrUnavailable", err)
}
})
}
}
func TestDiscoverReportsUnavailableWhenDWSMissing(t *testing.T) {
runner := &fakeRunner{failures: map[string]error{
kbKey("orgWikiSpace"): errors.New("dws binary not found"),
kbKey("myWikiSpace"): errors.New("dws binary not found"),
}}
_, err := Discover(context.Background(), runner)
if !errors.Is(err, ErrUnavailable) {
t.Fatalf("err = %v, want ErrUnavailable", err)
}
}
func TestSpaceURL(t *testing.T) {
if got := SpaceURL("ABC123"); got != "https://alidocs.dingtalk.com/i/spaces/ABC123/overview" {
t.Fatalf("space url = %q", got)
}
}
+83
View File
@@ -0,0 +1,83 @@
package dingtalkdiscovery
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// ExecRunner 是真的 dws 运行器。它只传 dws 需要的白名单环境(与取件器一致):
// 漏掉 DWS_CONFIG_DIR / DWS_HOME 时 dws 会找不到配置目录与文件型 keychain,报"未登录"。
type ExecRunner struct {
// Binary 是 dws 可执行文件;空值取 DWS_BIN,再取 PATH 里的 dws。
Binary string
// Timeout 单条命令超时;为零取 25 秒。
Timeout time.Duration
}
// RunDWS 运行 `dws <args…>` 并返回 stdout。
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
binary := r.Binary
if binary == "" {
binary = os.Getenv("DWS_BIN")
}
if binary == "" {
found, err := exec.LookPath("dws")
if err != nil {
return nil, fmt.Errorf("dws binary not found: %w", err)
}
binary = found
}
timeout := r.Timeout
if timeout <= 0 {
timeout = 25 * time.Second
}
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
command := exec.CommandContext(runCtx, binary, args...)
command.Env = dwsEnv()
var stdout, stderr bytes.Buffer
command.Stdout = &stdout
command.Stderr = &stderr
if err := command.Run(); err != nil {
// 退出码非零时 dws 仍会把错误 JSON 写在 stdout 上,保留它便于上层判定。
if stdout.Len() > 0 {
return stdout.Bytes(), fmt.Errorf("dws %s: %w", strings.Join(args, " "), err)
}
message := strings.TrimSpace(stderr.String())
if message == "" {
message = err.Error()
}
return nil, fmt.Errorf("dws %s: %s", strings.Join(args, " "), message)
}
return stdout.Bytes(), nil
}
// dwsEnv 是给 dws 子进程的环境白名单:不把平台的库口令等变量带进子进程。
func dwsEnv() []string {
env := make([]string, 0, 8)
for _, name := range []string{"PATH", "SSL_CERT_FILE", "LANG"} {
if value := os.Getenv(name); value != "" {
env = append(env, name+"="+value)
}
}
// dws 的文件型 keychain 固定在 $HOME/.local/share/dws-cli,而 keychain 是挂在 DWS_HOME
// 下面的(容器自身的 HOME 指向别处)。因此只给 dws 子进程换 HOME,不动整个进程。
home := os.Getenv("DWS_HOME")
if home == "" {
home = os.Getenv("HOME")
}
if home != "" {
env = append(env, "HOME="+home)
}
for _, name := range []string{"DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN"} {
if value := os.Getenv(name); value != "" {
env = append(env, name+"="+value)
}
}
return env
}
@@ -0,0 +1,70 @@
package dingtalkdiscovery
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// dws 的文件型 keychain 固定在 $HOME/.local/share/dws-cli,而 keychain 挂在 DWS_HOME 下面;
// 子进程若沿用容器自身的 HOME 就会报"未登录"。这条断言把该行为钉住(实测踩过)。
func TestDWSEnvPutsTheKeychainHomeOnTheDWSHome(t *testing.T) {
t.Setenv("DWS_HOME", "/data/home")
t.Setenv("HOME", "/home/app")
t.Setenv("DWS_CONFIG_DIR", "/data/dws")
t.Setenv("DWS_DISABLE_KEYCHAIN", "1")
t.Setenv("DWS_BIN", "/usr/local/bin/dws")
t.Setenv("DATABASE_URL", "postgres://governance:secret@postgres/governance")
t.Setenv("TEST_WEKNORA_API_KEY", "sk-should-not-leak")
env := dwsEnv()
joined := strings.Join(env, "\n")
if !strings.Contains(joined, "HOME=/data/home") {
t.Fatalf("dws child HOME should follow DWS_HOME, env=%v", env)
}
if strings.Contains(joined, "HOME=/home/app") {
t.Fatalf("container HOME leaked into dws child: %v", env)
}
for _, leaked := range []string{"DATABASE_URL", "TEST_WEKNORA_API_KEY"} {
if strings.Contains(joined, leaked) {
t.Fatalf("%s leaked into the dws child: %v", leaked, env)
}
}
}
// 没有 DWS_HOME 时退回进程自己的 HOME。
func TestDWSEnvFallsBackToProcessHome(t *testing.T) {
t.Setenv("DWS_HOME", "")
t.Setenv("HOME", "/home/app")
if joined := strings.Join(dwsEnv(), "\n"); !strings.Contains(joined, "HOME=/home/app") {
t.Fatalf("expected fallback HOME, got %v", dwsEnv())
}
}
// 真跑一个假的 dws:确认参数被原样传给二进制,且非零退出码时仍把 stdout 交回上层
// (dws 把错误 JSON 写在 stdout 上,丢了它就没法分辨"未登录"与"权限不足")。
func TestExecRunnerRunsTheBinaryAndKeepsStdoutOnFailure(t *testing.T) {
dir := t.TempDir()
binary := filepath.Join(dir, "dws")
script := "#!/bin/sh\necho \"args:$@\"\necho '{\"ok\":false,\"error\":{\"message\":\"dws: 未登录\"}}'\nexit 4\n"
if err := os.WriteFile(binary, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
runner := ExecRunner{Binary: binary, Timeout: 5 * time.Second}
out, err := runner.RunDWS(context.Background(), "wiki", "+space-list", "--limit", "200")
if err == nil {
t.Fatal("expected a non-zero exit to be reported")
}
if !strings.Contains(string(out), "未登录") {
t.Fatalf("stdout should be preserved on failure, got %q", string(out))
}
if !strings.Contains(string(out), "args:wiki +space-list --limit 200") {
t.Fatalf("args not passed through: %q", string(out))
}
if !strings.Contains(err.Error(), "wiki +space-list") {
t.Fatalf("error should name the command: %v", err)
}
}
+50
View File
@@ -0,0 +1,50 @@
package httpapi
import (
"context"
"errors"
"net/http"
"time"
"knowledge-governance/internal/dingtalkdiscovery"
)
// dingtalkSourcesLister 是本路由需要的最小能力面:枚举「我账号下能看到」的钉钉知识库与
// 钉盘空间。真实实现由 cmd/api 注入(用 worker 同一份 dws 状态跑只读列举);
// 未接线时返回 501,而不是把"没接线"当成空列表。
type dingtalkSourcesLister interface {
ListAvailableDingtalkSources(context.Context) (dingtalkdiscovery.Result, error)
}
// listDingtalkSources 处理 GET /api/v1/dingtalk-spaces/available:
// 「系统设置 → 数据源配置」用它列出可勾选为来源的钉钉知识库与钉盘空间。
//
// 走 /api/v1/dingtalk-spaces 前缀是刻意的:该前缀在角色判定里是管理员专用(与扫码会话、
// 空间登记同级),因为这里用的是平台持有的钉钉凭据读租户目录。
func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config) {
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
lister := config.DingtalkSources
if lister == nil {
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
result, err := lister.ListAvailableDingtalkSources(ctx)
if err != nil {
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "dingtalk_discovery_unavailable",
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
})
return
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
+120
View File
@@ -0,0 +1,120 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/dingtalkdiscovery"
)
type fakeDingtalkSources struct {
result dingtalkdiscovery.Result
err error
}
func (f fakeDingtalkSources) ListAvailableDingtalkSources(context.Context) (dingtalkdiscovery.Result, error) {
return f.result, f.err
}
func dingtalkSourcesRequest(role string) *http.Request {
request := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-spaces/available", nil)
if role == "" {
return request
}
return request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
}
func TestListDingtalkSourcesRequiresAdminAndWiring(t *testing.T) {
rec := httptest.NewRecorder()
listDingtalkSources(rec, dingtalkSourcesRequest(""), Config{})
if rec.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated = %d, want 401", rec.Code)
}
// 未接线:501("没接线"不能被当成空列表)。
rec = httptest.NewRecorder()
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), Config{})
if rec.Code != http.StatusNotImplemented {
t.Fatalf("unwired = %d, want 501 body=%s", rec.Code, rec.Body.String())
}
}
func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T) {
// 用包装错误模拟真实映射:errors.Is 必须认出来,页面才会显示"暂时列不出来"。
config := Config{DingtalkSources: fakeDingtalkSources{err: wrapUnavailable()}}
rec := httptest.NewRecorder()
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
t.Fatalf("body = %s", rec.Body.String())
}
}
func wrapUnavailable() error {
return &wrappedUnavailable{err: dingtalkdiscovery.ErrUnavailable}
}
type wrappedUnavailable struct{ err error }
func (w *wrappedUnavailable) Error() string { return "list knowledge bases: " + w.err.Error() }
func (w *wrappedUnavailable) Unwrap() error { return w.err }
func TestListDingtalkSourcesReturnsKnowledgeBasesAndDriveSpaces(t *testing.T) {
config := Config{DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "ATOM知识库", SpaceID: "9JOGOQneRgkneX4Q", URL: "https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview"}},
DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", SpaceType: "orgSpace"}},
DriveNotice: "list orgSpace: permission denied",
FetchedAt: time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC),
}}}
rec := httptest.NewRecorder()
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var payload struct {
Data struct {
KnowledgeBases []struct {
Name string `json:"name"`
SpaceID string `json:"space_id"`
URL string `json:"url"`
} `json:"knowledge_bases"`
DriveSpaces []struct {
Name string `json:"name"`
SpaceType string `json:"space_type"`
} `json:"drive_spaces"`
DriveNotice string `json:"drive_notice"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.KnowledgeBases) != 1 || payload.Data.KnowledgeBases[0].Name != "ATOM知识库" {
t.Fatalf("knowledge bases = %+v", payload.Data.KnowledgeBases)
}
if len(payload.Data.DriveSpaces) != 1 || payload.Data.DriveSpaces[0].SpaceType != "orgSpace" {
t.Fatalf("drive spaces = %+v", payload.Data.DriveSpaces)
}
if payload.Data.DriveNotice == "" {
t.Fatal("drive notice should be relayed so the page can explain why 钉盘 is missing")
}
}
func TestListDingtalkSourcesHidesInternalErrors(t *testing.T) {
config := Config{DingtalkSources: fakeDingtalkSources{err: errors.New("internal detail: connection string leaked")}}
rec := httptest.NewRecorder()
listDingtalkSources(rec, dingtalkSourcesRequest(roleAdmin), config)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d", rec.Code)
}
if strings.Contains(rec.Body.String(), "connection string") {
t.Fatalf("internal error leaked: %s", rec.Body.String())
}
}
+6
View File
@@ -126,6 +126,9 @@ type Config struct {
ProductionBackupRestoreVerified bool
ProductionReleaseAuthorizerRef string
ProductionReleaseAuthorizationToken string
// DingtalkSources 枚举「我账号下能看到」的钉钉知识库与钉盘空间(只读,dws)。
// 未接线时对应路由返回 501,页面显示"列不出来"而不是空列表。
DingtalkSources dingtalkSourcesLister
NewID func() (string, error)
Auth *AuthConfig
}
@@ -348,6 +351,9 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/dingtalk-spaces", func(w http.ResponseWriter, r *http.Request) {
registerDingtalkSpace(w, r, config)
})
mux.HandleFunc("GET /api/v1/dingtalk-spaces/available", func(w http.ResponseWriter, r *http.Request) {
listDingtalkSources(w, r, config)
})
mux.HandleFunc("GET /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) {
getDingtalkSession(w, r)
})
+17
View File
@@ -0,0 +1,17 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { DingtalkSourceDiscovery } from './DingtalkSourceDiscovery'
describe('DingtalkSourceDiscovery', () => {
it('renders the discovery shell without any file-format filter', () => {
const html = renderToStaticMarkup(<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />)
for (const text of ['可加入的来源', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
expect(html).toContain(text)
}
// 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则']) {
expect(html).not.toContain(removed)
}
})
})
+137
View File
@@ -0,0 +1,137 @@
import { useCallback, useEffect, useState } from 'react'
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
import { DingtalkSessionControl } from './DingtalkSessionControl'
import { discoveryCandidates, fetchAvailableDingtalkSources, type AvailableDingtalkSources, type DiscoveryCandidate } from './dingtalkSources'
// 「系统设置 → 数据源配置」里的数据源发现面板(管理员):
// ① 列出当前钉钉账号(dws)能看到的钉钉知识库;
// ② 列出钉盘空间(我的文件 / 组织空间);
// ③ 勾选后加入为来源(登记走既有路径,首次目录扫描自动排队);
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { registeredNames: string[]; onRegistered: () => void }) {
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
const [loading, setLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
const [checked, setChecked] = useState<string[]>([])
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const [loginRequired, setLoginRequired] = useState(false)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true); setLoadError(null)
try {
const next = await fetchAvailableDingtalkSources(signal)
setList(next)
// 已登记的默认不再勾选:避免重复登记。
setChecked([])
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setLoadError(cause instanceof Error ? cause.message : '列举数据源失败')
setList(null)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load])
const candidates = discoveryCandidates(list, registeredNames)
const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base')
const driveSpaces = candidates.filter((item) => item.kind === 'drive_space')
const selected = candidates.filter((item) => checked.includes(item.key))
const toggle = (key: string) => setChecked((current) => current.includes(key) ? current.filter((item) => item !== key) : [...current, key])
const submit = async (retryAfterLogin = false) => {
setBusy(true); setFailure(null); setMessage(null)
const added: string[] = []
const failed: string[] = []
let needLogin = false
for (const candidate of selected) {
try {
const result = await registerDingtalkSpace(candidate.url)
added.push(result.name || candidate.name)
} catch (cause) {
// 扫码会话失效:登记本身没问题,直接弹二维码,扫完自动重试剩下的。
if (cause instanceof DingtalkRequestError && cause.code === 'login_required' && !retryAfterLogin) {
needLogin = true
break
}
failed.push(`${candidate.name}:${cause instanceof Error ? cause.message : '登记失败'}`)
}
}
setBusy(false)
if (needLogin) {
setLoginRequired(true)
setFailure('钉钉扫码会话已失效:请扫码登录,登录成功后会自动继续这次登记。')
return
}
if (added.length) {
setMessage(`已加入 ${added.length} 个来源:${added.join('、')}。首次目录扫描已在后台排队。`)
onRegistered()
void load()
}
if (failed.length) setFailure(failed.join(';'))
}
const resumeAfterLogin = () => {
setLoginRequired(false)
setFailure(null)
void submit(true)
}
const renderRow = (candidate: DiscoveryCandidate) => {
const already = candidate.alreadyRegistered
return <li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
<label>
<input type="checkbox" aria-label={`选择${candidate.name}`} checked={checked.includes(candidate.key)} disabled={already || busy} onChange={() => toggle(candidate.key)} />
<span><strong>{candidate.name}</strong><small>{candidate.detail}</small></span>
</label>
{already ? <span className="safe-badge">已是来源</span> : null}
</li>
}
return <section className="dingtalk-discovery" aria-label="可加入的数据源">
<div className="dingtalk-discovery-heading">
<div>
<strong>可加入的来源</strong>
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
</div>
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>{loading ? '正在列举…' : '刷新列表'}</button>
</div>
{loadError ? <p className="error-message" role="alert">{loadError}</p> : null}
{list ? <div className="dingtalk-discovery-groups">
<div className="discovery-group">
<h4>知识库({knowledgeBases.length})</h4>
{list.knowledge_notice ? <small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small> : null}
{knowledgeBases.length ? <ul>{knowledgeBases.map(renderRow)}</ul> : <small className="empty-inline">当前账号下没有可访问的知识库。</small>}
</div>
<div className="discovery-group">
<h4>钉盘({driveSpaces.length})</h4>
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
{!list.drive_notice && !driveSpaces.length ? <small className="empty-inline">当前账号下没有可见的钉盘空间。</small> : null}
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
</div>
</div> : null}
<div className="dingtalk-discovery-actions">
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}</button>
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
</div>
{message ? <p className="success-message" role="status">{message}</p> : null}
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
{loginRequired ? <DingtalkSessionControl
autoStart
hideTrigger
space={selected[0]?.url}
onSuccess={resumeAfterLogin}
onClose={() => setLoginRequired(false)}
/> : null}
</section>
}
+2
View File
@@ -29,6 +29,8 @@ describe('SystemSettingsView',()=>{
it('separates document-engineer settings from locked administrator and production controls',()=>{
const html=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
for(const text of ['系统设置','数据源配置','服务配置','存储与备份','刷新策略','设置服务已启用','当前活动版本','公司级技术支持知识库','钉钉知识库','认证方式','端点与凭据','文档工程师可调整','管理员设置已锁定'])expect(html).toContain(text)
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
for(const removed of ['文件格式筛选','未勾选的一律不取件','保存保留格式','恢复继承上级规则'])expect(html).not.toContain(removed)
const servicesHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
for(const text of ['测试 WeKnora','生产 WeKnora','测试地址','生产地址','生产 ID','知识库 ID'])expect(servicesHtml).toContain(text)
const storageHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="storage" />)
+2 -2
View File
@@ -6,7 +6,7 @@ import { DingtalkSessionControl } from './DingtalkSessionControl'
import { RoutingBindingsSection } from './RoutingBindingsSection'
import { ProductionBindingsSection } from './ProductionBindingsSection'
import { DingtalkSpaceRegistrar } from './DingtalkSpaceRegistrar'
import { FilenameFilterEditor } from './FilenameFilterEditor'
import { DingtalkSourceDiscovery } from './DingtalkSourceDiscovery'
import { useOptionalAuth } from './auth'
import { fetchMonitorOverview } from './monitor'
import type { MonitorOverview } from './monitor'
@@ -164,7 +164,6 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
: <div className="source-schedule-actions"><button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>保存并启用</button></div>}
{connection.source_type === "dingtalk" && isAdmin ? <DingtalkSessionControl /> : null}
<FilenameFilterEditor connectionID={connection.id} label="整个来源" onChanged={onSourcesChanged} />
<button className="link" onClick={() => void loadHistory()}>{showHistory ? '收起修订历史' : '查看修订历史'}</button>
</div>
{message ? <p className="success-message" role="status">{message}</p> : null}
@@ -237,6 +236,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
<div className="simulation-banner server-settings-banner"><strong>设置服务已启用</strong><span>当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。</span></div>
{section === 'sources' ? <section className="settings-panel wide source-settings-panel" id="settings-sources">
<div className="settings-section-heading"><div><h2>数据源配置</h2><p>逐来源设置自动刷新周期或保持仅手动;保存会先生成修订、验证后原子启用,旧版本保留用于审计。</p></div>{identity?.role === 'admin' ? <DingtalkSpaceRegistrar onRegistered={onSourcesChanged} /> : null}</div>
{identity?.role === 'admin' ? <DingtalkSourceDiscovery registeredNames={connections.map((item) => item.name)} onRegistered={onSourcesChanged} /> : null}
{connections.length ? <div className="settings-source-list">
{connections.map((connection) => <SourceSettingsCard key={connection.id} connection={connection} onSourcesChanged={onSourcesChanged}/>)}
{sources.length ? null : <small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>}
+72
View File
@@ -0,0 +1,72 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { discoveryCandidates, driveSpaceURL, fetchAvailableDingtalkSources } from './dingtalkSources'
const payload = {
data: {
knowledge_bases: [
{ name: 'ATOM知识库', space_id: '9JOGOQneRgkneX4Q', space_type: 'orgWikiSpace', url: 'https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview', description: '' },
{ name: '视觉文档', space_id: '9JOGO9EEOMLMWX4Q', space_type: 'orgWikiSpace', url: '', description: '2d/2.5D/3D 视觉' },
{ name: '我的文档', space_id: '9JOGOxeo90ybnz4Q', space_type: 'myWikiSpace', url: 'https://alidocs.dingtalk.com/i/spaces/9JOGOxeo90ybnz4Q/overview', description: '' },
],
drive_spaces: [
{ name: '我的文件', space_id: '28122692916', space_type: 'mySpace', root_folder_id: '65Y1OQX0' },
{ name: '全员文件夹', space_id: '102571304', space_type: 'orgSpace', root_folder_id: 'g1YGl6Pm' },
],
knowledge_notice: '',
drive_notice: '',
fetched_at: '2026-10-10T08:00:00Z',
},
}
afterEach(() => {
vi.unstubAllGlobals()
})
describe('fetchAvailableDingtalkSources', () => {
it('parses knowledge bases and drive spaces', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), { status: 200 })))
const list = await fetchAvailableDingtalkSources()
expect(list.knowledge_bases).toHaveLength(3)
expect(list.knowledge_bases[1].url).toBe('https://alidocs.dingtalk.com/i/spaces/9JOGO9EEOMLMWX4Q/overview')
expect(list.drive_spaces).toHaveLength(2)
expect(list.drive_spaces[1].space_type).toBe('orgSpace')
expect(list.knowledge_notice).toBe('')
expect(list.drive_notice).toBe('')
})
it('explains environment problems instead of pretending the list is empty', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('{"error":"dingtalk_discovery_unavailable"}', { status: 503 })))
await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/暂时列不出来/)
vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 501 })))
await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/后端未接线/)
vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 403 })))
await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/需要管理员身份/)
})
it('carries the drive notice so the page can explain a missing 钉盘 list', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: { knowledge_bases: [], drive_spaces: [], drive_notice: 'list orgSpace: permission denied' } }), { status: 200 })))
const list = await fetchAvailableDingtalkSources()
expect(list.drive_notice).toContain('permission denied')
})
})
describe('discoveryCandidates', () => {
it('flattens both groups and marks the ones already registered as sources', () => {
const candidates = discoveryCandidates(payload.data as never, ['ATOM知识库', ' (空名字) '])
expect(candidates.map((item) => item.key)).toEqual([
'kb:9JOGOQneRgkneX4Q', 'kb:9JOGO9EEOMLMWX4Q', 'kb:9JOGOxeo90ybnz4Q', 'drive:28122692916', 'drive:102571304',
])
expect(candidates[0].alreadyRegistered).toBe(true)
expect(candidates[1].alreadyRegistered).toBe(false)
expect(candidates[0].detail).toBe('钉钉知识库 · 组织知识库')
expect(candidates[2].detail).toBe('钉钉知识库 · 我的知识库')
expect(candidates[3].detail).toBe('钉盘 · 我的文件')
expect(candidates[4].detail).toBe('钉盘 · 组织空间')
expect(candidates[4].url).toBe(driveSpaceURL('102571304'))
})
it('returns nothing for an empty list', () => {
expect(discoveryCandidates(null, ['X'])).toEqual([])
})
})
+105
View File
@@ -0,0 +1,105 @@
// 「系统设置 → 数据源配置」的数据源发现客户端:列出当前 dws 账号能看到的钉钉知识库与钉盘空间。
// 只读;勾选后的登记仍走既有的 /api/v1/dingtalk-spaces(由扫码会话解析空间根目录)。
export interface AvailableKnowledgeBase {
name: string
space_id: string
space_type?: string
url: string
description?: string
}
export interface AvailableDriveSpace {
name: string
space_id: string
space_type: string
root_folder_id?: string
}
export interface AvailableDingtalkSources {
knowledge_bases: AvailableKnowledgeBase[]
drive_spaces: AvailableDriveSpace[]
/** 知识库这一类为什么不全(某类无权限、被上限截断)。 */
knowledge_notice?: string
/** 钉盘这一类为什么列不出来(租户权限差异)。 */
drive_notice?: string
fetched_at: string
}
// 钉盘空间的链接形态与知识库一致(空间 id 决定地址),勾选后按同一条登记路径提交。
export function driveSpaceURL(spaceID: string): string {
return `https://alidocs.dingtalk.com/i/spaces/${spaceID}/overview`
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promise<AvailableDingtalkSources> {
const response = await fetch('/api/v1/dingtalk-spaces/available', { headers: { Accept: 'application/json' }, signal })
if (!response.ok) {
// 503 是环境问题(dws 未登录/权限不足),501 是后端没接线:都要说清楚"不是没有来源"。
if (response.status === 503) throw new Error('暂时列不出来:dws 未登录或缺少租户目录读权限。先刷新钉钉会话,或让管理员检查 dws 凭据。')
if (response.status === 501) throw new Error('后端未接线:数据源发现接口不可用。')
if (response.status === 401 || response.status === 403) throw new Error('需要管理员身份才能列举数据源。')
throw new Error(`列举数据源失败(HTTP ${response.status})`)
}
const payload = await response.json() as unknown
const data = isRecord(payload) && isRecord(payload.data) ? payload.data : {}
const knowledgeBases = Array.isArray(data.knowledge_bases) ? data.knowledge_bases : []
const driveSpaces = Array.isArray(data.drive_spaces) ? data.drive_spaces : []
return {
knowledge_bases: knowledgeBases.flatMap((item) => {
if (!isRecord(item)) return []
const name = typeof item.name === 'string' ? item.name : ''
const spaceID = typeof item.space_id === 'string' ? item.space_id : ''
const url = typeof item.url === 'string' && item.url ? item.url : driveSpaceURL(spaceID)
const spaceType = typeof item.space_type === 'string' ? item.space_type : ''
return name && spaceID ? [{ name, space_id: spaceID, space_type: spaceType, url, description: typeof item.description === 'string' ? item.description : '' }] : []
}),
drive_spaces: driveSpaces.flatMap((item) => {
if (!isRecord(item)) return []
const name = typeof item.name === 'string' ? item.name : ''
const spaceID = typeof item.space_id === 'string' ? item.space_id : ''
const spaceType = typeof item.space_type === 'string' ? item.space_type : ''
return name && spaceID ? [{ name, space_id: spaceID, space_type: spaceType, root_folder_id: typeof item.root_folder_id === 'string' ? item.root_folder_id : '' }] : []
}),
knowledge_notice: typeof data.knowledge_notice === 'string' ? data.knowledge_notice : '',
drive_notice: typeof data.drive_notice === 'string' ? data.drive_notice : '',
fetched_at: typeof data.fetched_at === 'string' ? data.fetched_at : '',
}
}
export interface DiscoveryCandidate {
key: string
kind: 'knowledge_base' | 'drive_space'
name: string
spaceID: string
url: string
detail: string
alreadyRegistered: boolean
}
// 把发现结果拍平成可勾选列表:已登记(按空间名比对来源连接名)的条目打标,页面据此禁用勾选,
// 避免重复登记。
export function discoveryCandidates(list: AvailableDingtalkSources | null, registeredNames: string[]): DiscoveryCandidate[] {
const registered = new Set(registeredNames.map((name) => name.trim()).filter(Boolean))
const knowledgeBases = (list?.knowledge_bases ?? []).map((item): DiscoveryCandidate => ({
key: `kb:${item.space_id}`,
kind: 'knowledge_base',
name: item.name,
spaceID: item.space_id,
url: item.url || driveSpaceURL(item.space_id),
detail: item.space_type === 'myWikiSpace' ? '钉钉知识库 · 我的知识库' : '钉钉知识库 · 组织知识库',
alreadyRegistered: registered.has(item.name.trim()),
}))
const driveSpaces = (list?.drive_spaces ?? []).map((item): DiscoveryCandidate => ({
key: `drive:${item.space_id}`,
kind: 'drive_space',
name: item.name,
spaceID: item.space_id,
url: driveSpaceURL(item.space_id),
detail: item.space_type === 'mySpace' ? '钉盘 · 我的文件' : '钉盘 · 组织空间',
alreadyRegistered: registered.has(item.name.trim()),
}))
return [...knowledgeBases, ...driveSpaces]
}
+17
View File
@@ -45,3 +45,20 @@ button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-d
.filename-filter-group>div{display:flex;flex-wrap:wrap;gap:4px}.filename-filter-group button{border:1px solid var(--border-base);background:var(--bg-panel);color:var(--ink-base);border-radius:999px;padding:2px 8px;font-size:10px;font-family:inherit;cursor:pointer}
.filename-filter-group button.picked{background:var(--c-run);border-color:var(--c-run);color:var(--bg-panel);font-weight:650}.filename-filter-group button.blocked{color:var(--c-fail)}
@media(max-width:900px){.filename-filter-groups{grid-template-columns:1fr 1fr}}
/* 数据源发现(系统设置 → 数据源配置):列出可勾选为来源的钉钉知识库与钉盘空间。 */
.dingtalk-discovery { display: flex; flex-direction: column; gap: 10px; padding: 12px; margin-bottom: 14px; border: 1px solid var(--border, #e3e8ec); border-radius: 10px; background: var(--card, #fff); }
.dingtalk-discovery-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.dingtalk-discovery-heading strong { display: block; font-size: 14px; }
.dingtalk-discovery-heading small { display: block; color: var(--muted-foreground, #5b6773); font-size: 12px; }
.dingtalk-discovery-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.discovery-group h4 { margin: 0 0 6px; font-size: 13px; }
.discovery-group ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 220px; overflow: auto; }
.discovery-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 6px; border-radius: 6px; }
.discovery-row:hover { background: var(--accent, #f2f5f8); }
.discovery-row label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.discovery-row.registered label { cursor: default; color: var(--muted-foreground, #5b6773); }
.discovery-row strong { font-size: 13px; font-weight: 500; }
.discovery-row small { display: block; font-size: 11px; color: var(--muted-foreground, #5b6773); }
.dingtalk-discovery-actions { display: flex; align-items: center; gap: 10px; }
.dingtalk-discovery-actions small { color: var(--muted-foreground, #5b6773); font-size: 12px; }