🎨 Unify project dictionaries as direct add edit and delete

This commit is contained in:
eust-w 2026-09-20 20:40:07 +08:00
parent d385919e28
commit 5c15aa8c9c
14 changed files with 255 additions and 327 deletions

View File

@ -1,16 +1,16 @@
# 舍弃原因字典
在项目“语义标签”页增加“舍弃原因字典”。管理员维护组织词条并按项目启用;切片、动作描述、舍弃原因三种字典分别按名称防重,不互相覆盖配置。项目移除词条只影响该项目;停用组织词条影响其所有引用项目,界面有确认提示。
在项目“语义标签”页增加“舍弃原因字典”。与切片、动作描述字典共用同一组件,直接添加、编辑、删除;只显示当前项目词条,无启用/停用开关。三个字典分别按名称防重,修改当前项目不改变其他项目及历史审核。
舍弃片段必须单选项目启用的原因。补充说明默认选填;“其他”或勾选“选择后必须补充说明”的词条要求说明,最多 1000 字。未配置时阻止新的舍弃并提示管理员配置;不自动生成示例词条。恢复为保留不依赖字典可用性。
舍弃片段必须单选项目已有的原因。补充说明默认选填;“其他”以及历史上已有说明要求的词条要求说明,最多 1000 字。未配置时阻止新的舍弃并提示管理员配置;不自动生成示例词条。恢复为保留不依赖字典可用性。
接口:
- `GET /api/annotation-labels?kind=discard_reason`:管理员组织字典。
- `POST /api/annotation-labels`、`PATCH /api/annotation-labels/{id}`:复用词条管理,新增 `requiresNote`。
- `GET/PUT /api/projects/{id}/discard-reason-labels`:项目可用词条/启用选择,PUT 使用 `labelIds`。
- `GET/PUT /api/projects/{id}/discard-reason-labels`:项目词条/项目引用列表,PUT 使用 `labelIds`。
- `POST /api/plugins/annotation-qa/tasks/{id}/slice-dispositions`:新增 `reasonLabelId`、`reasonVersion`、`reasonNote`;新舍弃不再接受自由文本原因作为替代。
后端校验组织、项目启用、词条类型、有效状态和版本;耗时的帧校验完成后再次检查词条。记录的 `discardReasonLabelId`、`discardReasonVersion`、`discardReasonName`、`discardReasonNote` 均由服务端确认。兼容字符串 `discardReason` 为名称与说明的可读组合。
后端校验组织、项目引用、词条类型、有效状态和版本;耗时的帧校验完成后再次检查词条。记录的 `discardReasonLabelId`、`discardReasonVersion`、`discardReasonName`、`discardReasonNote` 均由服务端确认。兼容字符串 `discardReason` 为名称与说明的可读组合。
已有自由文本原样保留并显示“历史填写”。普通保存不能篡改原因快照;字典改名/停用不追写历史。舍弃/恢复记录保留前后快照。新生成和复用媒体的审核 JSON 均保留词条快照。舍弃仍保留完整审核媒体,不改变切片边界,也不进入最终交付。

View File

@ -1,16 +1,13 @@
# 项目字典同名词条复用
# 项目字典:直接添加、编辑、删除
切片字典和动作描述字典的“添加”现在先查询组织内同类词条:已存在且有效时仅将其 ID 加入当前项目,不新建同名记录,不修改共享词条内容或历史。只有项目当前已启用的同名有效词条才提示重复。
切片、动作描述、舍弃原因三个字典统一使用 `AnnotationLabelsPanel`。界面只显示当前项目词条,采用相同输入框、编号列表、编辑和删除图标;没有启用、停用、勾选生效等操作。
从项目移除后,可直接重新添加,也可刷新后重新添加。保留后台名称唯一约束;并发创建遇到名称冲突时重新读取并复用成功创建的词条。新建成功但项目配置保存失败时,再次提交复用已有 ID,不留下重复记录。
直接添加时,有同名有效词条就复用并加入当前项目;本项目已有同名词条才提示重复。并发创建冲突后重新读取复用。新建成功但项目保存失败时,重试不重复创建。
编辑时不改变其他项目的共享词条:名称不变复用原 ID,改为组织内已有名称时切换当前项目引用,否则创建新词条。停用词条不自动恢复,并提示管理员处理。
历史 inactive 记录保留 ID、名称、版本、历史和旧项目引用。显式添加该名称时创建新的可用记录,只加入当前项目;数据库仅释放旧 inactive 记录占用的内部唯一键,不恢复旧记录、不改变其他项目内容。同名有效记录仍由唯一索引保证并发防重。
输入、编辑、新的保存或移除操作都会清除过期成功提示。失败与“已成功保存”不会同时显示。切换项目或字典类型后,过期查询不会继续创建新词条或更新另一个项目。
编辑不直接修改组织共享词条,只切换当前项目引用;删除仅从当前项目可选列表移除,已保存的切片、描述和舍弃审核快照不变。失败时清除旧成功提示,切换项目后不执行过期保存。
验证:
- `node --test tests/frontend/project-dictionary-reuse.test.mjs`
- Vite 在 `127.0.0.1:5177` 时运行 `node tests/browser/project-dictionary-reuse.mjs`;使用真实组件、独立模拟接口分别验证两个字典,不操作线上数据。
- `npm run lint:web`、`npm run build:web`。
舍弃字典不再提供“必须补充说明”的管理开关;舍弃弹窗保留补充说明,“其他”按原业务规则要求说明。既有历史记录不回写。
本次修改不包含线上字典绑定、推送或部署。
验证包括三个字典的添加、编辑、删除、重新添加、同名复用、历史停用名称、失败重试,以及独立 Mongo 数据库中的并发防重和历史保留。

View File

@ -343,14 +343,14 @@ func (server *server) handleProjectAnnotationLabelsPut(writer http.ResponseWrite
for _, id := range payload.LabelIDs {
id = strings.TrimSpace(id)
if _, ok := active[id]; !ok {
renderValidationError(writer, validationIssue{Field: "labelIds", Message: "项目只能启用当前组织中的有效标签"})
renderValidationError(writer, validationIssue{Field: "labelIds", Message: "项目只能添加当前组织中的有效词条"})
return
}
if _, exists := seen[id]; exists {
continue
}
if seenNames[nameKeys[id]] {
renderJSON(writer, http.StatusConflict, map[string]string{"error": "同一项目字典不能启用多个同名词条,请保留其中一个", "code": "dictionary_name_conflict"})
renderJSON(writer, http.StatusConflict, map[string]string{"error": "本项目不能添加多个同名词条,请保留其中一个", "code": "dictionary_name_conflict"})
return
}
seenNames[nameKeys[id]] = true

View File

@ -25,14 +25,14 @@ func (s *server) resolveDiscardReason(ctx context.Context, item *domain.HumanIte
}
}
if !enabled {
return issue("请从当前项目已启用的舍弃原因字典选择原因;未配置请联系管理员")
return issue("请从当前项目舍弃原因字典选择原因;没有词条请联系管理员添加")
}
label, err := s.store.GetAnnotationLabel(ctx, body.ReasonLabelID)
if err != nil {
return issue("舍弃原因读取失败,请重试")
}
if label == nil || label.OrganizationID != item.OrganizationID || dictionaryKind(label.Kind) != "discard_reason" || label.Status != domain.AnnotationLabelActive {
return issue("所选舍弃原因已停用或不可用,请刷新字典重新选择")
return issue("所选舍弃原因已不可用,请刷新字典重新选择")
}
if label.Version != body.ReasonVersion {
return issue("所选舍弃原因已更新,请刷新字典并重新确认")

View File

@ -0,0 +1,78 @@
package api
import (
"context"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// Explicit isolated database only; exercises an old inactive unique-key owner
// against the real Mongo unique index without touching business collections.
func TestUnifiedDictionaryMongoLifecycle(t *testing.T) {
if os.Getenv("UNIFIED_DICTIONARY_MONGO_TEST") != "1" {
t.Skip("isolated Mongo opt-in")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
c, e := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if e != nil {
t.Fatal("Mongo connection")
}
defer c.Disconnect(context.Background())
name := fmt.Sprintf("unified_dictionary_test_%d", time.Now().UnixNano())
if !strings.HasPrefix(name, "unified_dictionary_test_") || name == os.Getenv("MONGO_DB") {
t.Fatal("database scope")
}
db := c.Database(name)
defer db.Drop(context.Background())
s := store.NewMongoStore(db)
_, e = db.Collection("annotationLabels").Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{{Key: "organizationId", Value: 1}, {Key: "nameKey", Value: 1}}, Options: options.Index().SetName("organizationId_nameKey_unique").SetUnique(true).SetPartialFilterExpression(bson.M{"nameKey": bson.M{"$type": "string"}})})
if e != nil {
t.Fatal(e)
}
for _, kind := range []string{"action", "slice", "discard_reason"} {
old := domain.AnnotationLabelRecord{ID: "old-" + kind, OrganizationID: "org", Kind: kind, Code: "old-" + kind, Name: "历史名称", NameKey: domain.DictionaryNameKey(kind, "历史名称"), Status: domain.AnnotationLabelInactive, Version: 7, History: []domain.AnnotationLabelRevision{{Version: 7, Name: "历史名称", Status: domain.AnnotationLabelInactive}}}
if _, e = db.Collection("annotationLabels").InsertOne(ctx, old); e != nil {
t.Fatal(e)
}
var wins atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 12; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fresh := old
fresh.ID = fmt.Sprintf("new-%s-%d", kind, i)
fresh.Code = fresh.ID
fresh.Status = domain.AnnotationLabelActive
fresh.Version = 1
fresh.History = nil
e := s.UpsertAnnotationLabel(ctx, fresh)
if e == nil {
wins.Add(1)
} else if !errors.Is(e, store.ErrAnnotationLabelNameConflict) {
t.Errorf("unexpected: %v", e)
}
}(i)
}
wg.Wait()
if wins.Load() != 1 {
t.Fatalf("%s created %d duplicates", kind, wins.Load())
}
kept, e := s.GetAnnotationLabel(ctx, old.ID)
if e != nil || kept.Status != domain.AnnotationLabelInactive || kept.Version != 7 || kept.Name != old.Name || len(kept.History) != 1 {
t.Fatalf("changed history %s", kind)
}
}
}

View File

@ -39,12 +39,21 @@ func (store *MemoryStore) GetAnnotationLabel(_ context.Context, id string) (*dom
return &copy, nil
}
// Historical inactive terms keep their ID/text and references, but do not
// reserve a name needed by a newly added project term.
func annotationLabelStorageNameKey(item domain.AnnotationLabelRecord) string {
if item.Status == domain.AnnotationLabelInactive {
return "inactive:" + item.ID
}
return domain.DictionaryNameKey(item.Kind, item.Name)
}
func (store *MemoryStore) UpsertAnnotationLabel(_ context.Context, item domain.AnnotationLabelRecord) error {
store.mu.Lock()
defer store.mu.Unlock()
item.NameKey = domain.DictionaryNameKey(item.Kind, item.Name)
item.NameKey = annotationLabelStorageNameKey(item)
for _, other := range store.annotationLabels {
if other.ID != item.ID && organizationMatches(other.OrganizationID, item.OrganizationID) && domain.DictionaryNameKey(other.Kind, other.Name) == item.NameKey {
if item.Status != domain.AnnotationLabelInactive && other.Status != domain.AnnotationLabelInactive && other.ID != item.ID && organizationMatches(other.OrganizationID, item.OrganizationID) && domain.DictionaryNameKey(other.Kind, other.Name) == item.NameKey {
return ErrAnnotationLabelNameConflict
}
}
@ -102,15 +111,25 @@ func (store *MongoStore) GetAnnotationLabel(ctx context.Context, id string) (*do
}
func (store *MongoStore) UpsertAnnotationLabel(ctx context.Context, item domain.AnnotationLabelRecord) error {
item.NameKey = domain.DictionaryNameKey(item.Kind, item.Name)
item.NameKey = annotationLabelStorageNameKey(item)
// Legacy duplicates have no key: still refuse new collisions with them.
items, err := store.ListAnnotationLabels(ctx, item.OrganizationID)
if err != nil {
return err
}
for _, other := range items {
if other.ID != item.ID && domain.DictionaryNameKey(other.Kind, other.Name) == item.NameKey {
return ErrAnnotationLabelNameConflict
if item.Status != domain.AnnotationLabelInactive && other.ID != item.ID && domain.DictionaryNameKey(other.Kind, other.Name) == item.NameKey {
if other.Status != domain.AnnotationLabelInactive {
return ErrAnnotationLabelNameConflict
}
// Release only an old inactive key, without reactivating or renaming its
// record. A concurrent reactivation still wins the unique index safely.
if other.NameKey == item.NameKey {
_, err = store.annotationLabels.UpdateOne(ctx, bson.M{"id": other.ID, "organizationId": other.OrganizationID, "status": domain.AnnotationLabelInactive, "nameKey": item.NameKey}, bson.M{"$set": bson.M{"nameKey": annotationLabelStorageNameKey(other)}})
if err != nil {
return err
}
}
}
}
_, err = store.annotationLabels.UpdateOne(ctx, bson.M{"id": item.ID}, bson.M{"$set": item}, options.Update().SetUpsert(true))
@ -138,7 +157,7 @@ func (store *MongoStore) backfillDictionaryNameKeys(ctx context.Context) error {
}
}
for _, item := range items {
key := domain.DictionaryNameKey(item.Kind, item.Name)
key := annotationLabelStorageNameKey(item)
group := item.OrganizationID + "\x00" + key
if item.NameKey != "" || owned[group] {
continue

View File

@ -93,4 +93,50 @@ func TestDictionaryNameUniquenessMongo(t *testing.T) {
t.Fatal("legacy duplicate bypass", e)
}
exerciseDictionaryNameRace(t, s)
// Simulate an old inactive record that still owns the pre-fix unique key.
_, e = db.Collection("annotationLabels").InsertOne(ctx, bson.M{"id": "inactive-old", "organizationId": "inactive-org", "kind": "discard_reason", "code": "old", "name": "历史原因", "nameKey": "discard_reason:历史原因", "status": "inactive", "version": 7, "history": bson.A{bson.M{"version": 7, "name": "历史原因", "status": "inactive"}}})
if e != nil {
t.Fatal(e)
}
exerciseInactiveDictionaryReuse(t, s)
}
func exerciseInactiveDictionaryReuse(t *testing.T, s Store) {
t.Helper()
ctx := context.Background()
old := domain.AnnotationLabelRecord{ID: "inactive-old", OrganizationID: "inactive-org", Kind: "discard_reason", Code: "old", Name: "历史原因", Status: domain.AnnotationLabelInactive, Version: 7, History: []domain.AnnotationLabelRevision{{Version: 7, Name: "历史原因", Status: domain.AnnotationLabelInactive}}}
if _, ok := s.(*MongoStore); !ok {
if e := s.UpsertAnnotationLabel(ctx, old); e != nil {
t.Fatal(e)
}
}
selection := domain.ProjectAnnotationLabelsRecord{ID: "selection", OrganizationID: old.OrganizationID, ProjectID: "other-project", DiscardReasonLabelIDs: []string{old.ID}}
if e := s.UpsertProjectDiscardReasonLabels(ctx, selection); e != nil {
t.Fatal(e)
}
fresh := old
fresh.ID = "new-active"
fresh.Code = "fresh"
fresh.Status = domain.AnnotationLabelActive
fresh.Version = 1
fresh.History = nil
if e := s.UpsertAnnotationLabel(ctx, fresh); e != nil {
t.Fatal("inactive name blocked add", e)
}
retained, e := s.GetAnnotationLabel(ctx, old.ID)
if e != nil || retained.Status != domain.AnnotationLabelInactive || retained.Version != 7 || retained.Name != old.Name || len(retained.History) != 1 {
t.Fatal("changed historical term", e)
}
other, e := s.GetProjectAnnotationLabels(ctx, selection.ProjectID)
if e != nil || len(other.DiscardReasonLabelIDs) != 1 || other.DiscardReasonLabelIDs[0] != old.ID {
t.Fatal("changed another project", e)
}
duplicate := fresh
duplicate.ID = "duplicate-active"
if e := s.UpsertAnnotationLabel(ctx, duplicate); !errors.Is(e, ErrAnnotationLabelNameConflict) {
t.Fatal("active duplicate accepted", e)
}
}
func TestInactiveDictionaryAddPreservesHistoryMemory(t *testing.T) {
exerciseInactiveDictionaryReuse(t, NewMemoryStore())
}

View File

@ -14,10 +14,14 @@ export function AnnotationLabelsPanel({
key?: string;
projectId: string;
canManage: boolean;
kind?: "action" | "slice";
kind?: "action" | "slice" | "discard_reason";
}) {
const isSlice = kind === "slice";
const selectionPath = `/api/projects/${projectId}/${isSlice ? "slice-labels" : "annotation-labels"}`;
const isDiscard = kind === "discard_reason";
const projectScoped = kind !== "action";
const noun = isSlice ? "切片名称" : isDiscard ? "舍弃原因" : "描述";
const title = isSlice ? "项目切片字典" : isDiscard ? "项目舍弃原因字典" : "项目动作描述字典";
const selectionPath = `/api/projects/${projectId}/${isSlice ? "slice-labels" : isDiscard ? "discard-reason-labels" : "annotation-labels"}`;
const [labels, setLabels] = useState<AnnotationLabelRecord[]>([]);
const [enabled, setEnabled] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
@ -34,14 +38,18 @@ export function AnnotationLabelsPanel({
try {
const selectionRequest = apiRequest<ProjectAnnotationLabelsRecord>(selectionPath, { signal });
const [dictionary, selection] = await Promise.all([
isSlice
projectScoped
? selectionRequest.then((result) => ({ items: result.items || [] }))
: apiRequest<{ items: AnnotationLabelRecord[] }>("/api/annotation-labels", { signal }),
selectionRequest,
]);
if (scope.current !== generation || signal.aborted) return;
setLabels(dictionary.items || []);
setEnabled(isSlice ? dictionary.items.map((item) => item.id) : selection.labelIds || []);
setEnabled(
(selection.labelIds || []).filter((id) =>
dictionary.items.some((item) => item.id === id && item.status !== "inactive"),
),
);
} catch (loadError) {
if (scope.current !== generation || signal.aborted) return;
setError(getActionErrorMessage(loadError, "加载标签字典失败"));
@ -94,7 +102,7 @@ export function AnnotationLabelsPanel({
projectDictionaryNameKey(kind, label.name) === projectDictionaryNameKey(kind, text),
)
) {
setError("本项目已启用同名词条,无需重复添加");
setError("本项目已存在同名词条,无需重复添加");
return;
}
setSaving(true);
@ -141,15 +149,14 @@ export function AnnotationLabelsPanel({
resetEditing();
} catch (saveError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(saveError, editingLabelId ? "更新描述失败" : "添加描述失败"));
setError(getActionErrorMessage(saveError, `${editingLabelId ? "更新" : "添加"}${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
};
const deleteLabel = async (label: AnnotationLabelRecord) => {
if (!window.confirm(isSlice ? "确认从本项目移除此切片名称?已保存的切片名称不会改变。" : "确认删除此描述?"))
return;
if (!window.confirm(`确认从本项目删除此${noun}?已保存的标注和审核记录不会改变。`)) return;
setSaving(true);
setSaveSuccess(false);
setError("");
@ -166,7 +173,7 @@ export function AnnotationLabelsPanel({
if (editingLabelId === label.id) resetEditing();
} catch (delError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(delError, "删除描述失败"));
setError(getActionErrorMessage(delError, `删除${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
@ -175,8 +182,8 @@ export function AnnotationLabelsPanel({
const activeLabels = labels.filter((item) => item.status !== "inactive" && enabled.includes(item.id));
return (
<section className="space-y-4" aria-label={isSlice ? "项目切片字典" : "项目动作描述字典"}>
{isSlice && <p className="text-sm text-slate-500">用于填写切片名称,与动作描述字典独立配置。</p>}
<section className="space-y-4" aria-label={title}>
<p className="text-sm text-slate-500">添加后即可在本项目使用,三个字典独立管理。</p>
{/* Top action and input bar */}
{canManage && (
<form onSubmit={saveLabel} className="flex flex-wrap items-center gap-3">
@ -188,7 +195,13 @@ export function AnnotationLabelsPanel({
setError("");
}}
disabled={saving || loading}
placeholder={isSlice ? "输入切片名称,如:商品检查" : "输入描述内容,如:右手自上而下稳定抓取桌面上的水瓶"}
placeholder={
isSlice
? "输入切片名称,如:商品检查"
: isDiscard
? "输入舍弃原因,如:调整头环"
: "输入描述内容,如:右手自上而下稳定抓取桌面上的水瓶"
}
className="flex-1 min-w-[280px] rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2.5 text-sm text-[color:var(--app-text)] shadow-sm focus:border-blue-500 focus:outline-none"
/>
<button
@ -197,7 +210,7 @@ export function AnnotationLabelsPanel({
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
{editingLabelId ? <Save className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
{editingLabelId ? "保存修改" : isSlice ? "添加名称" : "添加描述"}
{editingLabelId ? "保存修改" : isSlice ? "添加名称" : isDiscard ? "添加原因" : "添加描述"}
</button>
{editingLabelId && (
<button
@ -220,7 +233,7 @@ export function AnnotationLabelsPanel({
{saveSuccess && (
<div className="rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-4 py-2.5 text-sm text-emerald-700 dark:text-emerald-300">
✓ {isSlice ? "项目切片字典已成功保存" : "项目语义描述已成功保存"}
✓ {title}已成功保存
</div>
)}
@ -229,12 +242,10 @@ export function AnnotationLabelsPanel({
{loading ? (
<div className="flex items-center justify-center gap-2 py-12 text-sm text-slate-500 dark:text-gray-400">
<Loader2 className="h-4 w-4 animate-spin text-blue-500" />
正在加载描述列表...
正在加载{noun}列表…
</div>
) : activeLabels.length === 0 ? (
<div className="py-12 text-center text-sm text-slate-500 dark:text-gray-400">
{isSlice ? "暂无切片名称,可在上方添加;标注员仍可手动输入。" : "暂无描述内容,请在上方输入添加。"}
</div>
<div className="py-12 text-center text-sm text-slate-500 dark:text-gray-400">暂无{noun},请在上方添加。</div>
) : (
<div className="divide-y divide-slate-100 dark:divide-[#202227]">
{activeLabels.map((item, index) => {
@ -264,7 +275,7 @@ export function AnnotationLabelsPanel({
onClick={() => startEdit(item)}
disabled={saving}
className="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700 dark:text-gray-500 dark:hover:bg-white/5 dark:hover:text-white transition-colors"
title={isSlice ? "编辑切片名称" : "编辑描述"}
title={`编辑${noun}`}
>
<Edit3 className="h-4 w-4" />
</button>
@ -273,7 +284,7 @@ export function AnnotationLabelsPanel({
onClick={() => void deleteLabel(item)}
disabled={saving}
className="rounded p-1.5 text-slate-400 hover:bg-red-50 hover:text-red-600 dark:text-gray-500 dark:hover:bg-red-500/10 dark:hover:text-red-400 transition-colors"
title={isSlice ? "移除切片名称" : "删除描述"}
title={`删除${noun}`}
>
<Trash2 className="h-4 w-4" />
</button>
@ -285,7 +296,9 @@ export function AnnotationLabelsPanel({
</div>
)}
</div>
{isSlice && <p className="text-sm text-slate-500">修改或移除字典项,不影响已保存的切片名称。</p>}
<p className="text-sm text-slate-500">
编辑或删除只影响本项目的可选词条,不影响其他项目及已保存的标注、审核记录。
</p>
</section>
);
}

View File

@ -1,227 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { apiRequest } from "../services/api/client";
import type { AnnotationLabelRecord } from "../types";
import { getActionErrorMessage } from "../lib/action-errors.js";
export function DiscardReasonDictionaryPanel({
projectId,
canManage,
}: {
key?: string;
projectId: string;
canManage: boolean;
}) {
const [items, setItems] = useState<AnnotationLabelRecord[]>([]),
[enabled, setEnabled] = useState<string[]>([]);
const [query, setQuery] = useState(""),
[name, setName] = useState(""),
[note, setNote] = useState(false),
[editing, setEditing] = useState("");
const [loading, setLoading] = useState(true),
[saving, setSaving] = useState(false),
[error, setError] = useState(""),
[notice, setNotice] = useState("");
const generation = useRef(0);
const path = `/api/projects/${projectId}/discard-reason-labels`;
const load = async () => {
const g = ++generation.current;
setLoading(true);
setError("");
try {
const [selection, dictionary] = await Promise.all([
apiRequest<{ labelIds: string[]; items: AnnotationLabelRecord[] }>(path),
canManage
? apiRequest<{ items: AnnotationLabelRecord[] }>("/api/annotation-labels?kind=discard_reason")
: Promise.resolve(null),
]);
if (g !== generation.current) return;
setEnabled(selection.labelIds);
setItems(dictionary?.items || selection.items);
} catch (e) {
if (g === generation.current) setError(getActionErrorMessage(e, "加载舍弃原因失败"));
} finally {
if (g === generation.current) setLoading(false);
}
};
useEffect(() => {
setItems([]);
setEnabled([]);
setEditing("");
setName("");
setNote(false);
void load();
return () => {
generation.current++;
};
}, [projectId, canManage]);
const action = async (fn: () => Promise<void>) => {
const g = generation.current;
setSaving(true);
setError("");
setNotice("");
try {
await fn();
if (g !== generation.current) return;
setNotice("已保存");
await load();
} catch (e) {
if (g === generation.current) setError(getActionErrorMessage(e, "保存失败"));
} finally {
setSaving(false);
}
};
const select = async (ids: string[]) => {
await apiRequest(
path,
{ method: "PUT" },
{ labelIds: ids.filter((id) => items.find((x) => x.id === id)?.status !== "inactive") },
);
};
const save = () =>
action(async () => {
const old = items.find((x) => x.id === editing);
const label = await apiRequest<AnnotationLabelRecord>(
editing ? `/api/annotation-labels/${editing}` : "/api/annotation-labels",
{ method: editing ? "PATCH" : "POST" },
{
kind: "discard_reason",
code:
old?.code ||
`discard_${globalThis.crypto?.randomUUID?.() || `${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}`,
name: name.trim(),
requiresNote: note || name.trim() === "其他",
status: old?.status || "active",
},
);
if (!editing) await select([...enabled, label.id]);
setEditing("");
setName("");
setNote(false);
});
return (
<section aria-label="项目舍弃原因字典" className="space-y-4">
<p className="text-sm text-slate-500">
从组织词条中启用本项目原因。新增词条自动启用;改名或停用不改变历史舍弃记录。停用会影响所有引用该词条的项目。
</p>
<input
aria-label="搜索舍弃原因词条"
placeholder="搜索舍弃原因"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full rounded border p-2"
/>
{canManage && (
<form
onSubmit={(e) => {
e.preventDefault();
void save();
}}
className="flex flex-wrap items-center gap-3"
>
<input
aria-label="原因名称"
placeholder="原因名称,例如:调整头环"
value={name}
onChange={(e) => setName(e.target.value)}
className="rounded border p-2"
/>
<label>
<input
type="checkbox"
checked={note || name.trim() === "其他"}
disabled={name.trim() === "其他"}
onChange={(e) => setNote(e.target.checked)}
/>
选择后必须补充说明
</label>
<button disabled={loading || saving || !name.trim()} className="rounded bg-blue-600 px-4 py-2 text-white">
{editing ? "保存修改" : "添加原因"}
</button>
{editing && (
<button
type="button"
onClick={() => {
setEditing("");
setName("");
setNote(false);
}}
>
取消编辑
</button>
)}
</form>
)}
{error && (
<div role="alert" className="text-red-600">
{error}
<button className="ml-3 underline" onClick={() => void load()}>
重试
</button>
</div>
)}
{notice && <p role="status">{notice}</p>}
{loading ? (
<p>正在加载舍弃原因…</p>
) : (
<ul className="divide-y rounded border">
{items
.filter((x) => x.name.toLowerCase().includes(query.trim().toLowerCase()))
.map((item) => (
<li key={item.id} className="flex flex-wrap items-center gap-3 p-3">
<label className="flex flex-1 items-center gap-2">
<input
aria-label={`启用原因 ${item.name}`}
type="checkbox"
checked={enabled.includes(item.id)}
disabled={!canManage || saving || item.status !== "active"}
onChange={(e) =>
void action(() =>
select(e.target.checked ? [...enabled, item.id] : enabled.filter((id) => id !== item.id)),
)
}
/>
{item.name}
{item.requiresNote && <span className="text-xs text-slate-500">需补充说明</span>}
{item.status === "inactive" && <span>已停用</span>}
</label>
{canManage && (
<>
<button
disabled={saving}
onClick={() => {
setEditing(item.id);
setName(item.name);
setNote(Boolean(item.requiresNote));
}}
>
编辑
</button>
<button
disabled={saving}
onClick={() => {
if (
window.confirm(
`${item.status === "active" ? "停用" : "启用"}组织词条“${item.name}”?已保存的审核原因不变。`,
)
)
void action(async () => {
await apiRequest(
`/api/annotation-labels/${item.id}`,
{ method: "PATCH" },
{ ...item, status: item.status === "active" ? "inactive" : "active" },
);
});
}}
>
{item.status === "active" ? "停用" : "启用"}
</button>
</>
)}
</li>
))}
</ul>
)}
{!loading && items.length === 0 && <p>当前尚无舍弃原因词条,请联系管理员配置。</p>}
</section>
);
}

View File

@ -19,7 +19,7 @@ export async function reuseOrCreateDictionaryLabel({ kind, name, preferredId, li
const matches = records.filter((label) => projectDictionaryNameKey(label.kind, label.name) === key);
const active = matches.filter((label) => label.status === "active");
if (active.length) return active.find((label) => label.id === preferredId) || active[0];
if (matches.length) throw new Error("同名词条已停用,请由管理员启用后再添加到项目;不会自动恢复停用词条。");
// Inactive records remain historical; create a new term without changing their references.
return null;
};
const existing = await lookup();

View File

@ -1,4 +1,3 @@
import { DiscardReasonDictionaryPanel } from "../components/DiscardReasonDictionaryPanel";
import React, { useEffect, useState, useDeferredValue } from "react";
import { continuousProcessingStatus } from "../lib/continuous-processing.js";
import { Link, useParams, useNavigate } from "react-router-dom";
@ -1816,20 +1815,12 @@ export default function ProjectDetail() {
</button>
))}
</div>
{dictionaryKind === "discard_reason" ? (
<DiscardReasonDictionaryPanel
key={project.id}
projectId={project.id}
canManage={isOrganizationAdminRole(role)}
/>
) : (
<AnnotationLabelsPanel
key={`${project.id}:${dictionaryKind}`}
kind={dictionaryKind}
projectId={project.id}
canManage={isOrganizationAdminRole(role)}
/>
)}
<AnnotationLabelsPanel
key={`${project.id}:${dictionaryKind}`}
kind={dictionaryKind}
projectId={project.id}
canManage={isOrganizationAdminRole(role)}
/>
</div>
)}

View File

@ -51,25 +51,15 @@ try {
body: `<!doctype html><html><head><meta charset="utf-8"><title>舍弃原因字典验证</title></head><body><div id="root"></div><script type="module">
import Rf from '/@react-refresh';Rf.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>t=>t;window.__vite_plugin_react_preamble_installed__=true;
const R=await import('/node_modules/.vite/deps/react.js'),React=R.default||R,D=await import('/node_modules/.vite/deps/react-dom_client.js');const root=(D.createRoot||D.default.createRoot)(document.getElementById('root'));
await import('/src/index.css');const {CaptureAnnotationWorkbench}=await import('/src/components/CaptureAnnotationWorkbench.tsx');const {DiscardReasonDictionaryPanel}=await import('/src/components/DiscardReasonDictionaryPanel.tsx');
await import('/src/index.css');const {CaptureAnnotationWorkbench}=await import('/src/components/CaptureAnnotationWorkbench.tsx');
window.calls=[];window.rejectName=false;let options=[];
window.showWorkbench=async()=>{const data=await (await fetch('/api/projects/demo/discard-reason-labels')).json();options=data.items;root.render(React.createElement(CaptureAnnotationWorkbench,{clipStart:0,clipEnd:10,slices:[{id:'a',name:'旧切片',start:0,end:10}],segments:[],statuses:{},phase:'slice',onChange:()=>{},discardReasons:options,onRefreshDiscardReasons:()=>{},onSliceDispositionChange:async(id,disposition,choice)=>{if(window.rejectName)throw Error('Validation failed (sliceSegments.0.name: 切片 1(旧切片)需要从本项目切片字典重新选择名称)');window.calls.push({id,disposition,...choice});return true}}))};
window.showAdmin=()=>root.render(React.createElement(DiscardReasonDictionaryPanel,{projectId:'demo',canManage:true}));window.showAdmin();
window.showWorkbench();
</script></body></html>`,
}),
);
await page.goto(base + "/__discard_test");
await page.getByRole("checkbox", { name: "启用原因 调整头环" }).waitFor();
await page.getByRole("textbox", { name: "原因名称", exact: true }).fill("相机遮挡");
await page.getByRole("button", { name: "添加原因", exact: true }).click();
await page.getByRole("checkbox", { name: "启用原因 相机遮挡" }).waitFor();
assert.ok(enabled.includes("new"));
await Promise.all([
page.waitForResponse((r) => r.url().includes("/discard-reason-labels") && r.request().method() === "GET"),
page.getByRole("checkbox", { name: "启用原因 相机遮挡" }).click(),
]);
assert.ok(!enabled.includes("new"));
await page.screenshot({ path: out + "/admin.png" });
await page.waitForFunction(() => typeof window.showWorkbench === "function");
await page.evaluate(() => window.showWorkbench());
await page.getByRole("button", { name: "舍弃片段", exact: true }).click();
const dialog = page.locator("dialog[open]"),

View File

@ -1,19 +1,19 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
import fs from "node:fs/promises";
const base = process.env.DICTIONARY_TEST_URL || "http://127.0.0.1:5177",
const base = process.env.DICTIONARY_TEST_URL || "http://127.0.0.1:5178",
out = process.env.DICTIONARY_TEST_OUTPUT || "verification/dictionary-reuse";
await fs.mkdir(out, { recursive: true });
const browser = await chromium.launch({ channel: "chrome", headless: true });
try {
for (const kind of ["slice", "action"]) {
for (const kind of ["slice", "action", "discard_reason"]) {
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => d.accept());
let creates = 0,
failSelection = false;
let enabled = [];
let enabled = ["disabled"];
const labels = [
{ id: "existing", kind, name: "表面清洁", description: "表面清洁", status: "active", version: 3 },
{ id: "disabled", kind, name: "停用词条", status: "inactive", version: 1 },
@ -55,7 +55,10 @@ try {
await page.goto(base + "/__dictionary_reuse");
assert.equal(await page.title(), "项目字典复用验证");
const input = page.getByRole("textbox"),
add = page.getByRole("button", { name: kind === "slice" ? "添加名称" : "添加描述", exact: true });
add = page.getByRole("button", {
name: kind === "slice" ? "添加名称" : kind === "discard_reason" ? "添加原因" : "添加描述",
exact: true,
});
await input.fill("表面清洁");
await add.click();
await page.getByText("表面清洁", { exact: true }).waitFor();
@ -64,10 +67,15 @@ try {
assert.equal(labels[0].version, 3);
await input.fill("表面清洁");
await add.click();
await page.getByText("本项目已启用同名词条,无需重复添加", { exact: true }).waitFor();
await page.getByText("本项目已存在同名词条,无需重复添加", { exact: true }).waitFor();
assert.equal(await page.getByText(/已成功保存/).count(), 0);
assert.equal(creates, 0);
await page.getByRole("button", { name: kind === "slice" ? "移除切片名称" : "删除描述", exact: true }).click();
await page
.getByRole("button", {
name: kind === "slice" ? "删除切片名称" : kind === "discard_reason" ? "删除舍弃原因" : "删除描述",
exact: true,
})
.click();
await page.getByText("表面清洁", { exact: true }).waitFor({ state: "hidden" });
await input.fill("表面清洁");
await add.click();
@ -77,27 +85,41 @@ try {
assert.equal(await page.getByText("表面清洁", { exact: true }).count(), 1);
await page.reload();
await page.getByText("表面清洁", { exact: true }).waitFor();
await page.getByRole("button", { name: kind === "slice" ? "编辑切片名称" : "编辑描述", exact: true }).click();
await page
.getByRole("button", {
name: kind === "slice" ? "编辑切片名称" : kind === "discard_reason" ? "编辑舍弃原因" : "编辑描述",
exact: true,
})
.click();
await page.getByRole("button", { name: "保存修改", exact: true }).click();
await add.waitFor();
assert.equal(creates, 0);
assert.deepEqual(enabled, ["existing"]);
await input.fill("停用词条");
await add.click();
await page.getByText(/同名词条已停用/).waitFor();
assert.equal(await page.getByText(/已成功保存/).count(), 0);
assert.equal(creates, 0);
await page.getByText("停用词条", { exact: true }).waitFor();
assert.equal(creates, 1);
assert.equal(labels.find((x) => x.id === "disabled").status, "inactive");
assert.equal(await page.getByRole("checkbox").count(), 0);
assert.equal(await page.getByRole("button", { name: /启用|停用/ }).count(), 0);
failSelection = true;
await input.fill("新词条");
await add.click();
await page.getByText("项目配置保存失败,请重试", { exact: true }).waitFor();
assert.equal(creates, 1);
assert.equal(creates, 2);
assert.equal(await page.getByText(/已成功保存/).count(), 0);
failSelection = false;
await add.click();
await page.getByText("新词条", { exact: true }).waitFor();
assert.equal(creates, 1, "retry reuses the previously created term");
assert.deepEqual(enabled, ["existing", "new-1"]);
assert.equal(creates, 2, "retry reuses the previously created term");
assert.deepEqual(enabled, ["existing", "new-1", "new-2"]);
await page.getByText("表面清洁", { exact: true }).click();
await input.fill("当前项目新名称");
await page.getByRole("button", { name: "保存修改", exact: true }).click();
await page.getByText("当前项目新名称", { exact: true }).waitFor();
assert.equal(labels.find((x) => x.id === "existing").name, "表面清洁");
assert.ok(!enabled.includes("existing"));
assert.equal(creates, 3);
assert.deepEqual(errors, []);
await page.screenshot({ path: out + "/" + kind + ".png", fullPage: true });
console.log("PASS", kind, "reuse, remove/re-add, duplicate, disabled, unchanged edit, partial-save retry");

View File

@ -31,20 +31,19 @@ test("name normalization and dictionary kinds are independent", async () => {
});
assert.ok(created);
});
test("disabled names do not reactivate or create duplicates", async () => {
await assert.rejects(
() =>
reuseOrCreateDictionaryLabel({
kind: "slice",
name: existing.name,
list: async () => [{ ...existing, status: "inactive" }],
create: async () => {
throw Error("must not create");
},
}),
/已停用/,
);
test("historical inactive terms allow a new record without reactivating old references", async () => {
const old = Object.freeze({ ...existing, status: "inactive" });
const result = await reuseOrCreateDictionaryLabel({
kind: "slice",
name: existing.name,
list: async () => [old],
create: async () => ({ ...existing, id: "new" }),
});
assert.equal(result.id, "new");
assert.equal(old.status, "inactive");
assert.equal(old.version, 3);
});
test("concurrent creator is reread after unique constraint rejection", async () => {
let lists = 0;
const result = await reuseOrCreateDictionaryLabel({