droboticflow/internal/api/inplace_slice_editing_test.go
d-robotics 8950746fca ✨ 06: restore first-pass reslice behind a submission-history gate
- server: handleSliceResetCreate splits on submission history using the
  established isRework signals (task revision fence, rework status, human
  annotation revision via fanyuV5CombinedSubmissionIsRework); first pass
  runs the original reset write path with sliceResetHistory audit, history
  keeps 409 slice_reset_disabled with in-place guidance (spec D1 revised)
- table tests pin both classes incl. the system-suggestion edge; the four
  retired-contract test files flip to split-flow assertions
- frontend: restore the reslice button, warning dialog with both reset
  modes, and authoritative reconciliation from f980696f~1; entry is gated
  client-side by the same signals (resliceEligible), normal and focused
  layouts share the restored footer entry; E-mode changes untouched
- dev preview regains the entry; two retirement-era nail assertions flip
  back with the gate asserted in their place
2026-10-14 21:55:29 +08:00

279 lines
13 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"droboticflow/internal/domain"
)
// seam ② (spec §6): server-side validation table tests for in-place slice
// structure editing. The annotate-phase stage locks are removed (R2-Q7:a) —
// first-pass and rework share one path — while "each action fully inside
// exactly one slice" plus the pending/described/invalid whitelist stay the
// bottom line; the reslice write endpoint is first-pass only and refuses
// submission history with a pointer to in-place editing (R3-2:a, ticket 06).
func enterAnnotatePhase(t *testing.T, f combinedDraftFixture, item domain.HumanItemRecord) domain.HumanItemRecord {
t.Helper()
item.Subject.Payload["sliceWorkflow"] = map[string]any{"phase": "annotate", "status": "completed"}
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
return item
}
// applyLegacySliceResetState reproduces on the item exactly the payload the
// retired reslice endpoint used to write. The write path is disabled, but
// historical post-reset data still exists, so tests keep covering the
// invariants over it (pre-reset evidence must stay untrusted).
func applyLegacySliceResetState(t *testing.T, f combinedDraftFixture) domain.HumanItemRecord {
t.Helper()
item, _ := readSliceRestoration(t, f)
draft := annotationWorkspacePayload(&item)
slices := descriptionOnlySlices(decodeMaterializationValue[domain.SliceSegment](draft["sliceSegments"]))
if len(slices) == 0 {
revisions, err := f.store.ListSliceRevisions(f.ctx, item.OrganizationID, item.LegacyTaskID)
if err != nil {
t.Fatal(err)
}
if len(revisions) > 0 {
slices = descriptionOnlySlices(revisions[len(revisions)-1].Segments)
}
}
now := nowISO()
resetHistory, _ := normalizeStructuredValue(item.Subject.Payload["sliceResetHistory"]).([]any)
resetHistory = append(resetHistory, map[string]any{"workspace": draft, "actorUserId": f.annotator.ID, "at": now, "itemVersion": item.Version + 1, "resetToUnifiedRange": false})
for i := range slices {
slices[i].DiscardedAnnotations = nil
}
item.Subject.Payload["sliceResetHistory"] = resetHistory
item.Subject.Payload["annotationWorkspace"] = map[string]any{
"sliceSegments": slices, "operations": []domain.SliceOperation{}, "segments": []domain.AnnotationSegment{},
"statuses": pendingSliceStatuses(slices), "userId": f.annotator.ID, "savedAt": now,
}
delete(item.Subject.Payload, "annotationDraft")
delete(item.Subject.Payload, sliceRestoreEvidenceKey)
delete(item.Subject.Payload, sliceArchiveEditsKey)
delete(item.Subject.Payload, sliceMergeEvidenceKey)
item.Subject.Payload["sliceWorkflow"] = map[string]any{"status": "editing", "phase": "slice", "resetAt": now, "resetFromVersion": item.Version, "resetToUnifiedRange": false, "revision": intValue(mapValue(item.Subject.Payload["sliceWorkflow"])["revision"])}
expected := item.Version
item.Version++
item.UpdatedAt = now
if updated, err := f.store.UpdateHumanItemVersioned(f.ctx, item, expected); err != nil || !updated {
t.Fatalf("legacy reset state was not persisted: updated=%v err=%v", updated, err)
}
return item
}
func TestAnnotatePhaseSliceStructureEditingIsUnlocked(t *testing.T) {
for _, scenario := range []string{"discarded-boundary-move", "kept-slice-merge", "discard-restore", "draft-boundary-move"} {
t.Run(scenario, func(t *testing.T) {
f := randomClaimFixture(t, 0)
body := dispositionFixturePayload(t, f)
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
r := f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatal(r.Body.String())
}
item, workspace := readSliceRestoration(t, f)
item = enterAnnotatePhase(t, f, item)
switch scenario {
case "discarded-boundary-move":
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
body.SliceSegments[1].End = 6
body.SliceSegments[2].Start = 6
r = f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
case "kept-slice-merge":
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
body.Disposition = "keep"
r = f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatalf("restore in annotate phase: %d %s", r.Code, r.Body.String())
}
item, workspace = readSliceRestoration(t, f)
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
body.SliceSegments = []domain.SliceSegment{workspace.SliceSegments[0], {ID: "b", Start: 3, End: 10, DeliveryDisposition: "keep", SourceIDs: []string{"b", "c"}}}
body.SliceID = "b"
body.Disposition = "keep"
r = f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
case "discard-restore":
body.combinedAnnotationDraftInput = workspace
body.Version = item.Version
body.Disposition = "keep"
r = f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
case "draft-boundary-move":
draft := combinedAnnotationDraftInput{Version: item.Version, SliceSegments: append([]domain.SliceSegment{}, workspace.SliceSegments...), Segments: workspace.Segments}
draft.SliceSegments[1].End = 6
draft.SliceSegments[2].Start = 6
r = f.request(http.MethodPut, path+"/drafts", f.annotator, draft)
}
if r.Code != 200 {
t.Fatalf("%s: HTTP %d %s", scenario, r.Code, r.Body.String())
}
if strings.Contains(r.Body.String(), "请先返回重新切片") {
t.Fatalf("%s: removed stage lock error resurfaced: %s", scenario, r.Body.String())
}
if scenario == "draft-boundary-move" {
// Draft saves persist into annotationDraft; the workspace only
// catches up on the next disposition/confirmation write.
var response struct {
Draft combinedAnnotationDraftInput `json:"draft"`
}
if err := json.Unmarshal(r.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Draft.SliceSegments[1].End != 6 || response.Draft.SliceSegments[2].Start != 6 {
t.Fatalf("draft boundary edit not persisted: %+v", response.Draft.SliceSegments)
}
return
}
_, saved := readSliceRestoration(t, f)
switch scenario {
case "discarded-boundary-move":
if saved.SliceSegments[1].End != 6 || saved.SliceSegments[2].Start != 6 {
t.Fatalf("%s: boundary edit not persisted: %+v", scenario, saved.SliceSegments)
}
case "kept-slice-merge":
if len(saved.SliceSegments) != 2 || saved.SliceSegments[1].Start != 3 || saved.SliceSegments[1].End != 10 || saved.SliceSegments[1].IsDiscarded() {
t.Fatalf("merge not persisted: %+v", saved.SliceSegments)
}
}
})
}
}
// The triage products of a boundary crossing (spec §3.1) are all existing
// domain states, so the unchanged bottom-line validations must accept them
// while still rejecting any hanging "half action" or unknown status.
func TestCombinedSubmissionBottomLineAfterStructureUnlock(t *testing.T) {
for _, scenario := range []struct {
name string
continuous bool
wantStatus int
wantBody string
}{
{"crossing-action-rejected", false, http.StatusBadRequest, "fully contained in exactly one submitted final slice"},
{"crossing-action-continuous-rejected", true, http.StatusBadRequest, "events must not overlap"},
{"half-action-rejected", true, http.StatusBadRequest, "event must be finite and inside the clip range"},
{"unknown-status-rejected", true, http.StatusBadRequest, "未知动作状态"},
{"truncate-product-accepted", true, http.StatusAccepted, ""},
{"move-product-accepted", true, http.StatusAccepted, ""},
{"invalidate-product-accepted", true, http.StatusAccepted, ""},
} {
t.Run(scenario.name, func(t *testing.T) {
f := newCombinedDraftFixture(t)
if scenario.continuous {
f = continuousFixture(t)
} else {
seedSliceDictionary(t, f, "测试切片")
}
payload := map[string]any{
"version": f.item.Version,
"sliceSegments": []map[string]any{
{"id": "s1", "name": "测试切片", "start": 0.0, "end": 5.0},
{"id": "s2", "name": "测试切片", "start": 5.0, "end": 10.0},
},
}
switch scenario.name {
case "crossing-action-rejected", "crossing-action-continuous-rejected":
payload["segments"] = []map[string]any{{"id": "c1", "start": 4.5, "end": 5.5, "status": "described", "description": "跨片动作"}}
case "half-action-rejected":
payload["segments"] = []map[string]any{{"id": "h1", "start": 9.5, "end": 10.5, "status": "described", "description": "半个动作"}}
case "unknown-status-rejected":
payload["segments"] = []map[string]any{{"id": "u1", "start": 1.0, "end": 2.0, "status": "awaiting-review", "description": "未知状态动作"}}
case "truncate-product-accepted":
payload["segments"] = []map[string]any{
{"id": "t1", "start": 4.5, "end": 5.0, "status": "pending"},
{"id": "t2", "start": 5.0, "end": 5.5, "status": "described", "description": "右手拿起"},
}
case "move-product-accepted":
payload["segments"] = []map[string]any{{"id": "m1", "start": 5.0, "end": 5.5, "status": "described", "description": "右手拿起"}}
case "invalidate-product-accepted":
payload["segments"] = []map[string]any{{"id": "i1", "start": 4.5, "end": 5.0, "status": "invalid", "isInvalid": true}}
}
r := submissionAsync(t, f, payload)
if r.Code != scenario.wantStatus {
t.Fatalf("%s: HTTP %d %s", scenario.name, r.Code, r.Body.String())
}
if scenario.wantBody != "" && !strings.Contains(r.Body.String(), scenario.wantBody) {
t.Fatalf("%s: body %s must contain %q", scenario.name, r.Body.String(), scenario.wantBody)
}
})
}
}
func TestSliceResetRefusesSubmissionHistoryWithInPlaceGuidance(t *testing.T) {
// Ticket 06:返修(有送检历史)一律 409 并指向原地编辑;首标放行由
// TestSliceResetSplitsFirstPassFromSubmissionHistory 覆盖。
f := sliceRestorationFixture(t)
body := dispositionFixturePayload(t, f)
path := "/api/plugins/annotation-qa/tasks/" + f.task.ID
r := f.request(http.MethodPost, path+"/slice-dispositions", f.annotator, body)
if r.Code != 200 {
t.Fatal(r.Body.String())
}
item, prior := readSliceRestoration(t, f)
item = enterAnnotatePhase(t, f, item)
// Pre-reset history from earlier first-pass resets stays readable (R3-2:a).
item.Subject.Payload["sliceResetHistory"] = []any{map[string]any{"workspace": map[string]any{"legacy": true}, "actorUserId": "legacy-user", "at": "2026-01-01T00:00:00Z", "itemVersion": 1, "resetToUnifiedRange": false}}
if err := f.store.UpsertHumanItem(f.ctx, item); err != nil {
t.Fatal(err)
}
reworkTask := f.task
reworkTask.Status = domain.AnnotationTaskStatusRework
if err := f.store.UpsertAnnotationTask(f.ctx, reworkTask); err != nil {
t.Fatal(err)
}
r = f.request(http.MethodPost, path+"/slice-reset", f.annotator, map[string]any{"version": item.Version, "resetToUnifiedRange": false})
if r.Code != http.StatusConflict || !strings.Contains(r.Body.String(), "slice_reset_disabled") || !strings.Contains(r.Body.String(), "原地") {
t.Fatalf("reset must refuse with in-place editing guidance: %d %s", r.Code, r.Body.String())
}
stored, _ := readSliceRestoration(t, f)
if stored.Version != item.Version || stringValue(mapValue(stored.Subject.Payload["sliceWorkflow"])["phase"]) != "annotate" {
t.Fatalf("disabled reset mutated item: %#v", stored)
}
history, _ := normalizeStructuredValue(stored.Subject.Payload["sliceResetHistory"]).([]any)
if len(history) != 1 {
t.Fatalf("disabled reset must not append history: %#v", history)
}
_, workspace := readSliceRestoration(t, f)
if len(workspace.SliceSegments) != len(prior.SliceSegments) || !workspace.SliceSegments[1].IsDiscarded() || len(workspace.SliceSegments[1].DiscardedAnnotations) != 1 {
t.Fatalf("disabled reset changed the live workspace: %+v", workspace.SliceSegments)
}
// A stale version gets the same explicit refusal, not a silent conflict.
r = f.request(http.MethodPost, path+"/slice-reset", f.annotator, map[string]any{"version": item.Version - 1, "resetToUnifiedRange": false})
if r.Code != http.StatusConflict || !strings.Contains(r.Body.String(), "slice_reset_disabled") {
t.Fatalf("stale reset must still explain the deprecation: %d %s", r.Code, r.Body.String())
}
}
// submissionAsync posts a combined submission with Prefer: respond-async so
// accepted payloads answer 202 after every validation gate, without running
// media materialization to completion.
func submissionAsync(t *testing.T, f combinedDraftFixture, payload map[string]any) *httptest.ResponseRecorder {
t.Helper()
encoded, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/combined-submissions", bytes.NewReader(encoded))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Prefer", "respond-async")
csrf := "inplace-slice-editing-csrf"
request.AddCookie(&http.Cookie{Name: csrfCookieName, Value: csrf})
request.Header.Set(csrfHeaderName, csrf)
request = request.WithContext(context.WithValue(request.Context(), authContextKey{}, &authenticatedPrincipal{User: f.annotator, Organization: domain.OrganizationRecord{ID: domain.DefaultOrganizationID, Status: domain.OrganizationStatusActive}}))
recorder := httptest.NewRecorder()
f.handler.ServeHTTP(recorder, request)
return recorder
}