feat(qaops): 完成流水表六项体验与AI执行修正
统一AI分析入口及双任务安全确认,采用全量载入的可见行渲染,保留完整原文。 右侧非模态详情固定五项质量字段,清理冗余展示并对齐查询和同步按钮。 默认4并发由数据库准入与逐任务租约保护,保留共享限流冷却、截断归因和有界重试。 兼容真实引用标题字段,不伪造证据或准确率,不修改源生产问答与公司区域规则。 验证:完整make verify退出0,710项Go通过、124项已声明可选跳过且必需0跳过; 另全量mirror隔离PostgreSQL race退出0,AI单元race退出0。 真实本地浏览器通过六项交互、390px内滚动及显式AI部分失败/零缺口故障夹具。 治理原生备份已真实恢复,schema57、72表计数与29张QA内容哈希一致。 候选镜像、精确提交CI与正式上线验收待本次提交后执行,不宣称已部署。
This commit is contained in:
@@ -76,6 +76,20 @@
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.39 - 2026-10-19
|
||||
|
||||
### Changed
|
||||
|
||||
- “问题流水”改为“问题流水表”;详情从右侧非模态弹出,不再生成左侧遮罩或焦点陷阱。移除详情中的区域、组织关联/版本/快照、记录来源、问答状态与流程触发人员展示,原始数据与审计不删除。
|
||||
- 是否覆盖、是否正确、产品分类、问题类型、根因分析置于详情顶部固定区域,正文独立滚动;查询与立即同步统一尺寸和基线。
|
||||
- 字段评估与中文翻译统一为“AI分析”,分别预览缺口、确认后按实际需要创建两类持久任务;部分成功重试保留幂等标识,跳过已确认种类与零缺口种类,不覆盖人工或已有非空结论。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 大流水表保留全量载入与无分页滚动,改为仅渲染可见行和缓冲行、稳定行引用及固定列宽;列表长文本限预览,详情与导出仍取完整原文,重复后台状态不再驱动整表刷新。
|
||||
- AI执行改为数据库准入控制的默认4并发、独立任务租约与过期栅栏;慢模型调用不阻塞其他工作槽或自动扫描。429遵守共享有界冷却;输出截断单独归因,最多三次有界重试并逐次扩大输出预算,最终失败保留可见状态。
|
||||
- 兼容源引用的knowledge_title字段,不将只有标题的引用伪造为正文证据;证据不足仍待确认,不将模型自报置信度当作准确率。修正人工复核区仍声称AI未接入的旧提示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.38 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -18,8 +19,9 @@ var ErrInvalid = errors.New("qa_ai_invalid_request")
|
||||
var ErrConflict = errors.New("qa_ai_version_conflict")
|
||||
|
||||
type RemoteError struct {
|
||||
Code string
|
||||
Retryable bool
|
||||
RetryAfter time.Duration
|
||||
Code string
|
||||
Retryable bool
|
||||
}
|
||||
|
||||
func (e *RemoteError) Error() string { return "qa_ai_" + e.Code }
|
||||
@@ -75,7 +77,21 @@ func (c Client) Call(ctx context.Context, base, model, key, system string, input
|
||||
case response.StatusCode >= 300 && response.StatusCode < 400:
|
||||
code = "redirect_rejected"
|
||||
}
|
||||
return Completion{}, &RemoteError{Code: code, Retryable: retry}
|
||||
var delay time.Duration
|
||||
if code == "rate_limited" {
|
||||
if seconds, e := strconv.Atoi(response.Header.Get("Retry-After")); e == nil && seconds > 0 {
|
||||
delay = time.Duration(seconds) * time.Second
|
||||
} else if date, e := http.ParseTime(response.Header.Get("Retry-After")); e == nil {
|
||||
delay = time.Until(date)
|
||||
}
|
||||
if delay < 15*time.Second {
|
||||
delay = 15 * time.Second
|
||||
}
|
||||
if delay > 120*time.Second {
|
||||
delay = 120 * time.Second
|
||||
}
|
||||
}
|
||||
return Completion{}, &RemoteError{Code: code, Retryable: retry, RetryAfter: delay}
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(response.Body, (4<<20)+1))
|
||||
if err != nil || len(raw) > 4<<20 {
|
||||
@@ -90,8 +106,11 @@ func (c Client) Call(ctx context.Context, base, model, key, system string, input
|
||||
FinishReason string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
if json.Unmarshal(raw, &result) == nil && len(result.Choices) == 1 && result.Choices[0].FinishReason == "length" {
|
||||
return Completion{}, &RemoteError{Code: "output_truncated", Retryable: true}
|
||||
}
|
||||
if json.Unmarshal(raw, &result) != nil || len(result.Choices) != 1 || result.Choices[0].FinishReason != "stop" || strings.TrimSpace(result.Choices[0].Message.Content) == "" {
|
||||
return Completion{}, &RemoteError{Code: "incomplete_response"}
|
||||
return Completion{}, &RemoteError{Code: "incomplete_response", Retryable: true}
|
||||
}
|
||||
return Completion{Content: result.Choices[0].Message.Content, Model: result.Model}, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package qaopsai
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -74,3 +75,28 @@ func TestClientRejectsPrivateEndpointsBeforeSendingSecrets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientDistinguishesTruncatedOutputAndRetainsProviderCooldown(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body, code string
|
||||
status int
|
||||
delay time.Duration
|
||||
}{
|
||||
{"truncated", `{"model":"fixture","choices":[{"message":{"content":"{"},"finish_reason":"length"}]}`, "output_truncated", 200, 0},
|
||||
{"rate-limit", `{}`, "rate_limited", 429, 45 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Retry-After", "45")
|
||||
w.WriteHeader(tc.status)
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
_, err := (Client{AllowPrivate: true}).Call(context.Background(), server.URL, "fixture", "fixture-only", "json", map[string]string{}, 64)
|
||||
var remote *RemoteError
|
||||
if !errors.As(err, &remote) || remote.Code != tc.code || !remote.Retryable || remote.RetryAfter != tc.delay {
|
||||
t.Fatalf("lost retry classification/cooldown: %+v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,12 @@ type claimedWork struct {
|
||||
Attempt, RetryBase int
|
||||
}
|
||||
|
||||
func (s *Store) concurrency() int {
|
||||
if s.options.Concurrency > 0 && s.options.Concurrency <= 16 {
|
||||
return s.options.Concurrency
|
||||
}
|
||||
return 4
|
||||
}
|
||||
func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
|
||||
if !s.valid() {
|
||||
return nil, ErrUnavailable
|
||||
@@ -26,33 +32,37 @@ func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
_, err = tx.Exec(ctx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant)
|
||||
if err != nil {
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var active string
|
||||
var leased, waiting bool
|
||||
err = tx.QueryRow(ctx, `SELECT active_work_id,COALESCE(lease_until>clock_timestamp(),false),next_request_at>clock_timestamp() FROM qa_ops_ai_runtime WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&active, &leased, &waiting)
|
||||
if err != nil {
|
||||
var waiting bool
|
||||
if tx.QueryRow(ctx, `SELECT next_request_at>clock_timestamp()FROM qa_ops_ai_runtime WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&waiting) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if leased || waiting {
|
||||
if waiting {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
if active != "" {
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=CASE WHEN attempt>=retry_base+3 THEN 'failed' ELSE 'retry' END,stage='lease_expired',error_code='worker_lease_expired',available_at=clock_timestamp(),lease_token='',lease_until=NULL,updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2 AND state='running'`, s.tenant, active)
|
||||
if err != nil {
|
||||
// The tenant lock protects admission only; each outbound request retains its own fenced lease.
|
||||
if _, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=CASE WHEN attempt>=retry_base+3 THEN 'failed' ELSE 'retry' END,stage='lease_expired',error_code='worker_lease_expired',available_at=clock_timestamp(),lease_token='',lease_until=NULL,updated_at=clock_timestamp()WHERE tenant_key=$1 AND state='running' AND lease_until<=clock_timestamp()`, s.tenant); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var running int
|
||||
if tx.QueryRow(ctx, `SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='running'AND lease_until>clock_timestamp()`, s.tenant).Scan(&running) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if running >= s.concurrency() {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
var out claimedWork
|
||||
err = tx.QueryRow(ctx, `SELECT id,record_id,kind,trigger_mode,input_hash,master_revision,review_revision,config_revision,attempt,retry_base FROM qa_ops_ai_work WHERE tenant_key=$1 AND state IN ('queued','retry') AND available_at<=clock_timestamp() AND ((trigger_mode='manual' AND EXISTS(SELECT 1 FROM qa_ops_ai_batch_items i JOIN qa_ops_ai_batches b ON b.tenant_key=i.tenant_key AND b.id=i.batch_id WHERE i.tenant_key=qa_ops_ai_work.tenant_key AND i.work_id=qa_ops_ai_work.id AND b.state='active')) OR (trigger_mode='automatic' AND EXISTS(SELECT 1 FROM qa_ops_ai_settings s WHERE s.tenant_key=qa_ops_ai_work.tenant_key AND s.verification='verified' AND CASE WHEN kind='evaluation' THEN s.automatic_evaluation ELSE s.automatic_translation END))) ORDER BY CASE WHEN trigger_mode='manual' THEN 0 ELSE 1 END,available_at,created_at,id FOR UPDATE SKIP LOCKED LIMIT 1`, s.tenant).Scan(&out.ID, &out.RecordID, &out.Kind, &out.Mode, &out.InputHash, &out.MasterRevision, &out.ReviewRevision, &out.ConfigRevision, &out.Attempt, &out.RetryBase)
|
||||
err = tx.QueryRow(ctx, `SELECT id,record_id,kind,trigger_mode,input_hash,master_revision,review_revision,config_revision,attempt,retry_base FROM qa_ops_ai_work w WHERE tenant_key=$1 AND state IN ('queued','retry')AND available_at<=clock_timestamp()AND NOT EXISTS(SELECT 1 FROM qa_ops_ai_work busy WHERE busy.tenant_key=w.tenant_key AND busy.record_id=w.record_id AND busy.kind=w.kind AND busy.state='running')AND((trigger_mode='manual'AND EXISTS(SELECT 1 FROM qa_ops_ai_batch_items i JOIN qa_ops_ai_batches b ON b.tenant_key=i.tenant_key AND b.id=i.batch_id WHERE i.tenant_key=w.tenant_key AND i.work_id=w.id AND b.state='active'))OR(trigger_mode='automatic'AND EXISTS(SELECT 1 FROM qa_ops_ai_settings s WHERE s.tenant_key=w.tenant_key AND s.verification='verified'AND CASE WHEN kind='evaluation' THEN s.automatic_evaluation ELSE s.automatic_translation END)))ORDER BY CASE WHEN trigger_mode='manual'THEN 0 ELSE 1 END,(SELECT count(*)FROM qa_ops_ai_work busy WHERE busy.tenant_key=w.tenant_key AND busy.kind=w.kind AND busy.state='running'),available_at,created_at,id FOR UPDATE SKIP LOCKED LIMIT 1`, s.tenant).Scan(&out.ID, &out.RecordID, &out.Kind, &out.Mode, &out.InputHash, &out.MasterRevision, &out.ReviewRevision, &out.ConfigRevision, &out.Attempt, &out.RetryBase)
|
||||
if err == pgx.ErrNoRows {
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id='',lease_token='',lease_until=NULL WHERE tenant_key=$1`, s.tenant)
|
||||
if err != nil || tx.Commit(ctx) != nil {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return nil, nil
|
||||
@@ -65,12 +75,10 @@ func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
|
||||
return nil, err
|
||||
}
|
||||
out.Attempt++
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state='running',stage='preparing',attempt=$3,lease_token=$4,lease_until=clock_timestamp()+interval '180 seconds',started_at=clock_timestamp(),updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2`, s.tenant, out.ID, out.Attempt, out.Token)
|
||||
if err != nil {
|
||||
if _, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state='running',stage='preparing',attempt=$3,lease_token=$4,lease_until=clock_timestamp()+interval '180 seconds',started_at=clock_timestamp(),updated_at=clock_timestamp()WHERE tenant_key=$1 AND id=$2`, s.tenant, out.ID, out.Attempt, out.Token); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id=$2,lease_token=$3,lease_until=clock_timestamp()+interval '180 seconds' WHERE tenant_key=$1`, s.tenant, out.ID, out.Token)
|
||||
if err != nil || tx.Commit(ctx) != nil {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return &out, nil
|
||||
@@ -107,6 +115,9 @@ func referencesFor(record dobotaiops.Record) []Reference {
|
||||
for _, item := range items {
|
||||
ref := Reference{}
|
||||
ref.Title, _ = item["title"].(string)
|
||||
if strings.TrimSpace(ref.Title) == "" {
|
||||
ref.Title, _ = item["knowledge_title"].(string)
|
||||
}
|
||||
for _, key := range []string{"excerpt", "snippet", "content", "text"} {
|
||||
if text, ok := item[key].(string); ok && strings.TrimSpace(text) != "" {
|
||||
ref.Excerpt = text
|
||||
@@ -181,7 +192,7 @@ func (s *Store) execute(ctx context.Context, w claimedWork) error {
|
||||
if err != nil {
|
||||
return s.finish(w, nil, nil, "", "", &RemoteError{Code: "secret_storage_unavailable"})
|
||||
}
|
||||
completion, err := (Client{AllowPrivate: s.options.AllowPrivate, DNSOverTLS: s.options.DNSOverTLS}).Call(ctx, cfg.BaseURL, cfg.Model, key, system, modelInput, 4096)
|
||||
completion, err := (Client{AllowPrivate: s.options.AllowPrivate, DNSOverTLS: s.options.DNSOverTLS}).Call(ctx, cfg.BaseURL, cfg.Model, key, system, modelInput, 4096<<min(w.Attempt-w.RetryBase-1, 2))
|
||||
if err != nil {
|
||||
return s.finish(w, nil, nil, "", "", err)
|
||||
}
|
||||
@@ -193,14 +204,14 @@ func (s *Store) execute(ctx context.Context, w claimedWork) error {
|
||||
if w.Kind == "translation" {
|
||||
chinese, e := DecodeTranslation(completion.Content, record.Question)
|
||||
if e != nil {
|
||||
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed"})
|
||||
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed", Retryable: true})
|
||||
}
|
||||
fields["question_chinese"] = chinese
|
||||
result = map[string]string{"question_chinese": chinese}
|
||||
} else {
|
||||
assessment, e := DecodeAssessment(completion.Content, input)
|
||||
if e != nil {
|
||||
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed"})
|
||||
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed", Retryable: true})
|
||||
}
|
||||
for field, value := range assessment.Fields {
|
||||
fields[field] = value.Value
|
||||
@@ -267,6 +278,12 @@ func (s *Store) finish(w claimedWork, payload []byte, proposed map[string]string
|
||||
}
|
||||
}
|
||||
delay := time.Duration(1<<uint(w.Attempt-w.RetryBase)) * time.Second
|
||||
cooldown := time.Duration(0)
|
||||
var remote *RemoteError
|
||||
if errors.As(cause, &remote) && code == "rate_limited" {
|
||||
cooldown = max(15*time.Second, remote.RetryAfter)
|
||||
delay = max(delay, cooldown)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=$4,stage=$5,error_code=$6,skip_reason=$7,lease_token='',lease_until=NULL,finished_at=CASE WHEN $4 IN ('retry','paused') THEN NULL ELSE clock_timestamp() END,available_at=clock_timestamp()+$8::interval,updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2 AND lease_token=$3`, s.tenant, w.ID, w.Token, status, stage, code, skip, delay.String())
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
@@ -277,7 +294,7 @@ func (s *Store) finish(w claimedWork, payload []byte, proposed map[string]string
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id='',lease_token='',lease_until=NULL,next_request_at=clock_timestamp()+interval '1 second',heartbeat_at=clock_timestamp() WHERE tenant_key=$1 AND lease_token=$2`, s.tenant, w.Token)
|
||||
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET heartbeat_at=clock_timestamp(),next_request_at=CASE WHEN $2 THEN GREATEST(next_request_at,clock_timestamp()+$3::interval)ELSE next_request_at END WHERE tenant_key=$1`, s.tenant, code == "rate_limited", cooldown.String())
|
||||
if err != nil || tx.Commit(ctx) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package qaopsai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunWithUnavailableStoreFailsClosed(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Fatal("unavailable worker panicked")
|
||||
}
|
||||
}()
|
||||
called := false
|
||||
(&Store{}).Run(ctx, func(err error) { called = err == ErrUnavailable })
|
||||
if !called {
|
||||
t.Fatal("unavailable worker failed silently")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferencesPreserveSourceKnowledgeTitleWithoutInventingEvidence(t *testing.T) {
|
||||
r := dobotaiops.Record{References: json.RawMessage(`[{"knowledge_title":"MG400官方连接说明","id":"only-title"},{"title":"原始标题","knowledge_title":"不能覆盖","content":"逐字证据"}]`)}
|
||||
refs := referencesFor(r)
|
||||
if len(refs) != 2 || refs[0].Title != "MG400官方连接说明" || refs[0].Excerpt != "" || refs[1].Title != "原始标题" || refs[1].Excerpt != "逐字证据" {
|
||||
t.Fatalf("source citation titles lost or title-only treated as evidence: %+v", refs)
|
||||
}
|
||||
}
|
||||
+47
-17
@@ -2,39 +2,69 @@ package qaopsai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This loop owns only the AI subqueue. Long HTTP calls never occupy a source-sync transaction/job.
|
||||
// Admission is fenced in PostgreSQL; slow model calls do not serialize source-sync or the other AI slots.
|
||||
func (s *Store) Run(ctx context.Context, onError func(error)) {
|
||||
tick := time.NewTicker(time.Second)
|
||||
defer tick.Stop()
|
||||
var nextScan, lastError time.Time
|
||||
if !s.valid() {
|
||||
if onError != nil {
|
||||
onError(ErrUnavailable)
|
||||
}
|
||||
return
|
||||
}
|
||||
var lock sync.Mutex
|
||||
var lastError time.Time
|
||||
report := func(err error) {
|
||||
if err != nil && ctx.Err() == nil && time.Since(lastError) > 30*time.Second {
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
if time.Since(lastError) > 30*time.Second {
|
||||
lastError = time.Now()
|
||||
if onError != nil {
|
||||
onError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if time.Now().After(nextScan) {
|
||||
scanCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
_, err := s.ScanAutomatic(scanCtx)
|
||||
cancel()
|
||||
report(err)
|
||||
nextScan = time.Now().Add(15 * time.Second)
|
||||
}
|
||||
_, err := s.ProcessOne(ctx)
|
||||
var workers sync.WaitGroup
|
||||
for i := 0; i < s.concurrency(); i++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for ctx.Err() == nil {
|
||||
worked, err := s.ProcessOne(ctx)
|
||||
report(err)
|
||||
if !worked || err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
defer workers.Wait()
|
||||
tick := time.NewTicker(10 * time.Second)
|
||||
defer tick.Stop()
|
||||
scan := func() {
|
||||
scanCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
_, err := s.ScanAutomatic(scanCtx)
|
||||
report(err)
|
||||
_, err = s.pool.Exec(scanCtx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant)
|
||||
report(err)
|
||||
}
|
||||
scan()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
scan()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Concurrency int
|
||||
KeyFile string
|
||||
AllowPrivate bool
|
||||
DNSOverTLS bool
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
@@ -16,6 +19,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAIBatchManualRetryKeepsCumulativeAttemptsAndFixedDenominator(t *testing.T) {
|
||||
@@ -228,7 +232,8 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
|
||||
var body struct {
|
||||
Messages []struct{ Content string } `json:"messages"`
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&body) != nil || len(body.Messages) != 2 {
|
||||
rawBody, readErr := io.ReadAll(r.Body)
|
||||
if readErr != nil || json.Unmarshal(rawBody, &body) != nil || len(body.Messages) != 2 {
|
||||
t.Error("invalid synthetic request")
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
@@ -238,6 +243,7 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
|
||||
return
|
||||
}
|
||||
calls.Add(1)
|
||||
r.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||
if handler != nil {
|
||||
handler(w, r)
|
||||
return
|
||||
@@ -279,6 +285,221 @@ func (m aiMatrix) batch(t *testing.T, nonce string) qaopsai.Batch {
|
||||
}
|
||||
return batch
|
||||
}
|
||||
func TestAIRunnerActuallyDispatchesFourConcurrentRequests(t *testing.T) {
|
||||
entered := make(chan struct{}, 8)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
m := newAIMatrix(t, "fixture-ai-runner-slots", func(w http.ResponseWriter, r *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
seedParallelAIWork(t, m)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { m.ai.Run(ctx, nil); close(done) }()
|
||||
defer func() { once.Do(func() { close(release) }); cancel(); <-done }()
|
||||
count := 0
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
loop:
|
||||
for count < 4 {
|
||||
select {
|
||||
case <-entered:
|
||||
count++
|
||||
case <-timer.C:
|
||||
break loop
|
||||
}
|
||||
}
|
||||
if count != 4 {
|
||||
t.Fatalf("actual worker runner is still serial: concurrent=%d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func seedParallelAIWork(t *testing.T, m aiMatrix) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
entries := []dobotaiops.MirrorRecord{}
|
||||
ids := []string{}
|
||||
for i, word := range []string{"Alpha", "Bravo", "Charlie", "Delta", "Echo"} {
|
||||
id := fmt.Sprintf("parallel-record-%d", i)
|
||||
entry := fixtureEntry(id, "fixture answer")
|
||||
var wire map[string]any
|
||||
_ = json.Unmarshal(entry.Payload, &wire)
|
||||
wire["question"] = "How do I connect MG400? " + word
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
entries = append(entries, entry)
|
||||
ids = append(ids, id)
|
||||
}
|
||||
var seedJob string
|
||||
if m.pool.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state='running'`, m.master.SyncJobType()).Scan(&seedJob) != nil {
|
||||
t.Fatal("seed lease unavailable")
|
||||
}
|
||||
if e := pg.NewStore(m.pool).Complete(ctx, seedJob, "fixture-sync-worker", time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job := claimMirrorJob(t, m.master, pg.NewStore(m.pool), "parallel-seed")
|
||||
if e := m.master.HandleSync(ctx, *job, func(context.Context) (Source, error) { return &fixtureSource{rows: entries}, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
preview, e := m.ai.Preview(ctx, qaopsai.Scope{Kind: "translation", IDs: ids}, "fixture-admin")
|
||||
if e != nil || preview.Eligible != 5 {
|
||||
t.Fatal("five unique inputs unavailable", e, preview.Eligible)
|
||||
}
|
||||
if _, e = m.ai.Start(ctx, preview.ID, strings.Repeat("parallel", 4), "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIParallelClaimsUseFourSlotsWithoutDuplicatingOrExceedingLimit(t *testing.T) {
|
||||
entered := make(chan struct{}, 8)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
m := newAIMatrix(t, "fixture-ai-four-slots", func(w http.ResponseWriter, r *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
defer once.Do(func() { close(release) })
|
||||
ctx := context.Background()
|
||||
seedParallelAIWork(t, m)
|
||||
var group sync.WaitGroup
|
||||
failures := make(chan error, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := m.ai.ProcessOne(ctx)
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
}()
|
||||
}
|
||||
seen := 0
|
||||
timeout := time.NewTimer(1500 * time.Millisecond)
|
||||
loop:
|
||||
for seen < 4 {
|
||||
select {
|
||||
case <-entered:
|
||||
seen++
|
||||
case <-timeout.C:
|
||||
break loop
|
||||
}
|
||||
}
|
||||
timeout.Stop()
|
||||
if seen != 4 {
|
||||
t.Errorf("wanted four concurrent model requests before any completes; got %d", seen)
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
t.Error("exceeded four global slots")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
once.Do(func() { close(release) })
|
||||
group.Wait()
|
||||
close(failures)
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
if seen == 4 {
|
||||
var running, queued, outputs int
|
||||
if m.pool.QueryRow(ctx, `SELECT (SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='running'),(SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='queued'),(SELECT count(*)FROM qa_ops_ai_outputs WHERE tenant_key=$1)`, m.tenant).Scan(&running, &queued, &outputs) != nil || running != 0 || queued != 1 || outputs != 4 {
|
||||
t.Fatal("slot completion lost/duplicated work", running, queued, outputs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAITruncationRetriesExpandBudgetAndStopAfterThreeAttempts(t *testing.T) {
|
||||
budgets := []int{}
|
||||
m := newAIMatrix(t, "fixture-ai-truncation-budget", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Max int `json:"max_tokens"`
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&req) != nil {
|
||||
t.Error("request decode")
|
||||
}
|
||||
budgets = append(budgets, req.Max)
|
||||
if len(budgets) < 3 {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"model": "fixture", "choices": []any{map[string]any{"finish_reason": "length", "message": map[string]string{"content": ""}}}})
|
||||
return
|
||||
}
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
batch := m.batch(t, "t")
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := m.pool.Exec(ctx, `UPDATE qa_ops_ai_work SET available_at=clock_timestamp()-interval '1 second'WHERE tenant_key=$1`, m.tenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if worked, err := m.ai.ProcessOne(ctx); err != nil || !worked {
|
||||
t.Fatal("bounded retry did not execute", err)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(budgets) != "[4096 8192 16384]" {
|
||||
t.Fatal("truncation budget did not grow", budgets)
|
||||
}
|
||||
current, err := m.ai.GetBatch(ctx, batch.ID)
|
||||
if err != nil || current.Succeeded != 1 || current.Total != 1 || m.calls.Load() != 3 {
|
||||
t.Fatal("retry denominator or completion", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIParallelSuccessCannotClearAnotherRequestsRateLimit(t *testing.T) {
|
||||
entered := make(chan struct{}, 4)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
var calls atomic.Int32
|
||||
m := newAIMatrix(t, "fixture-ai-shared-cooldown", func(w http.ResponseWriter, r *http.Request) {
|
||||
n := calls.Add(1)
|
||||
entered <- struct{}{}
|
||||
if n == 4 {
|
||||
w.Header().Set("Retry-After", "45")
|
||||
w.WriteHeader(429)
|
||||
return
|
||||
}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
defer once.Do(func() { close(release) })
|
||||
seedParallelAIWork(t, m)
|
||||
ctx := context.Background()
|
||||
var group sync.WaitGroup
|
||||
errs := make(chan error, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
group.Add(1)
|
||||
go func() { defer group.Done(); _, err := m.ai.ProcessOne(ctx); errs <- err }()
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("four parallel slots not reached")
|
||||
}
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
remaining := 0.0
|
||||
for time.Now().Before(deadline) {
|
||||
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) == nil && remaining > 40 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
}
|
||||
once.Do(func() { close(release) })
|
||||
group.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) != nil || remaining < 40 {
|
||||
t.Fatal("success cleared shared provider cooldown", remaining)
|
||||
}
|
||||
if worked, err := m.ai.ProcessOne(ctx); err != nil || worked || calls.Load() != 4 {
|
||||
t.Fatal("new request bypassed shared rate limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIManualBatchPauseResumeKeepsSharedWorkAndActionReplaysSafe(t *testing.T) {
|
||||
m := newAIMatrix(t, "fixture-ai-pause", nil)
|
||||
ctx := context.Background()
|
||||
|
||||
+13
-1
@@ -27,7 +27,7 @@ it('shows open-ended automatic queue counts without fabricating a percentage', (
|
||||
query={{ start: '2026-10-05T00:00:00Z', end: '2026-10-12T00:00:00Z', keyword: 'executed-query', cursor: '' }}
|
||||
/>
|
||||
)
|
||||
for (const value of ['补缺评估', '补缺中文翻译', '当前已执行筛选', '后台任务', '排队 2', '执行 1', '失败 1'])
|
||||
for (const value of ['AI分析', '当前已执行筛选', '后台任务', '排队 2', '执行 1', '失败 1'])
|
||||
expect(html).toContain(value)
|
||||
expect(html).not.toContain('100%')
|
||||
})
|
||||
@@ -109,3 +109,15 @@ it('renders original evidence quotes, actual model/version and applied-versus-sk
|
||||
])
|
||||
expect(html).toContain(value)
|
||||
})
|
||||
|
||||
it('uses one AI分析 entry for combined evaluation and Chinese translation', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAAIWorkbench
|
||||
initial={status}
|
||||
query={{ start: '2026-10-05T00:00:00Z', end: '2026-10-12T00:00:00Z', keyword: '', cursor: '' }}
|
||||
/>
|
||||
)
|
||||
expect([...html.matchAll(/>AI分析<\/button>/g)]).toHaveLength(1)
|
||||
expect(html).not.toContain('补缺评估')
|
||||
expect(html).not.toContain('补缺中文翻译')
|
||||
})
|
||||
|
||||
+36
-41
@@ -56,23 +56,27 @@ export function QAAIRequest({
|
||||
disabled,
|
||||
onQueued,
|
||||
}: {
|
||||
scope: AIScope | null
|
||||
scope: Omit<AIScope, 'kind'> | null
|
||||
label: string
|
||||
disabled?: boolean
|
||||
onQueued?: () => void
|
||||
}) {
|
||||
const [preview, setPreview] = useState<AIPreview | null>(null),
|
||||
const [preview, setPreview] = useState<AIPreview[] | null>(null),
|
||||
[nonce, setNonce] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState<string | null>(null),
|
||||
[message, setMessage] = useState<string | null>(null)
|
||||
const queued = useRef(new Set<AIKind>())
|
||||
const prepare = async () => {
|
||||
if (!scope) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setMessage(null)
|
||||
try {
|
||||
setPreview(await previewAI(scope))
|
||||
setPreview(
|
||||
await Promise.all((['evaluation', 'translation'] as const).map((kind) => previewAI({ ...scope, kind })))
|
||||
)
|
||||
queued.current.clear()
|
||||
setNonce(newOperationID())
|
||||
} catch (reason) {
|
||||
setError(errorText(reason))
|
||||
@@ -85,12 +89,17 @@ export function QAAIRequest({
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await startAI(preview.id, nonce)
|
||||
for (const part of preview) {
|
||||
if (part.eligible === 0 || queued.current.has(part.kind)) continue
|
||||
await startAI(part.id, nonce + ':' + part.kind)
|
||||
queued.current.add(part.kind)
|
||||
}
|
||||
setPreview(null)
|
||||
setMessage('批次已持久保存;关闭页面后继续执行。')
|
||||
setMessage('AI分析任务已持久保存;字段分析与中文翻译按实际缺口执行,关闭页面后继续。')
|
||||
onQueued?.()
|
||||
} catch (reason) {
|
||||
setError(errorText(reason))
|
||||
setError((queued.current.size ? '部分任务已创建,重试只补未确认部分,不会重复入队。' : '') + errorText(reason))
|
||||
if (queued.current.size) onQueued?.()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
@@ -102,17 +111,23 @@ export function QAAIRequest({
|
||||
</button>
|
||||
{preview ? (
|
||||
<span className="qa-ai-confirm" role="dialog" aria-label={label + '范围确认'}>
|
||||
<strong>{`${aiKindLabels[preview.kind]}:范围 ${preview.scope_total} 条,实际待补 ${preview.eligible} 条,跳过 ${preview.skipped} 条。`}</strong>
|
||||
<strong>AI分析:仅补当前范围的空白字段和缺失中文翻译</strong>
|
||||
{preview.map((part) => (
|
||||
<small key={part.kind}>
|
||||
{aiKindLabels[part.kind]}:范围 {part.scope_total} 条,待补 {part.eligible} 条,跳过 {part.skipped} 条。
|
||||
</small>
|
||||
))}
|
||||
<small>
|
||||
{preview.kind === 'evaluation'
|
||||
? '只向已配置模型发送待补记录的问题、答案及获准引用,不发送人员/部门信息。'
|
||||
: '只发送待补记录的原始问题,不翻译或发送答案。'}
|
||||
仅补空白,不覆盖既有标签或人工结论。
|
||||
两类任务独立计数,同一记录可能同时需要两项。仅发送问题、分析所需答案及已有引用片段,不发送人员/部门;不覆盖非空标签或人工结论。
|
||||
</small>
|
||||
<button type="button" disabled={busy} onClick={() => setPreview(null)}>
|
||||
取消
|
||||
</button>
|
||||
<button type="button" disabled={busy || preview.eligible === 0} onClick={() => void confirm()}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || preview.every((part) => part.eligible === 0)}
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
确认创建后台批次
|
||||
</button>
|
||||
</span>
|
||||
@@ -192,6 +207,7 @@ export function QAAIWorkbench({
|
||||
const callbacks = useRef({ onStatus, onRecordChanged })
|
||||
callbacks.current = { onStatus, onRecordChanged }
|
||||
const previous = useRef<Map<string, string> | null>(null)
|
||||
const statusSignature = useRef('')
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
@@ -202,7 +218,11 @@ export function QAAIWorkbench({
|
||||
if (controller.signal.aborted) return
|
||||
setStatus(next)
|
||||
setError(null)
|
||||
callbacks.current.onStatus?.(next)
|
||||
const signature = JSON.stringify(next)
|
||||
if (signature !== statusSignature.current) {
|
||||
statusSignature.current = signature
|
||||
callbacks.current.onStatus?.(next)
|
||||
}
|
||||
if (previous.current) {
|
||||
for (const task of next.recent_tasks) {
|
||||
if (
|
||||
@@ -245,27 +265,13 @@ export function QAAIWorkbench({
|
||||
}
|
||||
}
|
||||
const ready = Boolean(status?.settings.verification === 'verified' && status.settings.storage_ready)
|
||||
const scope = (kind: AIKind): AIScope | null =>
|
||||
query ? { kind, start: query.start, end: query.end, keyword: query.keyword } : null
|
||||
const scope = query ? { start: query.start, end: query.end, keyword: query.keyword } : null
|
||||
const scopeKey = query ? `${query.start}:${query.end}:${query.keyword}` : 'none'
|
||||
return (
|
||||
<section className="qa-ai-workbench" aria-label="问答后台任务">
|
||||
<div className="qa-ai-actions">
|
||||
<span>当前已执行筛选</span>
|
||||
<QAAIRequest
|
||||
key={'evaluation:' + scopeKey}
|
||||
scope={scope('evaluation')}
|
||||
label="补缺评估"
|
||||
disabled={!ready}
|
||||
onQueued={refresh}
|
||||
/>
|
||||
<QAAIRequest
|
||||
key={'translation:' + scopeKey}
|
||||
scope={scope('translation')}
|
||||
label="补缺中文翻译"
|
||||
disabled={!ready}
|
||||
onQueued={refresh}
|
||||
/>
|
||||
<QAAIRequest key={scopeKey} scope={scope} label="AI分析" disabled={!ready} onQueued={refresh} />
|
||||
{status ? (
|
||||
<small>
|
||||
{status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'}
|
||||
@@ -490,18 +496,7 @@ export function QAAIRecordEvidence({
|
||||
return (
|
||||
<>
|
||||
<div className="qa-ai-actions">
|
||||
<QAAIRequest
|
||||
key={recordID + ':evaluation'}
|
||||
scope={{ kind: 'evaluation', ids: [recordID] }}
|
||||
label="本条补缺评估"
|
||||
onQueued={refresh}
|
||||
/>
|
||||
<QAAIRequest
|
||||
key={recordID + ':translation'}
|
||||
scope={{ kind: 'translation', ids: [recordID] }}
|
||||
label="本条补缺中文翻译"
|
||||
onQueued={refresh}
|
||||
/>
|
||||
<QAAIRequest key={recordID} scope={{ ids: [recordID] }} label="AI分析" onQueued={refresh} />
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
|
||||
@@ -15,7 +15,12 @@ export function QAMirrorSyncView(p: ViewProps) {
|
||||
return (
|
||||
<section className="qa-mirror-sync" aria-label="问答同步状态">
|
||||
<div className="qa-mirror-sync-line">
|
||||
<button type="button" onClick={p.onSync} disabled={p.submitting || !s?.worker_ready || active}>
|
||||
<button
|
||||
className="qa-query-action"
|
||||
type="button"
|
||||
onClick={p.onSync}
|
||||
disabled={p.submitting || !s?.worker_ready || active}
|
||||
>
|
||||
{p.submitting ? '正在入队…' : active ? '后台同步中…' : '立即同步'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { QAOperationsTabs, QAOperationsView } from './QAOperations'
|
||||
@@ -101,12 +103,13 @@ describe('QA operations workbench', () => {
|
||||
expect(html).toContain('数据源有待审核的安全告警')
|
||||
expect(html).toContain('fixture real read failure')
|
||||
})
|
||||
it('keeps a name-only person summary with the original available separately', () => {
|
||||
it('removes workflow personnel from details while preserving the record data', () => {
|
||||
const detail = { ...item, trigger_person: JSON.stringify({ name: '示例姓名', unionId: 'fixture-union' }) }
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} detail={detail} />)
|
||||
expect(html).toContain('<dd>示例姓名</dd>')
|
||||
expect(html).toContain('原始人员信息')
|
||||
expect(html).toContain('fixture-union')
|
||||
const drawer = html.slice(html.indexOf('<aside'))
|
||||
expect(drawer).not.toContain('示例姓名')
|
||||
expect(drawer).not.toContain('原始人员信息')
|
||||
expect(drawer).not.toContain('fixture-union')
|
||||
})
|
||||
it('provides a row-level detail target and categorical color tags without adding business columns', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
@@ -182,3 +185,38 @@ describe('QA operations workbench', () => {
|
||||
expect(restored.activeTab).toBe('qaops')
|
||||
})
|
||||
})
|
||||
|
||||
it('opens a modeless right drawer with fixed leading quality fields and no redundant organization/personnel details', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} detail={{ ...item, record_origin: 'dobotai_2_0' }} />)
|
||||
const drawer = html.slice(html.indexOf('<aside'))
|
||||
expect(html).not.toContain('qa-ops-backdrop')
|
||||
expect(drawer).toContain('aria-modal="false"')
|
||||
expect(drawer).toContain('qa-detail-quality')
|
||||
const labels = ['是否覆盖', '是否正确', '产品分类', '问题类型', '根因分析']
|
||||
for (const label of labels) expect(drawer).toContain(label)
|
||||
expect(drawer.indexOf('根因分析')).toBeLessThan(drawer.indexOf('原始问题'))
|
||||
for (const label of [
|
||||
'<dt>区域</dt>',
|
||||
'当前组织关联',
|
||||
'当前通讯录部门/区域',
|
||||
'组织版本',
|
||||
'源端组织快照',
|
||||
'记录来源',
|
||||
'问答状态',
|
||||
'流程触发人员信息',
|
||||
'原始人员信息',
|
||||
])
|
||||
expect(drawer).not.toContain(label)
|
||||
})
|
||||
|
||||
it('names the ledger explicitly as 问题流水表', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
|
||||
expect(html).toContain('>问题流水表</button>')
|
||||
})
|
||||
|
||||
it('uses matching query/sync action sizing and keeps synchronization status outside the button baseline', () => {
|
||||
const css = readFileSync(new URL('./qaOps.css', import.meta.url), 'utf8')
|
||||
expect(css).toContain('.qa-ops-query .qa-query-action')
|
||||
expect(css).toMatch(/\.qa-ops-query \.qa-query-action\s*\{[^}]*width:\s*96px/)
|
||||
expect(css).toMatch(/\.qa-ops-query \.qa-mirror-sync-line\s*\{[^}]*margin-bottom:\s*0/)
|
||||
})
|
||||
|
||||
+90
-92
@@ -4,13 +4,13 @@ import { useOptionalAuth } from './auth'
|
||||
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
|
||||
import { QARegionalStatistics } from './QADepartmentStatistics'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAQualityEditor } from './QAQuality'
|
||||
import { qaFieldColors, qaTagColumns } from './qaFieldColors'
|
||||
import { qualityLabels } from './qaQuality'
|
||||
import { usageLabels } from './qaUsage'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
import { QAMirrorSync } from './QAMirrorSync'
|
||||
@@ -24,7 +24,7 @@ export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
{(
|
||||
[
|
||||
['records', '问题流水'],
|
||||
['records', '问题流水表'],
|
||||
['dashboard', '问题统计看板'],
|
||||
['regions', '区域统计'],
|
||||
['weekly', '周报生成'],
|
||||
@@ -58,12 +58,6 @@ const warningLabels: Record<string, string> = {
|
||||
database_transport_unencrypted: '数据库连接未启用 TLS:上线前须完成传输安全审核',
|
||||
}
|
||||
const stamp = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
const statusLabels: Record<string, string> = {
|
||||
succeeded: '成功',
|
||||
failed: '失败',
|
||||
running: '处理中',
|
||||
cancelled: '已取消',
|
||||
}
|
||||
const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', uncovered: '未覆盖' }
|
||||
|
||||
function tasksFor(item: QARecord, updates: AIWorkState[] | undefined) {
|
||||
@@ -78,17 +72,21 @@ function tasksFor(item: QARecord, updates: AIWorkState[] | undefined) {
|
||||
const QARow = memo(
|
||||
function QARow({
|
||||
item,
|
||||
rowIndex,
|
||||
tasks,
|
||||
onSelect,
|
||||
}: {
|
||||
item: QARecord
|
||||
rowIndex: number
|
||||
tasks: AIWorkState[]
|
||||
signature: string
|
||||
onSelect: (id: string) => void
|
||||
}) {
|
||||
return (
|
||||
<tr
|
||||
className="qa-ops-record-row"
|
||||
data-qa-row={item.id}
|
||||
aria-rowindex={rowIndex}
|
||||
onDoubleClick={(event) => {
|
||||
if (!(event.target as HTMLElement).closest('button,a,input,select,textarea,summary')) onSelect(item.id)
|
||||
}}
|
||||
@@ -106,26 +104,55 @@ const QARow = memo(
|
||||
className={qaTagColumns.has(key) ? 'qa-field-tag' : key === 'trigger_person' ? 'qa-person-name' : ''}
|
||||
style={qaTagColumns.has(key) ? qaFieldColors(key, qaCellValue(item, key) ?? '—') : undefined}
|
||||
>
|
||||
{qaCellValue(item, key) ?? '—'}
|
||||
{['answer', 'question', 'question_chinese', 'department'].includes(key)
|
||||
? ledgerCellPreview(qaCellValue(item, key) ?? '—')
|
||||
: (qaCellValue(item, key) ?? '—')}
|
||||
</span>
|
||||
</td>
|
||||
))}
|
||||
<td>
|
||||
<button type="button" onClick={() => onSelect(item.id)} aria-label={`查看问答 ${item.id} 的详情`}>
|
||||
详情
|
||||
</button>
|
||||
{item.quality ? <small className="qa-quality-state">{qualityLabels[item.quality.state]}</small> : null}
|
||||
<QAAITaskBadges tasks={tasks} />
|
||||
<div className="qa-ledger-actions">
|
||||
<button type="button" onClick={() => onSelect(item.id)} aria-label={`查看问答 ${item.id} 的详情`}>
|
||||
详情
|
||||
</button>
|
||||
{item.quality ? <small className="qa-quality-state">{qualityLabels[item.quality.state]}</small> : null}
|
||||
<QAAITaskBadges tasks={tasks} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
},
|
||||
(before, after) =>
|
||||
before.item === after.item && before.signature === after.signature && before.onSelect === after.onSelect
|
||||
before.item === after.item &&
|
||||
before.rowIndex === after.rowIndex &&
|
||||
before.signature === after.signature &&
|
||||
before.onSelect === after.onSelect
|
||||
)
|
||||
|
||||
const ledgerColumnWidth = (key: string) =>
|
||||
['answer', 'question', 'question_chinese'].includes(key)
|
||||
? 320
|
||||
: key === 'asked_at'
|
||||
? 185
|
||||
: key === 'department'
|
||||
? 240
|
||||
: key === 'root_cause'
|
||||
? 155
|
||||
: 125
|
||||
export function QAOperationsView(props: ViewProps) {
|
||||
const page = props.page
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const [viewport, setViewport] = useState({ top: 0, height: 600 })
|
||||
const visible = ledgerWindow(page?.items.length ?? 0, viewport.top, viewport.height)
|
||||
useEffect(() => {
|
||||
const element = scrollRef.current
|
||||
if (!element) return
|
||||
const observer = new ResizeObserver(() =>
|
||||
setViewport({ top: Math.max(0, element.scrollTop - 40), height: element.clientHeight })
|
||||
)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [Boolean(page?.items.length)])
|
||||
const columns = qaColumns
|
||||
const updates = useMemo(() => {
|
||||
const map = new Map<string, AIWorkState[]>()
|
||||
@@ -145,7 +172,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
{props.loading
|
||||
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
|
||||
: page
|
||||
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
|
||||
? `共 ${page.total} 条 · 已载入 ${page.items.length} 条`
|
||||
: '尚未读取问答'}
|
||||
</span>
|
||||
<small className="qa-ops-muted">双击行查看详情</small>
|
||||
@@ -167,8 +194,27 @@ export function QAOperationsView(props: ViewProps) {
|
||||
</div>
|
||||
) : null}
|
||||
{page && page.items.length > 0 ? (
|
||||
<div className="qa-ops-table-scroll" aria-label="问答表格滚动区" tabIndex={0}>
|
||||
<table className="qa-ops-table">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="qa-ops-table-scroll"
|
||||
aria-label="问答表格滚动区"
|
||||
tabIndex={0}
|
||||
onScroll={(event) => {
|
||||
const element = event.currentTarget
|
||||
setViewport({ top: Math.max(0, element.scrollTop - 40), height: element.clientHeight })
|
||||
}}
|
||||
>
|
||||
<table
|
||||
className="qa-ops-table"
|
||||
aria-rowcount={page.items.length + 1}
|
||||
style={{ width: qaColumns.reduce((sum, c) => sum + ledgerColumnWidth(c.key), 160) }}
|
||||
>
|
||||
<colgroup>
|
||||
{qaColumns.map((c) => (
|
||||
<col key={c.key} style={{ width: ledgerColumnWidth(c.key) }} />
|
||||
))}
|
||||
<col style={{ width: 160 }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map(({ key, label }) => (
|
||||
@@ -178,18 +224,29 @@ export function QAOperationsView(props: ViewProps) {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{page.items.map((item) => {
|
||||
{visible.padTop > 0 ? (
|
||||
<tr aria-hidden="true" className="qa-ledger-spacer">
|
||||
<td colSpan={columns.length + 1} style={{ height: visible.padTop }} />
|
||||
</tr>
|
||||
) : null}
|
||||
{page.items.slice(visible.start, visible.end).map((item, index) => {
|
||||
const tasks = tasksFor(item, updates.get(item.id))
|
||||
return (
|
||||
<QARow
|
||||
key={item.id}
|
||||
item={item}
|
||||
rowIndex={visible.start + index + 2}
|
||||
tasks={tasks}
|
||||
signature={JSON.stringify(tasks)}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{visible.padBottom > 0 ? (
|
||||
<tr aria-hidden="true" className="qa-ledger-spacer">
|
||||
<td colSpan={columns.length + 1} style={{ height: visible.padBottom }} />
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -199,36 +256,13 @@ export function QAOperationsView(props: ViewProps) {
|
||||
|
||||
{showDrawer ? (
|
||||
<>
|
||||
<button
|
||||
className="qa-ops-backdrop"
|
||||
type="button"
|
||||
onClick={props.onCloseDetail}
|
||||
aria-label="关闭问答详情遮罩"
|
||||
/>
|
||||
<aside
|
||||
className="qa-ops-drawer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-modal="false"
|
||||
aria-label="问答详情"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') props.onCloseDetail()
|
||||
if (event.key === 'Tab') {
|
||||
const buttons = Array.from(
|
||||
event.currentTarget.querySelectorAll<HTMLElement>(
|
||||
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex="0"]'
|
||||
)
|
||||
)
|
||||
const first = buttons[0],
|
||||
last = buttons[buttons.length - 1]
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault()
|
||||
last?.focus()
|
||||
}
|
||||
if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault()
|
||||
first?.focus()
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<header>
|
||||
@@ -237,6 +271,18 @@ export function QAOperationsView(props: ViewProps) {
|
||||
关闭详情
|
||||
</button>
|
||||
</header>
|
||||
{detail ? (
|
||||
<div className="qa-detail-quality" aria-label="固定质量字段">
|
||||
{(['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'] as const).map((key) => (
|
||||
<div key={key} data-quality-field={key}>
|
||||
<span>{qaColumns.find((column) => column.key === key)!.label}</span>
|
||||
<strong className="qa-field-tag" style={qaFieldColors(key, qaCellValue(detail, key) ?? '—')}>
|
||||
{qaCellValue(detail, key) ?? '—'}
|
||||
</strong>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{props.detailLoading ? <p role="status">正在读取完整问答…</p> : null}
|
||||
{props.detailError ? (
|
||||
<p className="error-banner" role="alert">
|
||||
@@ -258,55 +304,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
{detail.department || '未匹配'}
|
||||
{detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''}
|
||||
</dd>
|
||||
<dt>区域</dt>
|
||||
<dd>
|
||||
{detail.region || '未配置/待核对'}
|
||||
{detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''}
|
||||
</dd>
|
||||
{detail.organization ? (
|
||||
<>
|
||||
<dt>当前组织关联</dt>
|
||||
<dd>
|
||||
{detail.organization.state === 'matched'
|
||||
? '已关联'
|
||||
: (usageLabels[detail.organization.state] ?? detail.organization.state)}
|
||||
</dd>
|
||||
<dt>当前通讯录部门/区域</dt>
|
||||
<dd>
|
||||
{detail.organization.departments.join(';') || '未匹配'} /{' '}
|
||||
{detail.organization.region || '未配置或待核对'}
|
||||
</dd>
|
||||
<dt>组织版本</dt>
|
||||
<dd>
|
||||
{detail.organization.version.directory_id || '无完整目录'} /{' '}
|
||||
{detail.organization.version.revision_id || '未保存区域配置'}
|
||||
</dd>
|
||||
<dt>源端组织快照</dt>
|
||||
<dd>
|
||||
{detail.organization.source_department || '空'} / {detail.organization.source_region || '空'}
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
{detail.record_origin ? (
|
||||
<>
|
||||
<dt>记录来源</dt>
|
||||
<dd>
|
||||
{detail.record_origin === 'historical_excel'
|
||||
? '历史 Excel 导入(原标注保留)'
|
||||
: 'DobotAI 2.0 收录副本'}
|
||||
;主表不随源同步覆盖或删除
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
<dt>问答状态</dt>
|
||||
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
|
||||
<dt>流程触发人员信息</dt>
|
||||
<dd>{qaCellValue(detail, 'trigger_person') || '未记录'}</dd>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>原始人员信息</summary>
|
||||
<pre>{detail.master_fields?.trigger_person ?? detail.trigger_person ?? '未记录'}</pre>
|
||||
</details>
|
||||
<h4>原始问题</h4>
|
||||
<div className="qa-ops-full-text">{detail.question || '无文本问题'}</div>
|
||||
<h4>AI答案</h4>
|
||||
@@ -582,7 +580,7 @@ export function QAOperations() {
|
||||
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading}>
|
||||
<button className="qa-query-action" type="submit" disabled={loading}>
|
||||
查询
|
||||
</button>
|
||||
<QAMirrorSync
|
||||
|
||||
@@ -16,6 +16,7 @@ describe('manual quality operations', () => {
|
||||
for (const value of ['人工复核', '保存并读回', '覆盖结论', '正确性', '复核理由', 'fixture-admin'])
|
||||
expect(html).toContain(value)
|
||||
expect(html).not.toContain('<script>')
|
||||
expect(html).not.toContain('AI 评估未接入')
|
||||
})
|
||||
it('labels stale manual judgment as needing reconfirmation', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
|
||||
@@ -196,7 +196,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload, dataset
|
||||
</p>
|
||||
) : null}
|
||||
<p className="qa-ops-muted">
|
||||
AI 评估未接入。自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,不自动猜测。复核人取登录身份。
|
||||
模型建议、自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,人工结论优先。复核人取登录身份。
|
||||
</p>
|
||||
{error ? (
|
||||
<div role="alert" className="error-banner">
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { it, expect, vi } from 'vitest'
|
||||
import { qaCellValue } from './qaOps'
|
||||
import type { QARecord } from './qaOps'
|
||||
it('formats Beijing timestamps identically without constructing per-row locale formatting work', () => {
|
||||
const record = { asked_at: '2026-10-19T12:11:22Z' } as QARecord
|
||||
const expected = new Date(record.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
const spy = vi.spyOn(Date.prototype, 'toLocaleString')
|
||||
try {
|
||||
for (let i = 0; i < 200; i++) expect(qaCellValue(record, 'asked_at')).toBe(expected)
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { ledgerCellPreview } from './qaLedgerRendering'
|
||||
it('bounds clipped cell text without modifying full original strings or splitting Unicode', () => {
|
||||
const original = '测试🎵'.repeat(5000)
|
||||
const preview = ledgerCellPreview(original)
|
||||
expect([...preview].length).toBeLessThanOrEqual(401)
|
||||
expect(preview.endsWith('…')).toBe(true)
|
||||
expect(original).toBe('测试🎵'.repeat(5000))
|
||||
expect(ledgerCellPreview('短问题')).toBe('短问题')
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
export const ledgerRowHeight = 108
|
||||
export function ledgerWindow(total: number, top: number, height: number) {
|
||||
const visible = Math.max(1, Math.ceil(height / ledgerRowHeight))
|
||||
const start = Math.min(Math.max(0, total - visible), Math.max(0, Math.floor(top / ledgerRowHeight) - 8))
|
||||
const end = Math.min(total, start + visible + 16)
|
||||
return { start, end, padTop: start * ledgerRowHeight, padBottom: (total - end) * ledgerRowHeight }
|
||||
}
|
||||
export function ledgerCellPreview(value: string): string {
|
||||
if (value.length <= 400) return value
|
||||
let prefix = '',
|
||||
count = 0
|
||||
for (const point of value) {
|
||||
if (count++ === 400) return prefix + '…'
|
||||
prefix += point
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { ledgerWindow } from './qaLedgerRendering'
|
||||
it('keeps a bounded viewport while all records remain reachable without pagination', () => {
|
||||
const total = 6041,
|
||||
seen = new Set<number>()
|
||||
for (let top = 0; top < total * 108; top += 540) {
|
||||
const w = ledgerWindow(total, top, 600)
|
||||
expect(w.end - w.start).toBeLessThanOrEqual(23)
|
||||
expect(w.padTop + (w.end - w.start) * 108 + w.padBottom).toBe(total * 108)
|
||||
for (let i = w.start; i < w.end; i++) seen.add(i)
|
||||
}
|
||||
expect(seen.size).toBe(total)
|
||||
expect(ledgerWindow(total, total * 108, 600).end).toBe(total)
|
||||
})
|
||||
+95
-24
@@ -264,11 +264,34 @@
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.qa-ops-table .qa-ops-record-row {
|
||||
height: 108px;
|
||||
}
|
||||
.qa-ledger-actions {
|
||||
max-height: 84px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.qa-ledger-actions .qa-ai-task {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.qa-ops-table .qa-ops-record-row > td > span {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.qa-ops-table .qa-ledger-spacer > td {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
line-height: 0;
|
||||
}
|
||||
.qa-ops-table {
|
||||
width: 100%;
|
||||
min-width: 980px;
|
||||
border-collapse: collapse;
|
||||
table-layout: auto;
|
||||
table-layout: fixed;
|
||||
font-size: 13px;
|
||||
}
|
||||
.qa-ops-table th {
|
||||
@@ -321,44 +344,55 @@
|
||||
.qa-ops-page-bar {
|
||||
border-top: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-ops-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: rgb(15 23 32 / 28%);
|
||||
cursor: default;
|
||||
}
|
||||
.qa-ops-backdrop:hover {
|
||||
background: rgb(15 23 32 / 28%);
|
||||
}
|
||||
.qa-ops-drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
inset: 0 0 0 auto;
|
||||
z-index: 81;
|
||||
width: min(760px, 100vw);
|
||||
height: 100vh;
|
||||
overflow: auto;
|
||||
padding: 22px;
|
||||
height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
background: var(--bg-panel);
|
||||
border-left: 1px solid var(--border-strong);
|
||||
box-shadow: -8px 0 24px rgb(15 23 32 / 10%);
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.qa-ops-drawer > header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
gap: 14px;
|
||||
position: sticky;
|
||||
top: -22px;
|
||||
padding: 12px 0;
|
||||
padding: 16px 22px;
|
||||
background: var(--bg-panel);
|
||||
border-bottom: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-detail-quality {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
flex: none;
|
||||
gap: 8px;
|
||||
padding: 12px 22px;
|
||||
border-bottom: 1px solid var(--border-base);
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.qa-detail-quality > div {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
.qa-detail-quality > div > span {
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-detail-quality .qa-field-tag {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.qa-ops-drawer h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
@@ -368,6 +402,10 @@
|
||||
font-size: 14px;
|
||||
}
|
||||
.qa-ops-detail-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 0 22px 22px;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
overflow-wrap: anywhere;
|
||||
@@ -416,7 +454,14 @@
|
||||
max-height: 55vh;
|
||||
}
|
||||
.qa-ops-drawer {
|
||||
padding: 14px;
|
||||
padding: 0;
|
||||
}
|
||||
.qa-detail-quality {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
padding: 10px 14px;
|
||||
}
|
||||
.qa-ops-detail-content {
|
||||
padding: 0 14px 14px;
|
||||
}
|
||||
.qa-ops-detail-meta {
|
||||
grid-template-columns: 100px 1fr;
|
||||
@@ -633,3 +678,29 @@
|
||||
.qa-ai-hash {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.qa-ops-query .qa-query-action {
|
||||
width: 96px;
|
||||
height: 36px;
|
||||
flex: none;
|
||||
padding: 0 8px;
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-ops-query .qa-mirror-sync {
|
||||
position: relative;
|
||||
}
|
||||
.qa-ops-query .qa-mirror-sync-line {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.qa-ops-query .qa-mirror-sync > [role='status']:not(:empty),
|
||||
.qa-ops-query .qa-mirror-sync > .error-banner {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
right: 0;
|
||||
min-width: 260px;
|
||||
z-index: 4;
|
||||
padding: 6px 8px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-base);
|
||||
}
|
||||
|
||||
+12
-2
@@ -387,6 +387,17 @@ export function triggerPersonName(raw: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const qaAskedAtFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
|
||||
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
|
||||
if (column === 'trigger_person') return triggerPersonName(item.master_fields?.trigger_person ?? item.trigger_person)
|
||||
|
||||
@@ -439,7 +450,6 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
|
||||
if (item.feedback.up || item.feedback.down) return `其他人:赞 ${item.feedback.up} / 踩 ${item.feedback.down}`
|
||||
return null
|
||||
}
|
||||
if (column === 'asked_at')
|
||||
return new Date(item.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
if (column === 'asked_at') return qaAskedAtFormatter.format(new Date(item.asked_at))
|
||||
return item[column] || null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user