Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ec7bbdc20 | |||
| 371d8a60a0 | |||
| bceb7ba682 | |||
| c1bdbe181e | |||
| 5798183392 | |||
| 7567159dc0 |
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.427(导入对账:平台 Key 自动带工作空间)
|
||||
|
||||
### Added
|
||||
|
||||
- **WeKnora 客户端支持平台 Key**:绑定页保存的 Key 若是 platform scope,上游的租户接口会回 `409 TENANT_REQUIRED`;客户端此时用同一把 Key 查 `/api/v1/tenants/all`,按工作空间逐个重试原请求,成功后缓存 ID 并在后续请求带上 `X-Tenant-ID`。租户 Key 不触发该路径,行为不变;JSON 请求体在重试时会被重放(上限 1 MiB),上传流式接口不走这条路径。
|
||||
- 覆盖三种情形:平台 Key 首次拒绝后重放成功、租户 Key 从不发 `X-Tenant-ID`、普通 409(上传冲突)不被误判成 `TENANT_REQUIRED`。
|
||||
|
||||
### Changed
|
||||
|
||||
- **为什么需要这一步**:WeKnora v0.9.1 把 `/api/v1/system/admin/runtime/*` 声明为 `apiKeyPlatform`,网关在能力判定之前就拒绝租户 Key,`system_runtime_read` 授给租户 Key 也无效。要想「运行时读与对账共用一把 Key」,绑定里必须是平台 Key,而平台 Key 访问租户资源必须点名工作空间。
|
||||
- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7:写清平台 Key 约束、工作空间自动识别,以及建议的最小能力集。
|
||||
|
||||
## 开发快照 0.1.426(导入对账:运行时读复用知识库绑定 Key)
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -118,12 +118,15 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
|
||||
|
||||
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
|
||||
|
||||
**运行时读 Key 的配置契约(Q7,2026-12-02 改判)**
|
||||
**运行时读 Key 的配置契约(Q7,2026-12-02 改判,同日修正)**
|
||||
|
||||
- 不再单独维护平台级只读 Key:「导入对账」的 `runtime/queues` 与 `runtime/documents/{id}`(以及页面上的「WeKnora 处理详情」)直接使用「系统设置 → 知识库绑定」测试环境保存的地址与 Key,与对账扫描共用同一个 resolver。
|
||||
- **绑定里的 Key 必须是平台 Key**:WeKnora v0.9.1 的 `/api/v1/system/admin/runtime/*` 由 `apiKeyPlatform` 声明为 `PlatformOnly`,`internal/middleware/api_key_gate.go` 在能力判定之前就先拒绝非 platform scope 的 Key,所以租户 Key 即使授予 `system_runtime_read` 也会得到 403。改动前实测:租户 Key 打 queues 403、打 `knowledge-bases` 200;平台 Key 反之。
|
||||
- **平台 Key 访问租户资源要带工作空间**:缺少 `X-Tenant-ID` 时上游返回 `409 TENANT_REQUIRED`。平台在首次遇到该响应时用同一把 Key 请求 `/api/v1/tenants/all`,按返回的工作空间逐个重试原请求,成功后缓存该 ID 并在后续请求带上 `X-Tenant-ID`;租户 Key 不会触发这条路径,行为与之前一致。
|
||||
- 绑定 Key 建议按最小权限配置(`system_runtime_read` + `retrieve`,需要列库时再加 `manage_kbs`),不要保存带租户管理/写能力的全权限 Key。
|
||||
- 每次请求解析绑定;管理员换 Key 保存后,下一次请求即生效,不需要重启 API。不再读取任何 Key 文件。
|
||||
- 绑定未配置或无法解密 → 503 `runtime_read_unavailable`,页面指向绑定页;上游 401/403 → 502 `runtime_key_forbidden`,页面提示去 WeKnora 授权 `system_runtime_read`;连接或运行时读失败 → 502 `runtime_unreachable`,页面提示连不上 WeKnora。
|
||||
- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身(对账只用租户 Key 列库与读单条)。
|
||||
- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身。
|
||||
|
||||
## 6. 运行方式
|
||||
|
||||
|
||||
@@ -161,6 +161,9 @@ FROM test_publications p
|
||||
JOIN source_item_versions version ON version.id=p.source_item_version_id
|
||||
JOIN source_items item ON item.id=version.source_item_id
|
||||
LEFT JOIN removal_candidates removal_candidate ON removal_candidate.publication_id=p.id
|
||||
-- 整库都被顶替过的 KB 只剩历史行:不排除就仍会占一行「0 条」,
|
||||
-- 还会出现在导入对账的库下拉里,点下去直接打在已删除的库上。
|
||||
WHERE p.superseded_at IS NULL
|
||||
GROUP BY p.test_kb_id
|
||||
ORDER BY p.test_kb_id`)
|
||||
if err != nil {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -102,6 +103,13 @@ type Client struct {
|
||||
apiKey string
|
||||
httpClient *http.Client
|
||||
maxResponseBytes int64
|
||||
|
||||
// tenantMu guards tenantID: a platform-scoped key must name the workspace
|
||||
// it acts on (X-Tenant-ID), so the first call that is refused with
|
||||
// TENANT_REQUIRED discovers the workspace once and every later call reuses
|
||||
// it. Tenant keys never trigger this path.
|
||||
tenantMu sync.Mutex
|
||||
tenantID string
|
||||
}
|
||||
|
||||
func NewClient(config ClientConfig) (*Client, error) {
|
||||
@@ -446,25 +454,140 @@ func (c *Client) doJSON(ctx context.Context, method, path string, body io.Reader
|
||||
return c.doJSONQuery(ctx, method, path, nil, body, target)
|
||||
}
|
||||
|
||||
// maxJSONRequestBody bounds the buffered request body a retry can replay.
|
||||
// Every JSON call here carries a small filter object; uploads stream through
|
||||
// UploadFile and never reach this path.
|
||||
const maxJSONRequestBody int64 = 1 << 20
|
||||
|
||||
func (c *Client) doJSONQuery(ctx context.Context, method, path string, query url.Values, body io.Reader, target any) error {
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
read, err := io.ReadAll(io.LimitReader(body, maxJSONRequestBody+1))
|
||||
if err != nil {
|
||||
return errors.New("read WeKnora request body")
|
||||
}
|
||||
if int64(len(read)) > maxJSONRequestBody {
|
||||
return errors.New("WeKnora request body exceeds size limit")
|
||||
}
|
||||
payload = read
|
||||
}
|
||||
response, err := c.send(ctx, method, path, query, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tenantRequired(response) {
|
||||
// A platform-scoped key is refused until it names its workspace. The
|
||||
// binding page stores whichever key the operator saved, so discover the
|
||||
// workspace from the same key instead of asking for a second setting.
|
||||
tenants, err := c.platformTenants(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, tenant := range tenants {
|
||||
c.rememberTenant(tenant)
|
||||
response, err = c.send(ctx, method, path, query, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !tenantRequired(response) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if response.status < 200 || response.status >= 300 {
|
||||
return &HTTPError{StatusCode: response.status}
|
||||
}
|
||||
if err := json.Unmarshal(response.body, target); err != nil {
|
||||
return errors.New("decode WeKnora response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
status int
|
||||
body []byte
|
||||
}
|
||||
|
||||
// send performs one request with the currently known workspace header.
|
||||
func (c *Client) send(ctx context.Context, method, path string, query url.Values, payload []byte) (*rawResponse, error) {
|
||||
endpoint := c.endpoint(path)
|
||||
if len(query) > 0 {
|
||||
endpoint += "?" + query.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
|
||||
var reader io.Reader
|
||||
if payload != nil {
|
||||
reader = bytes.NewReader(payload)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, reader)
|
||||
if err != nil {
|
||||
return errors.New("create WeKnora request")
|
||||
return nil, errors.New("create WeKnora request")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
if tenant := c.currentTenant(); tenant != "" {
|
||||
req.Header.Set("X-Tenant-ID", tenant)
|
||||
}
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send WeKnora request: %w", err)
|
||||
return nil, fmt.Errorf("send WeKnora request: %w", err)
|
||||
}
|
||||
return c.decodeResponse(resp, target)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, errors.New("read WeKnora response")
|
||||
}
|
||||
if int64(len(body)) > c.maxResponseBytes {
|
||||
return nil, errors.New("WeKnora response exceeds size limit")
|
||||
}
|
||||
return &rawResponse{status: resp.StatusCode, body: body}, nil
|
||||
}
|
||||
|
||||
// tenantRequired reports WeKnora's 409 TENANT_REQUIRED refusal, which is
|
||||
// distinct from an upload conflict despite sharing the status code.
|
||||
func tenantRequired(response *rawResponse) bool {
|
||||
return response != nil && response.status == http.StatusConflict &&
|
||||
bytes.Contains(response.body, []byte(`"TENANT_REQUIRED"`))
|
||||
}
|
||||
|
||||
// platformTenants lists the workspaces a platform-scoped key may act on. The
|
||||
// route is tenant-optional, so it answers before any workspace is known.
|
||||
func (c *Client) platformTenants(ctx context.Context) ([]string, error) {
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Items []struct {
|
||||
ID uint64 `json:"id"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/tenants/all", nil, nil, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenants := make([]string, 0, len(response.Data.Items))
|
||||
for _, item := range response.Data.Items {
|
||||
if item.ID != 0 {
|
||||
tenants = append(tenants, fmt.Sprint(item.ID))
|
||||
}
|
||||
}
|
||||
if len(tenants) == 0 {
|
||||
return nil, errors.New("WeKnora platform key has no workspace to act on")
|
||||
}
|
||||
return tenants, nil
|
||||
}
|
||||
|
||||
func (c *Client) currentTenant() string {
|
||||
c.tenantMu.Lock()
|
||||
defer c.tenantMu.Unlock()
|
||||
return c.tenantID
|
||||
}
|
||||
|
||||
func (c *Client) rememberTenant(tenant string) {
|
||||
c.tenantMu.Lock()
|
||||
defer c.tenantMu.Unlock()
|
||||
c.tenantID = tenant
|
||||
}
|
||||
|
||||
func (c *Client) decodeResponse(resp *http.Response, target any) error {
|
||||
|
||||
@@ -469,3 +469,99 @@ func TestClientClassifiesTimeoutAsRetryable(t *testing.T) {
|
||||
t.Fatalf("GetKnowledge() error = %v, want retryable timeout", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A platform-scoped key is refused with TENANT_REQUIRED until it names a
|
||||
// workspace. The client must discover that workspace with the same key and
|
||||
// replay the call, then reuse the header for later calls.
|
||||
func TestClientResolvesWorkspaceForPlatformKey(t *testing.T) {
|
||||
const apiKey = "platform" + "-key"
|
||||
var listCalls, tenantCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/tenants/all":
|
||||
tenantCalls.Add(1)
|
||||
if got := r.Header.Get("X-API-Key"); got != apiKey {
|
||||
t.Fatalf("tenants X-API-Key = %q", got)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000,"name":"workspace"}]}}`))
|
||||
case "/api/v1/knowledge-bases":
|
||||
listCalls.Add(1)
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required: platform API keys must send X-Tenant-ID"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`))
|
||||
case "/api/v1/knowledge/knowledge-1":
|
||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"completed"}}`))
|
||||
default:
|
||||
t.Fatalf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bases, err := client.ListKnowledgeBases(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListKnowledgeBases() error = %v", err)
|
||||
}
|
||||
if len(bases) != 1 || bases[0].ID != "kb-1" {
|
||||
t.Fatalf("bases = %#v", bases)
|
||||
}
|
||||
if _, err := client.GetKnowledge(context.Background(), "knowledge-1"); err != nil {
|
||||
t.Fatalf("GetKnowledge() after discovery error = %v", err)
|
||||
}
|
||||
if tenantCalls.Load() != 1 {
|
||||
t.Fatalf("tenant discovery calls = %d, want 1", tenantCalls.Load())
|
||||
}
|
||||
if listCalls.Load() != 2 {
|
||||
t.Fatalf("knowledge-base calls = %d, want 2 (refused + replay)", listCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A tenant key never sends X-Tenant-ID and never asks for the workspace list.
|
||||
func TestClientTenantKeyNeverSendsWorkspaceHeader(t *testing.T) {
|
||||
const apiKey = "tenant" + "-key"
|
||||
var tenantCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/tenants/all" {
|
||||
tenantCalls.Add(1)
|
||||
t.Fatalf("tenant key must not query the workspace list")
|
||||
}
|
||||
if got := r.Header.Get("X-Tenant-ID"); got != "" {
|
||||
t.Fatalf("X-Tenant-ID = %q, want empty for a tenant key", got)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[{"id":"kb-1","name":"测试库","knowledge_count":1,"chunk_count":2,"tenant_id":10000}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.ListKnowledgeBases(context.Background()); err != nil {
|
||||
t.Fatalf("ListKnowledgeBases() error = %v", err)
|
||||
}
|
||||
if tenantCalls.Load() != 0 {
|
||||
t.Fatalf("tenant discovery calls = %d", tenantCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not
|
||||
// treated as a workspace refusal.
|
||||
func TestTenantRequiredIgnoresPlainConflict(t *testing.T) {
|
||||
if tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"error":"already exists"}`)}) {
|
||||
t.Fatal("plain 409 must not be classified as TENANT_REQUIRED")
|
||||
}
|
||||
if !tenantRequired(&rawResponse{status: http.StatusConflict, body: []byte(`{"code":"TENANT_REQUIRED"}`)}) {
|
||||
t.Fatal("TENANT_REQUIRED 409 must be classified")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -42,6 +43,14 @@ func RuntimeErrorCode(err error) string {
|
||||
}
|
||||
}
|
||||
|
||||
// knowledgeBaseMissing 只认 WeKnora 明确回答的 404 —— 库被删掉、或 ID 属于
|
||||
// 别的环境/租户。它与网络不通、Key 无权限要分开:这三种情况的处置完全不同,
|
||||
// 页面把 404 说成「检查地址与 Key」会让工程师去改一个根本没坏的配置。
|
||||
func knowledgeBaseMissing(err error) bool {
|
||||
var httpErr *weknora.HTTPError
|
||||
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
||||
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
||||
@@ -268,6 +277,9 @@ func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
|
||||
}
|
||||
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
|
||||
if err != nil {
|
||||
if knowledgeBaseMissing(err) {
|
||||
return finished("remote_kb_missing")
|
||||
}
|
||||
return finished("remote_unavailable")
|
||||
}
|
||||
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
|
||||
|
||||
@@ -145,6 +145,7 @@ type fakeReconciliationRemote struct {
|
||||
missing map[string]bool
|
||||
gets map[string]weknora.Knowledge
|
||||
listErr error
|
||||
beginErr error
|
||||
pageSizes []int
|
||||
deleteCalls int
|
||||
listInFlight int
|
||||
@@ -152,6 +153,9 @@ type fakeReconciliationRemote struct {
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
|
||||
if f.beginErr != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, f.beginErr
|
||||
}
|
||||
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
|
||||
}
|
||||
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
|
||||
@@ -395,6 +399,24 @@ func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowl
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
|
||||
// 库被删掉时,远端回的是 404,不是网络故障。批次必须落成 remote_kb_missing,
|
||||
// 页面才能提示「去选当前绑定的库」,而不是让人去改没坏的地址与 Key。
|
||||
func TestExecuteRunReportsMissingKnowledgeBase(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-gone", State: "running", StartedAt: now}}
|
||||
remote := &fakeReconciliationRemote{beginErr: &weknora.HTTPError{StatusCode: 404}}
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if store.failCode != "remote_kb_missing" {
|
||||
t.Fatalf("fail code = %q", store.failCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// @vitest-environment jsdom
|
||||
// 右侧抽屉(原生 <dialog>)必须能用三条路收回:关闭按钮、Esc、点抽屉外面。
|
||||
// 这条用例专门盯第三条:内容比视口长时按钮会被滚走,只剩点外面能救场;
|
||||
// 同时要保证点抽屉内部(含内边距)不会误关。
|
||||
import { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import type { Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { FindingDetail } from './ReconciliationFindings'
|
||||
import type { ReconciliationFinding } from './reconciliationApi'
|
||||
|
||||
const finding: ReconciliationFinding = {
|
||||
id: 'f1',
|
||||
run_id: 'run-1',
|
||||
type: 'R3',
|
||||
publication_id: 'tp-1',
|
||||
document_id: '',
|
||||
title: '线总览.md',
|
||||
path: '产品/说明书',
|
||||
source: '钉盘',
|
||||
target_scope: 'internal',
|
||||
ledger_state: 'completed',
|
||||
weknora_parse_status: '',
|
||||
normalized_state: 'completed',
|
||||
ledger_sha256: 'deadbeef',
|
||||
declared_sha256: 'deadbeef',
|
||||
weknora_file_md5: 'deadbeef',
|
||||
evidence_level: 'none',
|
||||
confirmation_state: 'confirmed',
|
||||
detail: '非平台导入条目,仅统计',
|
||||
suggested_action: 'none',
|
||||
action_state: 'open',
|
||||
weknora_url: '',
|
||||
}
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
|
||||
beforeEach(() => {
|
||||
const reactTestGlobal: { IS_REACT_ACT_ENVIRONMENT: boolean } = globalThis as unknown as {
|
||||
IS_REACT_ACT_ENVIRONMENT: boolean
|
||||
}
|
||||
reactTestGlobal.IS_REACT_ACT_ENVIRONMENT = true
|
||||
// jsdom 没有实现 dialog 的模态方法。
|
||||
HTMLDialogElement.prototype.showModal = function showModal(this: HTMLDialogElement) {
|
||||
this.open = true
|
||||
}
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
})
|
||||
|
||||
const renderDrawer = async () => {
|
||||
const onClose = vi.fn()
|
||||
await act(async () => root.render(<FindingDetail finding={finding} onClose={onClose} />))
|
||||
const dialog = container.querySelector('dialog')
|
||||
if (!dialog) throw new Error('抽屉没有渲染出来')
|
||||
// 抽屉贴在视口右侧:x 800–1280、y 0–694。
|
||||
dialog.getBoundingClientRect = () =>
|
||||
({
|
||||
left: 800,
|
||||
right: 1280,
|
||||
top: 0,
|
||||
bottom: 694,
|
||||
width: 480,
|
||||
height: 694,
|
||||
x: 800,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect
|
||||
return { onClose, dialog }
|
||||
}
|
||||
|
||||
const click = async (target: Element, clientX: number, clientY: number) => {
|
||||
await act(async () => {
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, clientX, clientY }))
|
||||
})
|
||||
}
|
||||
|
||||
describe('reconciliation finding drawer', () => {
|
||||
it('closes when the backdrop is clicked', async () => {
|
||||
const { onClose, dialog } = await renderDrawer()
|
||||
await click(dialog, 200, 300)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('stays open when the drawer body is clicked', async () => {
|
||||
const { onClose, dialog } = await renderDrawer()
|
||||
await click(dialog, 1000, 400)
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
} from './reconciliationApi'
|
||||
import { fetchReconciliationProgress } from './reconciliationApi'
|
||||
import { reconciliationErrorText, reconciliationFailureText, reconciliationStageText } from './reconciliationMessages'
|
||||
import { onBackdropClick } from './dialogBackdrop'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const time = (value: string | null | undefined) =>
|
||||
@@ -441,7 +442,7 @@ export function FindingDetail({ finding, onClose }: { finding: ReconciliationFin
|
||||
ref.current?.showModal()
|
||||
}, [])
|
||||
return (
|
||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
|
||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose} onClick={onBackdropClick(ref, onClose)}>
|
||||
<header>
|
||||
<h2>{typeLabels[finding.type]} · 处理详情</h2>
|
||||
<button onClick={onClose} autoFocus>
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from './reconciliationApi'
|
||||
import type { ReconciliationFinding, ReconciliationFindingPage, ReconciliationRunPage } from './reconciliationApi'
|
||||
import { isTestBindingMissing, reconciliationErrorText, reconciliationMessages } from './reconciliationMessages'
|
||||
import { onBackdropClick } from './dialogBackdrop'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const emptyRuns: ReconciliationRunPage = { items: [], total: 0, limit: 20, offset: 0 }
|
||||
@@ -522,7 +523,7 @@ export function TaskDetail({
|
||||
ref.current?.showModal()
|
||||
}, [])
|
||||
return (
|
||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
|
||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose} onClick={onBackdropClick(ref, onClose)}>
|
||||
<header>
|
||||
<h2>文件处理详情</h2>
|
||||
<button onClick={onClose} autoFocus>
|
||||
@@ -606,6 +607,12 @@ export function WeKnoraMonitor({
|
||||
const [findingFilters, setFindingFilters] = useState<FindingFilters>({ type: '', q: '' })
|
||||
const [findingOffset, setFindingOffset] = useState(0)
|
||||
const [selectedKB, setSelectedKB] = useState('')
|
||||
// 下拉里的候选来自台账(test_publications.test_kb_id),可能包含早已被删掉的
|
||||
// 测试库。默认值必须落在「当前绑定的测试库」上,否则一进页面点立即对账就会
|
||||
// 打在死库上,远端只回 404。
|
||||
const [boundKB, setBoundKB] = useState('')
|
||||
const [bindingReady, setBindingReady] = useState(false)
|
||||
const kbPickedRef = useRef(false)
|
||||
const [findingDetail, setFindingDetail] = useState<ReconciliationFinding | null>(null)
|
||||
const [reconLoading, setReconLoading] = useState(true)
|
||||
const [reconBusy, setReconBusy] = useState(false)
|
||||
@@ -727,9 +734,10 @@ export function WeKnoraMonitor({
|
||||
return () => c.abort()
|
||||
}, [resRev])
|
||||
useEffect(() => {
|
||||
if (selectedKB || !overview?.knowledge_bases.length) return
|
||||
setSelectedKB(overview.knowledge_bases[0].id)
|
||||
}, [overview, selectedKB])
|
||||
if (kbPickedRef.current || !bindingReady || !overview?.knowledge_bases.length) return
|
||||
const ids = overview.knowledge_bases.map((item) => item.id)
|
||||
setSelectedKB(boundKB && ids.includes(boundKB) ? boundKB : ids[0])
|
||||
}, [overview, bindingReady, boundKB])
|
||||
// 绑定快照与批次列表分开取:批次列表成功会清空 reconError,不能把
|
||||
// 「测试环境未配置」也塞进同一个 state,否则一刷新就消失。
|
||||
useEffect(() => {
|
||||
@@ -738,12 +746,17 @@ export function WeKnoraMonitor({
|
||||
void fetchKBBindings(c.signal)
|
||||
.then((snapshot) => {
|
||||
if (!c.signal.aborted) {
|
||||
setBoundKB(snapshot.test.internal_kb_id)
|
||||
setBindingReady(true)
|
||||
setBindingError(isTestBindingMissing(snapshot) ? reconciliationMessages.bindingMissing : '')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// 预检失败不阻塞页面:真正触发时仍由批次错误兜底。
|
||||
if (!c.signal.aborted) setBindingError('')
|
||||
if (!c.signal.aborted) {
|
||||
setBindingReady(true)
|
||||
setBindingError('')
|
||||
}
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [tab, reconRev])
|
||||
@@ -954,7 +967,10 @@ export function WeKnoraMonitor({
|
||||
filters={findingFilters}
|
||||
selectedRunID={selectedRunID}
|
||||
selectedKB={selectedKB}
|
||||
kbOptions={(overview?.knowledge_bases || []).map((item) => ({ id: item.id, name: item.name }))}
|
||||
kbOptions={(overview?.knowledge_bases || []).map((item) => ({
|
||||
id: item.id,
|
||||
name: item.id === boundKB ? `${item.name}(当前绑定)` : item.name,
|
||||
}))}
|
||||
loading={reconLoading}
|
||||
busy={reconBusy}
|
||||
canOperate={canOperate}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// 原生 <dialog> 的 ::backdrop 点击会派发到 dialog 元素本身,但浏览器不会自动关闭它,
|
||||
// 于是右侧抽屉一打开就只能靠「关闭」按钮或 Esc 收回;内容比视口长时按钮还会被滚走。
|
||||
// 这里按坐标判断:落在 dialog 矩形外的点击才关闭(dialog 自己的内边距仍算内部,
|
||||
// 不能因为点在内边距上就把抽屉关掉)。
|
||||
export function onBackdropClick(
|
||||
ref: { current: HTMLDialogElement | null },
|
||||
close: () => void
|
||||
): (event: { clientX: number; clientY: number }) => void {
|
||||
return (event) => {
|
||||
const dialog = ref.current
|
||||
if (!dialog) return
|
||||
const rect = dialog.getBoundingClientRect()
|
||||
const inside =
|
||||
event.clientX >= rect.left &&
|
||||
event.clientX <= rect.right &&
|
||||
event.clientY >= rect.top &&
|
||||
event.clientY <= rect.bottom
|
||||
if (!inside) close()
|
||||
}
|
||||
}
|
||||
@@ -434,7 +434,9 @@
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-left: 1px solid var(--border-base);
|
||||
padding: 25px;
|
||||
/* 顶部的内边距交给 sticky 的 header:抽屉内容比视口长时,
|
||||
「关闭」必须一直留在可见区,不能被滚走。 */
|
||||
padding: 0 25px 25px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
overflow: auto;
|
||||
@@ -448,6 +450,12 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
/* 长内容滚动时「关闭」不离屏:吸顶 + 盖住底下滚过的行 */
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
padding: 25px 0 12px;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.monitor-drawer h2 {
|
||||
font-size: 19px;
|
||||
|
||||
@@ -41,6 +41,12 @@ describe('reconciliation error copy', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('distinguishes a deleted knowledge base from a broken binding', () => {
|
||||
expect(reconciliationFailureText('remote_kb_missing')).toBe(reconciliationMessages.remoteKBMissing)
|
||||
expect(reconciliationFailureText('remote_unavailable')).toBe(reconciliationMessages.remoteFailed)
|
||||
expect(reconciliationMessages.remoteKBMissing).not.toBe(reconciliationMessages.remoteFailed)
|
||||
})
|
||||
|
||||
it('falls back to Chinese for an unknown code instead of echoing it', () => {
|
||||
expect(reconciliationFailureText('some_new_code')).toBe(reconciliationMessages.generic)
|
||||
expect(reconciliationFailureText('some_new_code')).not.toContain('some_new_code')
|
||||
|
||||
@@ -13,6 +13,7 @@ export const reconciliationMessages = {
|
||||
runInProgress: '该测试知识库已有对账批次在运行,请等本轮结束后再试',
|
||||
stateChanged: '记录状态已变化,请刷新后重试',
|
||||
remoteFailed: '测试知识库连接失败:请检查系统设置 → 知识库绑定中的测试环境地址与 Key',
|
||||
remoteKBMissing: '所选测试知识库在 WeKnora 中已不存在(可能已被删除),请改选当前绑定的测试库',
|
||||
queueUnavailable: '对账任务队列不可用,请联系管理员',
|
||||
ledgerUnavailable: '台账读取失败,请稍后重试或联系管理员',
|
||||
overlapCheckFailed: '无法确认整库作业状态,请稍后重试',
|
||||
@@ -27,6 +28,7 @@ const failureMessages: Record<string, string> = {
|
||||
reconciliation_not_configured: reconciliationMessages.notEnabled,
|
||||
reconciliation_failed: reconciliationMessages.generic,
|
||||
reconciliation_remote_failed: reconciliationMessages.remoteFailed,
|
||||
remote_kb_missing: reconciliationMessages.remoteKBMissing,
|
||||
remote_unavailable: reconciliationMessages.remoteFailed,
|
||||
remote_scan_failed: reconciliationMessages.remoteFailed,
|
||||
remote_confirm_failed: reconciliationMessages.remoteFailed,
|
||||
|
||||
Reference in New Issue
Block a user