From e6d592815d4ffc744cf22a73dcc07523eab5881d Mon Sep 17 00:00:00 2001 From: zhangxinhao Date: Mon, 23 Nov 2026 09:32:29 +0800 Subject: [PATCH 1/5] feat(v2): enforce who may edit, reassign, split, stop and send back a task - Edit, reassign and split: the creator, the workspace owner and whoever does the work now (the assignee, or a member of the assigned squad). An Agent task has no person doing it, so only its creator and the owner manage it. A finished task is read-only (409 task_closed). - Reassigning waits for a running Agent turn (409 run_active). - Splitting only applies to a task still being worked; a task in review answers 409 task_in_review. - Stopping a run: whoever started it, the creator and the owner. - The creator and the owner may send a task in review back to pending while no run executes it. Anyone else gets 403 forbidden. --- .../server/schedule_personal_task_test.go | 3 +- .../internal/server/task_decompositions.go | 6 +- v2-server/internal/server/tasks.go | 14 +- .../internal/store/notifications_test.go | 12 +- v2-server/internal/store/task_access.go | 45 ++++++ v2-server/internal/store/task_access_test.go | 148 ++++++++++++++++++ .../store/task_workflows_edits_test.go | 9 +- .../store/task_workflows_review_test.go | 4 +- v2-server/internal/store/tasks.go | 60 +++++-- v2-server/internal/store/tasks_test.go | 22 +-- v2-server/internal/taskdecomp/taskdecomp.go | 20 ++- .../internal/taskdecomp/taskdecomp_test.go | 67 ++++++-- .../internal/taskrun/result_retry_test.go | 5 + v2-server/internal/taskrun/taskrun.go | 14 +- v2-server/internal/taskrun/taskrun_test.go | 39 +++-- v2-server/internal/workflowhost/forms_test.go | 2 +- 16 files changed, 389 insertions(+), 81 deletions(-) create mode 100644 v2-server/internal/store/task_access.go create mode 100644 v2-server/internal/store/task_access_test.go diff --git a/v2-server/internal/server/schedule_personal_task_test.go b/v2-server/internal/server/schedule_personal_task_test.go index b02994b12..46167eaf8 100644 --- a/v2-server/internal/server/schedule_personal_task_test.go +++ b/v2-server/internal/server/schedule_personal_task_test.go @@ -11,6 +11,7 @@ import ( "github.com/wanglongan587/cloud/v2-server/internal/execution" "github.com/wanglongan587/cloud/v2-server/internal/server" "github.com/wanglongan587/cloud/v2-server/internal/store" + "github.com/wanglongan587/cloud/v2-server/internal/store/storetest" "github.com/wanglongan587/cloud/v2-server/internal/taskrun" ) @@ -154,7 +155,7 @@ func testPersonalTask(t *testing.T, lost bool) { if e != nil || review.Reason != "task_no_longer_actionable" || review.ExecutionRef != "" { t.Fatalf("review: %+v %v", review, e) } - _, e = f.db.SetTaskAssignee(ctx, scope.TenantID, src.ID, "", nil, current.Version) + _, e = f.db.SetTaskAssignee(ctx, storetest.Access(t, f.db, scope.TenantID, scope.UserID), src.ID, nil, current.Version) if e != nil { t.Fatal(e) } diff --git a/v2-server/internal/server/task_decompositions.go b/v2-server/internal/server/task_decompositions.go index 2f73b4056..1ed3beeec 100644 --- a/v2-server/internal/server/task_decompositions.go +++ b/v2-server/internal/server/task_decompositions.go @@ -40,6 +40,8 @@ func taskDecompositionFault(w http.ResponseWriter, op string, e error) { faultWithParams(w, http.StatusBadRequest, "decomposition_output_required", map[string]string{"message": taskdecomp.OutputRequirement}) case errors.Is(e, taskdecomp.ErrTaskClosed): fault(w, http.StatusConflict, "task_closed") + case errors.Is(e, taskdecomp.ErrTaskInReview): + fault(w, http.StatusConflict, "task_in_review") case errors.Is(e, taskdecomp.ErrSubtask): fault(w, http.StatusConflict, "subtask_not_decomposable") case taskFault(w, e): @@ -64,7 +66,7 @@ func (h *handler) listTaskDecompositions(w http.ResponseWriter, r *http.Request, // startTaskDecomposition runs a published workflow over the task; its `tasks` output becomes the // task's subtasks once the run succeeds. func (h *handler) startTaskDecomposition(w http.ResponseWriter, r *http.Request, a access) { - host, tenant, id, ok := h.taskDecompositionScope(w, r, a) + host, _, id, ok := h.taskDecompositionScope(w, r, a) if !ok { return } @@ -82,7 +84,7 @@ func (h *handler) startTaskDecomposition(w http.ResponseWriter, r *http.Request, fault(w, http.StatusBadRequest, "invalid_workflow") return } - d, e := host.Start(r.Context(), tenant, a.UserID, id, in.WorkflowID, key) + d, e := host.Start(r.Context(), a.Access, id, in.WorkflowID, key) if e != nil { taskDecompositionFault(w, "start task decomposition", e) return diff --git a/v2-server/internal/server/tasks.go b/v2-server/internal/server/tasks.go index 66c1a99ae..4a17e2dfe 100644 --- a/v2-server/internal/server/tasks.go +++ b/v2-server/internal/server/tasks.go @@ -19,9 +19,9 @@ type taskStore interface { Tasks(context.Context, string) ([]store.Task, error) Task(context.Context, string, string) (store.Task, error) CreateTask(context.Context, string, string, store.TaskInput) (store.Task, error) - UpdateTask(context.Context, string, string, store.TaskInput) (store.Task, error) + UpdateTask(context.Context, store.Access, string, store.TaskInput) (store.Task, error) SetTaskStatus(context.Context, store.Access, string, string, int64) (store.Task, error) - SetTaskAssignee(context.Context, string, string, string, *store.TaskAssigneeRef, int64) (store.Task, error) + SetTaskAssignee(context.Context, store.Access, string, *store.TaskAssigneeRef, int64) (store.Task, error) } // taskUUID matches the ids this server mints for tasks; anything else cannot exist. @@ -72,6 +72,8 @@ func taskFault(w http.ResponseWriter, e error) bool { fault(w, http.StatusConflict, "run_active") case errors.Is(e, store.ErrWorkflowActive): fault(w, http.StatusConflict, "workflow_active") + case errors.Is(e, store.ErrTaskClosed): + fault(w, http.StatusConflict, "task_closed") case errors.Is(e, store.ErrInvalidProject): fault(w, http.StatusBadRequest, "invalid_project") case errors.Is(e, store.ErrInvalidAssignee), errors.Is(e, store.ErrUserUnavailable), @@ -200,7 +202,7 @@ func (h *handler) getTask(w http.ResponseWriter, r *http.Request, a access) { } func (h *handler) updateTask(w http.ResponseWriter, r *http.Request, a access) { - s, tenant, id, ok := h.taskScope(w, r, a) + s, _, id, ok := h.taskScope(w, r, a) if !ok { return } @@ -222,7 +224,7 @@ func (h *handler) updateTask(w http.ResponseWriter, r *http.Request, a access) { ProjectID: req.ProjectID, Version: req.Version, } - task, e := s.UpdateTask(r.Context(), tenant, id, in) + task, e := s.UpdateTask(r.Context(), a.Access, id, in) if e != nil { if taskFault(w, e) { return @@ -266,7 +268,7 @@ func (h *handler) setTaskStatus(w http.ResponseWriter, r *http.Request, a access // setTaskAssignee replaces or clears the assignee. An explicit null clears it; a missing field is // a malformed request, so a client bug cannot silently unassign work. func (h *handler) setTaskAssignee(w http.ResponseWriter, r *http.Request, a access) { - s, tenant, id, ok := h.taskScope(w, r, a) + s, _, id, ok := h.taskScope(w, r, a) if !ok { return } @@ -291,7 +293,7 @@ func (h *handler) setTaskAssignee(w http.ResponseWriter, r *http.Request, a acce } ref = validAssigneeRef(&in) } - task, e := s.SetTaskAssignee(r.Context(), tenant, id, a.UserID, ref, req.Version) + task, e := s.SetTaskAssignee(r.Context(), a.Access, id, ref, req.Version) if e != nil { if taskFault(w, e) { return diff --git a/v2-server/internal/store/notifications_test.go b/v2-server/internal/store/notifications_test.go index b97ce5f05..9ca9740df 100644 --- a/v2-server/internal/store/notifications_test.go +++ b/v2-server/internal/store/notifications_test.go @@ -49,12 +49,12 @@ func TestNotifyAssignment(t *testing.T) { t.Run("reassigning tells the new assignee once", func(t *testing.T) { task := createTask(t, f, owner, store.TaskInput{Title: "改派"}) - task, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version) + task, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version) if e != nil { t.Fatal(e) } // Re-sending the same assignee is not a new assignment. - if task, e = f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version); e != nil { + if task, e = f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version); e != nil { t.Fatal(e) } if n := countFor(must(inbox(t, f, bob)), task.ID, store.NotifyAssigned); n != 1 { @@ -62,10 +62,10 @@ func TestNotifyAssignment(t *testing.T) { } // Clearing and an Agent assignee tell nobody. agentID := f.agent(t, "Agent", "active") - if task, e = f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: agentID}, task.Version); e != nil { + if task, e = f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: agentID}, task.Version); e != nil { t.Fatal(e) } - if _, e = f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, nil, task.Version); e != nil { + if _, e = f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, nil, task.Version); e != nil { t.Fatal(e) } if n := countFor(must(inbox(t, f, bob)), task.ID, store.NotifyAssigned); n != 1 { @@ -76,12 +76,12 @@ func TestNotifyAssignment(t *testing.T) { t.Run("upper-case UUIDs are the same person", func(t *testing.T) { upper := strings.ToUpper(bob) task := createTask(t, f, owner, store.TaskInput{Title: "大写改派"}) - task, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version) + task, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: bob}, task.Version) if e != nil { t.Fatal(e) } // The same person spelled in upper case is not a new assignment. - if _, e = f.store.SetTaskAssignee(ctx, f.tenant, task.ID, owner, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: upper}, task.Version); e != nil { + if _, e = f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: upper}, task.Version); e != nil { t.Fatal(e) } if n := countFor(must(inbox(t, f, bob)), task.ID, store.NotifyAssigned); n != 1 { diff --git a/v2-server/internal/store/task_access.go b/v2-server/internal/store/task_access.go new file mode 100644 index 000000000..491d99345 --- /dev/null +++ b/v2-server/internal/store/task_access.go @@ -0,0 +1,45 @@ +package store + +import "context" + +// Who may act on a task. Ending a task, and sending it back from 待验收, is the decision of whoever +// asked for the work or the workspace owner (canCloseTask). Editing, reassigning and splitting it +// also belong to whoever currently does the work: the person it is assigned to, or any current +// member of its squad. An Agent task has no person doing it, so only its creator and the owner +// manage it; running its Agent stays open to every member (AuthorizeTaskRunner). + +// TaskFinished reports whether the task is done or cancelled; a finished task is read-only. +func TaskFinished(task Task) bool { + return task.Status == TaskDone || task.Status == TaskCancelled +} + +// CanManageTask reports whether the caller may edit, reassign or split the task. inSquad answers +// squad membership, from the caller's transaction when there is one. +func CanManageTask(ctx context.Context, a Access, task Task, inSquad func(context.Context, string, string, string) (bool, error)) (bool, error) { + if canCloseTask(a, task) { + return true, nil + } + if task.Assignee == nil { + return false, nil + } + switch task.Assignee.Type { + case AssigneeHuman: + return task.Assignee.ID == a.UserID, nil + case AssigneeSquad: + return inSquad(ctx, a.TenantID, task.Assignee.ID, a.UserID) + } + return false, nil +} + +// CanStopTaskRun reports whether the caller may stop the task's run: whoever started it, and +// whoever may end the task. +func CanStopTaskRun(a Access, task Task, run TaskRun) bool { + return run.StartedBy == a.UserID || canCloseTask(a, task) +} + +// canManageTaskTx is CanManageTask inside a transaction. +func canManageTaskTx(ctx context.Context, q dbTX, a Access, task Task) (bool, error) { + return CanManageTask(ctx, a, task, func(ctx context.Context, tenant, squad, user string) (bool, error) { + return inSquad(ctx, q, tenant, squad, user) + }) +} diff --git a/v2-server/internal/store/task_access_test.go b/v2-server/internal/store/task_access_test.go new file mode 100644 index 000000000..4115c2c17 --- /dev/null +++ b/v2-server/internal/store/task_access_test.go @@ -0,0 +1,148 @@ +package store_test + +import ( + "errors" + "testing" + + "github.com/wanglongan587/cloud/v2-server/internal/store" + "github.com/wanglongan587/cloud/v2-server/internal/store/storetest" +) + +// Editing and reassigning belong to the task's creator, the workspace owner and whoever currently +// does the work; a finished task is read-only, and a running Agent turn keeps its assignee. +func TestTaskManageNeedsCreatorOwnerOrAssignee(t *testing.T) { + f := newSquadFixture(t) + ctx := f.ctx + owner := f.login(t, "owner", "owner") + lead := f.login(t, "lead", "member") + doer := f.login(t, "doer", "member") + mate := f.login(t, "mate", "member") + bystander := f.login(t, "bystander", "member") + addProject(t, f, owner) + as := func(user string) store.Access { return storetest.Access(t, f.store, f.tenant, user) } + edit := func(user string, task store.Task) (store.Task, error) { + return f.store.UpdateTask(ctx, as(user), task.ID, store.TaskInput{Title: task.Title + "(改)", ProjectID: taskProject, Version: task.Version}) + } + reassign := func(user string, task store.Task, to string) (store.Task, error) { + return f.store.SetTaskAssignee(ctx, as(user), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: to}, task.Version) + } + + // A person's task: the creator, the owner and the assignee may edit; nobody else. + task := createTask(t, f, lead, store.TaskInput{Title: "人的任务", Assignee: &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: doer}}) + if _, e := edit(bystander, task); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("bystander edit = %v", e) + } + if _, e := reassign(bystander, task, bystander); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("bystander reassign = %v", e) + } + var e error + for _, user := range []string{doer, lead, owner} { + if task, e = edit(user, task); e != nil { + t.Fatalf("edit by %s = %v", user, e) + } + } + // The assignee may hand it on, and is then no longer the one doing it. + if task, e = reassign(doer, task, mate); e != nil || task.Assignee.ID != mate { + t.Fatalf("assignee reassign = %+v %v", task, e) + } + if _, e := edit(doer, task); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("former assignee edit = %v", e) + } + + // A squad's task: any current member is doing it. + squad, e := f.store.CreateSquad(ctx, f.tenant, owner, store.SquadInput{Name: "前端"}) + if e != nil { + t.Fatal(e) + } + if _, e := f.store.AddSquadMember(ctx, as(owner), squad.ID, store.SquadMemberInput{Type: store.MemberHuman, UserID: mate, Version: squad.Version}); e != nil { + t.Fatal(e) + } + squadTask := createTask(t, f, lead, store.TaskInput{Title: "小队任务", Assignee: &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}}) + if _, e := edit(bystander, squadTask); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("non-member edit = %v", e) + } + if _, e := edit(mate, squadTask); e != nil { + t.Fatalf("squad member edit = %v", e) + } + + // An Agent's task has no person doing it: only its creator and the owner manage it. + agentTask := createTask(t, f, lead, store.TaskInput{Title: "Agent 任务", Assignee: &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: f.agent(t, "OpenCode", "active")}}) + if _, e := edit(bystander, agentTask); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("member edit of an Agent task = %v", e) + } + if agentTask, e = edit(lead, agentTask); e != nil { + t.Fatalf("creator edit of an Agent task = %v", e) + } + + // While its Agent turn runs, the task keeps its assignee; an edit still goes through. + run, e := f.store.CreateTaskRun(ctx, store.NewTaskRun{TenantID: f.tenant, TaskID: agentTask.ID, StartedBy: bystander, StartKey: "k", ExecutorID: "test"}) + if e != nil { + t.Fatal(e) + } + if e := f.store.RecordTaskTurn(ctx, run.ID, "session", "turn"); e != nil { + t.Fatal(e) + } + agentTask, _ = f.store.Task(ctx, f.tenant, agentTask.ID) + if _, e := reassign(lead, agentTask, doer); !errors.Is(e, store.ErrRunActive) { + t.Fatalf("reassign during a turn = %v", e) + } + if _, e := edit(lead, agentTask); e != nil { + t.Fatalf("edit during a turn = %v", e) + } + + // A finished task is read-only, even to its creator. + closed, e := f.store.SetTaskStatus(ctx, as(lead), task.ID, store.TaskCancelled, task.Version) + if e != nil { + t.Fatal(e) + } + if _, e := edit(lead, closed); !errors.Is(e, store.ErrTaskClosed) { + t.Fatalf("edit of a finished task = %v", e) + } + if _, e := reassign(owner, closed, doer); !errors.Is(e, store.ErrTaskClosed) { + t.Fatalf("reassign of a finished task = %v", e) + } +} + +// Whoever may confirm a task in 待验收 may instead send it back to 待处理 for rework; the person +// doing it may not, and no other status goes back to 待处理 by hand. +func TestTaskSendBackNeedsCreatorOrOwner(t *testing.T) { + f := newSquadFixture(t) + ctx := f.ctx + owner := f.login(t, "owner", "owner") + lead := f.login(t, "lead", "member") + doer := f.login(t, "doer", "member") + addProject(t, f, owner) + as := func(user string) store.Access { return storetest.Access(t, f.store, f.tenant, user) } + inReview := func() store.Task { + t.Helper() + task := createTask(t, f, lead, store.TaskInput{Title: "返工", Assignee: &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: doer}}) + for _, status := range []string{store.TaskRunning, store.TaskReview} { + var e error + if task, e = f.store.SetTaskStatus(ctx, as(doer), task.ID, status, task.Version); e != nil { + t.Fatalf("%s: %v", status, e) + } + } + return task + } + + task := inReview() + if _, e := f.store.SetTaskStatus(ctx, as(doer), task.ID, store.TaskPending, task.Version); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("assignee send back = %v", e) + } + back, e := f.store.SetTaskStatus(ctx, as(lead), task.ID, store.TaskPending, task.Version) + if e != nil || back.Status != store.TaskPending { + t.Fatalf("creator send back = %+v %v", back, e) + } + other := inReview() + if back, e := f.store.SetTaskStatus(ctx, as(owner), other.ID, store.TaskPending, other.Version); e != nil || back.Status != store.TaskPending { + t.Fatalf("owner send back = %+v %v", back, e) + } + // 进行中 still only moves on, or ends. + running, e := f.store.SetTaskStatus(ctx, as(doer), back.ID, store.TaskRunning, back.Version) + if e != nil { + t.Fatal(e) + } + if _, e := f.store.SetTaskStatus(ctx, as(lead), running.ID, store.TaskPending, running.Version); !errors.Is(e, store.ErrInvalidTransition) { + t.Fatalf("running → pending = %v", e) + } +} diff --git a/v2-server/internal/store/task_workflows_edits_test.go b/v2-server/internal/store/task_workflows_edits_test.go index 41247c5e7..aba8b090c 100644 --- a/v2-server/internal/store/task_workflows_edits_test.go +++ b/v2-server/internal/store/task_workflows_edits_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/wanglongan587/cloud/v2-server/internal/store" + "github.com/wanglongan587/cloud/v2-server/internal/store/storetest" "github.com/wanglongan587/cloud/v2-server/internal/taskworkflow" ) @@ -35,12 +36,12 @@ func TestTaskWorkflowEditsPreserveSettlement(t *testing.T) { } switch tc.edit { case "describe": - if _, err := f.store.UpdateTask(f.ctx, f.tenant, task.ID, store.TaskInput{Title: cur.Title, Description: "clarified while it runs", ProjectID: cur.ProjectID, Version: cur.Version}); err != nil { + if _, err := f.store.UpdateTask(f.ctx, storetest.Access(t, f.store, f.tenant, user), task.ID, store.TaskInput{Title: cur.Title, Description: "clarified while it runs", ProjectID: cur.ProjectID, Version: cur.Version}); err != nil { t.Fatalf("edit refused: %v", err) } case "reassign": other := f.login(t, "other", "member") - if _, err := f.store.SetTaskAssignee(f.ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: "human", ID: other}, cur.Version); err != nil { + if _, err := f.store.SetTaskAssignee(f.ctx, storetest.Access(t, f.store, f.tenant, user), task.ID, &store.TaskAssigneeRef{Type: "human", ID: other}, cur.Version); err != nil { t.Fatalf("reassign refused: %v", err) } } @@ -63,7 +64,7 @@ func TestTaskWorkflowEditsPreserveSettlement(t *testing.T) { if e != nil { t.Fatal(e) } - if _, e = f.store.UpdateTask(f.ctx, f.tenant, agentTask.ID, store.TaskInput{Title: running.Title, Description: "clarified", ProjectID: running.ProjectID, Version: running.Version}); e != nil { + if _, e = f.store.UpdateTask(f.ctx, storetest.Access(t, f.store, f.tenant, user), agentTask.ID, store.TaskInput{Title: running.Title, Description: "clarified", ProjectID: running.ProjectID, Version: running.Version}); e != nil { t.Fatal(e) } agentResult, e := f.store.TransitionTaskStatus(f.ctx, f.tenant, agentTask.ID, "running", tc.want) @@ -92,7 +93,7 @@ func TestTaskWorkflowEditDuringPrepare(t *testing.T) { if err != nil { return err } - _, err = f.store.UpdateTask(ctx, f.tenant, task.ID, store.TaskInput{Title: cur.Title, Description: "edited", ProjectID: cur.ProjectID, Version: cur.Version}) + _, err = f.store.UpdateTask(ctx, storetest.Access(t, f.store, f.tenant, user), task.ID, store.TaskInput{Title: cur.Title, Description: "edited", ProjectID: cur.ProjectID, Version: cur.Version}) if err != nil { return err } diff --git a/v2-server/internal/store/task_workflows_review_test.go b/v2-server/internal/store/task_workflows_review_test.go index 1d2fff67c..54db92cc0 100644 --- a/v2-server/internal/store/task_workflows_review_test.go +++ b/v2-server/internal/store/task_workflows_review_test.go @@ -249,7 +249,7 @@ func TestTaskWorkflowIdleAgentAndCallerKeys(t *testing.T) { } other := f.login(t, "other", "member") current, _ := f.store.Task(f.ctx, f.tenant, task.ID) - if _, err := f.store.SetTaskAssignee(f.ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: "human", ID: other}, current.Version); err != nil { + if _, err := f.store.SetTaskAssignee(f.ctx, storetest.Access(t, f.store, f.tenant, user), task.ID, &store.TaskAssigneeRef{Type: "human", ID: other}, current.Version); err != nil { t.Fatal(err) } in.UserID = other @@ -524,7 +524,7 @@ func TestTaskWorkflowAssigneePolicy(t *testing.T) { if _, err := f.store.AddSquadMember(f.ctx, storetest.Access(t, f.store, f.tenant, user), squad.ID, store.SquadMemberInput{Type: store.MemberHuman, UserID: member, Version: squad.Version}); err != nil { t.Fatal(err) } - if _, err := f.store.SetTaskAssignee(f.ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, task.Version); err != nil { + if _, err := f.store.SetTaskAssignee(f.ctx, storetest.Access(t, f.store, f.tenant, user), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, task.Version); err != nil { t.Fatal(err) } in := store.NewTaskWorkflow{TenantID: f.tenant, TaskID: task.ID, UserID: outsider, Key: "squad", WorkflowID: wid} diff --git a/v2-server/internal/store/tasks.go b/v2-server/internal/store/tasks.go index 69571ec1f..8f6d1119c 100644 --- a/v2-server/internal/store/tasks.go +++ b/v2-server/internal/store/tasks.go @@ -38,6 +38,9 @@ var ( // ErrWorkflowActive reports a manual status move while a workflow is handling the task: the // workflow's settlement owns the status until it ends. ErrWorkflowActive = errors.New("task workflow active") + // ErrTaskClosed reports a change to a task that is done or cancelled: a finished task is + // read-only. + ErrTaskClosed = errors.New("task closed") ) // TaskAssignee is one typed reference. Identifier carries the plugin identity for agents, in the @@ -107,21 +110,22 @@ func CanTransitionTask(from, to string) bool { case TaskRunning: return to == TaskReview || to == TaskCancelled case TaskReview: - return to == TaskDone || to == TaskCancelled + return to == TaskDone || to == TaskCancelled || to == TaskPending } return false } -// canCloseTask reports whether the caller may end the task, by confirming it done or cancelling it. -// That is the decision of whoever asked for the work or a workspace administrator; doing the work -// does not grant it. +// canCloseTask reports whether the caller may end the task, by confirming it done or cancelling it, +// or send it back from 待验收 for rework. That is the decision of whoever asked for the work or a +// workspace administrator; doing the work does not grant it. func canCloseTask(a Access, task Task) bool { return a.Owner() || task.CreatedBy == a.UserID } // CanRunTransitionTask reports the moves a task's Agent run makes: starting or following up a run // puts the task in 进行中, a finished turn hands it to 待验收, and a stopped or interrupted turn -// returns it to 待处理. A person still cannot make the last two moves by hand. +// returns it to 待处理. A person cannot make the last two moves by hand; sending a task back from +// 待验收 to 待处理 is the person's own move (CanTransitionTask), which a run never makes. func CanRunTransitionTask(from, to string) bool { switch from { case TaskPending, TaskReview: @@ -336,11 +340,17 @@ func (s *Store) CreateTask(ctx context.Context, tenant, user string, in TaskInpu } // UpdateTask replaces the title, description and project under a version check. The status and -// assignee have their own writes so a stale form cannot silently undo them. -func (s *Store) UpdateTask(ctx context.Context, tenant, id string, in TaskInput) (Task, error) { +// assignee have their own writes so a stale form cannot silently undo them. Only CanManageTask may +// edit, and a finished task is read-only. +func (s *Store) UpdateTask(ctx context.Context, a Access, id string, in TaskInput) (Task, error) { var out Task + tenant := a.TenantID e := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { - if _, e := lockTask(ctx, tx, tenant, id, in.Version); e != nil { + task, e := lockTask(ctx, tx, tenant, id, in.Version) + if e != nil { + return e + } + if e := requireManage(ctx, tx, a, task); e != nil { return e } if e := requireProject(ctx, tx, tenant, in.ProjectID); e != nil { @@ -352,7 +362,7 @@ func (s *Store) UpdateTask(ctx context.Context, tenant, id string, in TaskInput) id, in.Title, in.Description, in.ProjectID); e != nil { return fmt.Errorf("update task: %w", e) } - task, e := scanTask(tx.QueryRow(ctx, `SELECT `+taskColumns+` `+taskJoins+` WHERE t.id = $1`, id)) + task, e = scanTask(tx.QueryRow(ctx, `SELECT `+taskColumns+` `+taskJoins+` WHERE t.id = $1`, id)) out = task return e }) @@ -361,7 +371,7 @@ func (s *Store) UpdateTask(ctx context.Context, tenant, id string, in TaskInput) // SetTaskStatus moves a task by hand under a version check. Only the lifecycle's legal moves are // accepted, so 待验收 cannot be skipped and a finished task cannot silently reopen. Ending the task -// is limited by canCloseTask; anyone else gets ErrForbidden. While an Agent turn runs the run owns +// and sending it back from 待验收 are limited by canCloseTask; anyone else gets ErrForbidden. While an Agent turn runs the run owns // the status, and a manual move returns ErrRunActive; while a workflow handles the task it returns // ErrWorkflowActive, so the page can say which of the two to wait for. func (s *Store) SetTaskStatus(ctx context.Context, a Access, id, status string, version int64) (Task, error) { @@ -371,7 +381,7 @@ func (s *Store) SetTaskStatus(ctx context.Context, a Access, id, status string, if e != nil { return e } - if status == TaskDone || status == TaskCancelled { + if status == TaskDone || status == TaskCancelled || (task.Status == TaskReview && status == TaskPending) { if !canCloseTask(a, task) { return ErrForbidden } @@ -421,14 +431,23 @@ func (s *Store) TransitionTaskStatus(ctx context.Context, tenant, id, from, to s // SetTaskAssignee replaces or clears the typed assignee under a version check. Assigning a squad // puts the task in front of every member; none of them is picked for it. A new assignee is -// notified unless actor, the person assigning, is them; re-sending the same assignee is not new. -func (s *Store) SetTaskAssignee(ctx context.Context, tenant, id, actor string, ref *TaskAssigneeRef, version int64) (Task, error) { +// notified unless the person assigning is them; re-sending the same assignee is not new. Only +// CanManageTask may reassign, judged against the current assignee; a finished task is read-only, +// and while an Agent turn runs the run keeps its assignee (ErrRunActive). +func (s *Store) SetTaskAssignee(ctx context.Context, a Access, id string, ref *TaskAssigneeRef, version int64) (Task, error) { var out Task + tenant, actor := a.TenantID, a.UserID e := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { before, e := lockTask(ctx, tx, tenant, id, version) if e != nil { return e } + if e := requireManage(ctx, tx, a, before); e != nil { + return e + } + if before.ActiveRun != nil && before.ActiveRun.State == TaskRunRunning { + return ErrRunActive + } var kind, assignee string if ref != nil { if e := requireAssignee(ctx, tx, tenant, *ref); e != nil { @@ -457,3 +476,18 @@ type WorkflowTaskSource struct { Name string `json:"name"` SubmittedAt *time.Time `json:"submittedAt"` } + +// requireManage refuses a caller CanManageTask does not admit, then a finished task. +func requireManage(ctx context.Context, tx pgx.Tx, a Access, task Task) error { + ok, e := canManageTaskTx(ctx, tx, a, task) + if e != nil { + return e + } + if !ok { + return ErrForbidden + } + if TaskFinished(task) { + return ErrTaskClosed + } + return nil +} diff --git a/v2-server/internal/store/tasks_test.go b/v2-server/internal/store/tasks_test.go index 6b398d27b..0e34f002c 100644 --- a/v2-server/internal/store/tasks_test.go +++ b/v2-server/internal/store/tasks_test.go @@ -51,11 +51,11 @@ func TestTaskLifecycle(t *testing.T) { } // An edit bumps the version; the version the caller read is then stale. - edited, e := f.store.UpdateTask(ctx, f.tenant, created.ID, store.TaskInput{Title: "整理演示数据(改)", Description: "两行", ProjectID: taskProject, Version: 1}) + edited, e := f.store.UpdateTask(ctx, storetest.Access(t, f.store, f.tenant, owner), created.ID, store.TaskInput{Title: "整理演示数据(改)", Description: "两行", ProjectID: taskProject, Version: 1}) if e != nil || edited.Version != 2 || edited.Title != "整理演示数据(改)" { t.Fatalf("edit = %+v %v", edited, e) } - if _, e := f.store.UpdateTask(ctx, f.tenant, created.ID, store.TaskInput{Title: "再来", ProjectID: taskProject, Version: 1}); !errors.Is(e, store.ErrConflict) { + if _, e := f.store.UpdateTask(ctx, storetest.Access(t, f.store, f.tenant, owner), created.ID, store.TaskInput{Title: "再来", ProjectID: taskProject, Version: 1}); !errors.Is(e, store.ErrConflict) { t.Fatalf("stale edit = %v", e) } @@ -175,24 +175,24 @@ func TestTaskAssignees(t *testing.T) { task := createTask(t, f, owner, store.TaskInput{Title: "交给谁"}) // All three typed assignees are accepted and read back with live names. - human, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: member}, 1) + human, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: member}, 1) if e != nil || human.Assignee == nil || human.Assignee.DisplayName != "member" || human.Assignee.Identifier != "" { t.Fatalf("human assignee = %+v %v", human, e) } - agent, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: agentID}, 2) + agent, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: agentID}, 2) if e != nil || agent.Assignee == nil || agent.Assignee.DisplayName != "OpenCode" || agent.Assignee.Identifier != "official/ora-space.opencode" { t.Fatalf("agent assignee = %+v %v", agent, e) } - bySquad, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, 3) + bySquad, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, 3) if e != nil || bySquad.Assignee == nil || bySquad.Assignee.DisplayName != "产品小队" { t.Fatalf("squad assignee = %+v %v", bySquad, e) } - cleared, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", nil, 4) + cleared, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, nil, 4) if e != nil || cleared.Assignee != nil || cleared.Version != 5 { t.Fatalf("clear assignee = %+v %v", cleared, e) } - if _, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", nil, 4); !errors.Is(e, store.ErrConflict) { + if _, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, nil, 4); !errors.Is(e, store.ErrConflict) { t.Fatalf("stale assignment = %v", e) } @@ -201,16 +201,16 @@ func TestTaskAssignees(t *testing.T) { if e := f.db.QueryRow(ctx, `INSERT INTO v2_space_agents (tenant_id, name, status) VALUES ($1, '退役', 'retired') RETURNING id`, f.tenant).Scan(&retired); e != nil { t.Fatal(e) } - if _, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: retired}, 5); !errors.Is(e, store.ErrAgentUnavailable) { + if _, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeAgent, ID: retired}, 5); !errors.Is(e, store.ErrAgentUnavailable) { t.Fatalf("retired agent = %v", e) } if _, e := f.store.ArchiveSquad(ctx, storetest.Access(t, f.store, f.tenant, owner), squad.ID, squad.Version); e != nil { t.Fatal(e) } - if _, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, 5); !errors.Is(e, store.ErrInvalidAssignee) { + if _, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeSquad, ID: squad.ID}, 5); !errors.Is(e, store.ErrInvalidAssignee) { t.Fatalf("archived squad = %v", e) } - if _, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: "robot", ID: member}, 5); !errors.Is(e, store.ErrInvalidAssignee) { + if _, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: "robot", ID: member}, 5); !errors.Is(e, store.ErrInvalidAssignee) { t.Fatalf("unknown kind = %v", e) } @@ -225,7 +225,7 @@ func TestTaskAssignees(t *testing.T) { if _, e := f.db.Exec(ctx, `INSERT INTO memberships (tenant_id, user_id, role) VALUES ($1, $2, 'member')`, strangerTenant, stranger); e != nil { t.Fatal(e) } - if _, e := f.store.SetTaskAssignee(ctx, f.tenant, task.ID, "", &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: stranger}, 5); !errors.Is(e, store.ErrUserUnavailable) { + if _, e := f.store.SetTaskAssignee(ctx, storetest.Access(t, f.store, f.tenant, owner), task.ID, &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: stranger}, 5); !errors.Is(e, store.ErrUserUnavailable) { t.Fatalf("foreign human = %v", e) } } diff --git a/v2-server/internal/taskdecomp/taskdecomp.go b/v2-server/internal/taskdecomp/taskdecomp.go index 3b906fbad..0118cb283 100644 --- a/v2-server/internal/taskdecomp/taskdecomp.go +++ b/v2-server/internal/taskdecomp/taskdecomp.go @@ -38,6 +38,9 @@ var ( ErrTaskClosed = errors.New("task closed") // ErrSubtask reports a decomposition of a subtask: only one level exists. ErrSubtask = errors.New("subtask cannot be decomposed") + // ErrTaskInReview reports a decomposition of a task in 待验收: a task is split only while it is + // still being worked (待处理 or 进行中). + ErrTaskInReview = errors.New("task in review") ) // Limits on what a run's output may become: the task routes' title and description limits, and a @@ -51,6 +54,7 @@ const ( // Store is the persistence a Host needs; *store.Store implements it. type Store interface { Task(ctx context.Context, tenant, id string) (store.Task, error) + InSquad(ctx context.Context, tenant, squad, user string) (bool, error) PublishedWorkflowSnapshot(ctx context.Context, tenant, workflowID string) (store.WorkflowSnapshot, error) CreateWorkflowRun(ctx context.Context, tenant, workflowID, snapshotID string, in store.WorkflowRunInput) (store.WorkflowRun, error) CancelWorkflowRun(ctx context.Context, tenant, runID string) (store.WorkflowRun, error) @@ -119,12 +123,20 @@ func (h *Host) lock(taskID string) func() { // Start runs the workflow over the task as the caller and returns the running decomposition. The // same key returns the decomposition it already started. A published snapshot that fails // CanDecompose is rejected before any run is created. A run the workflow host refuses to start -// fails the decomposition at once, with the reason, rather than leaving it running. -func (h *Host) Start(ctx context.Context, tenant, user, taskID, workflowID, key string) (store.TaskDecomposition, error) { +// fails the decomposition at once, with the reason, rather than leaving it running. Only +// store.CanManageTask may split a task (store.ErrForbidden otherwise). +func (h *Host) Start(ctx context.Context, a store.Access, taskID, workflowID, key string) (store.TaskDecomposition, error) { + tenant, user := a.TenantID, a.UserID task, e := h.store.Task(ctx, tenant, taskID) if e != nil { return store.TaskDecomposition{}, e } + if ok, e := store.CanManageTask(ctx, a, task, h.store.InSquad); e != nil || !ok { + if e == nil { + e = store.ErrForbidden + } + return store.TaskDecomposition{}, e + } defer h.lock(taskID)() if d, e := h.store.TaskDecompositionByKey(ctx, tenant, taskID, user, key); e == nil { return d, nil @@ -132,8 +144,10 @@ func (h *Host) Start(ctx context.Context, tenant, user, taskID, workflowID, key return d, e } switch { - case task.Status == store.TaskDone || task.Status == store.TaskCancelled: + case store.TaskFinished(task): return store.TaskDecomposition{}, ErrTaskClosed + case task.Status == store.TaskReview: + return store.TaskDecomposition{}, ErrTaskInReview case task.ParentID != nil: return store.TaskDecomposition{}, ErrSubtask } diff --git a/v2-server/internal/taskdecomp/taskdecomp_test.go b/v2-server/internal/taskdecomp/taskdecomp_test.go index 87b23f082..0bcd11950 100644 --- a/v2-server/internal/taskdecomp/taskdecomp_test.go +++ b/v2-server/internal/taskdecomp/taskdecomp_test.go @@ -155,7 +155,7 @@ const output = `{"tasks":[{"title":"登录页","description":"邮箱登录,错 func TestDecompositionWritesSubtasksOnce(t *testing.T) { f := newFixture(t) parent := f.task(t, "账号体系") - d, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "key-1") + d, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "key-1") if e != nil || d.Status != store.DecompositionRunning || d.WorkflowName != "需求拆分" || d.StartedBy != f.owner { t.Fatalf("start = %+v %v", d, e) } @@ -165,10 +165,10 @@ func TestDecompositionWritesSubtasksOnce(t *testing.T) { t.Fatalf("run = %+v %v", run, e) } // The same key is the same decomposition; another one waits for this to end. - if again, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "key-1"); e != nil || again.ID != d.ID { + if again, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "key-1"); e != nil || again.ID != d.ID { t.Fatalf("same key = %+v %v", again, e) } - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "key-2"); !errors.Is(e, store.ErrDecompositionActive) { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "key-2"); !errors.Is(e, store.ErrDecompositionActive) { t.Fatalf("second = %v", e) } @@ -201,16 +201,55 @@ func TestDecompositionWritesSubtasksOnce(t *testing.T) { } // A subtask is not split again, and a finished task is not split at all. - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, subs[0].ID, f.workflow, "key-3"); !errors.Is(e, taskdecomp.ErrSubtask) { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), subs[0].ID, f.workflow, "key-3"); !errors.Is(e, taskdecomp.ErrSubtask) { t.Fatalf("subtask = %v", e) } closed := f.task(t, "已取消的需求") if _, e := f.store.SetTaskStatus(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), closed.ID, store.TaskCancelled, closed.Version); e != nil { t.Fatal(e) } - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, closed.ID, f.workflow, "key-4"); !errors.Is(e, taskdecomp.ErrTaskClosed) { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), closed.ID, f.workflow, "key-4"); !errors.Is(e, taskdecomp.ErrTaskClosed) { t.Fatalf("closed = %v", e) } + // A task in 待验收 is not split either: it is split only while still being worked. + reviewed := f.task(t, "待验收的需求") + for _, status := range []string{store.TaskRunning, store.TaskReview} { + var e error + if reviewed, e = f.store.SetTaskStatus(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), reviewed.ID, status, reviewed.Version); e != nil { + t.Fatal(e) + } + } + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), reviewed.ID, f.workflow, "key-5"); !errors.Is(e, taskdecomp.ErrTaskInReview) { + t.Fatalf("in review = %v", e) + } +} + +// Only the task's creator, the workspace owner and whoever does the work may split it. +func TestDecompositionNeedsCreatorOwnerOrAssignee(t *testing.T) { + f := newFixture(t) + member := func(name string) string { + t.Helper() + u, e := f.store.SessionUser(f.ctx, storetest.SignIn(t, f.store, name, name, store.RoleMember)) + if e != nil { + t.Fatal(e) + } + return u.ID + } + doer, bystander := member("doer"), member("bystander") + task, e := f.store.CreateTask(f.ctx, f.tenant, f.owner, store.TaskInput{Title: "注册流程", ProjectID: f.project, + Assignee: &store.TaskAssigneeRef{Type: store.AssigneeHuman, ID: doer}}) + if e != nil { + t.Fatal(e) + } + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, bystander), task.ID, f.workflow, "by-bystander"); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("bystander split = %v", e) + } + if list, _ := f.host.List(f.ctx, f.tenant, task.ID); len(list) != 0 { + t.Fatalf("a refused split left a decomposition: %+v", list) + } + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, doer), task.ID, f.workflow, "by-doer"); e != nil { + t.Fatalf("assignee split = %v", e) + } } func TestDecompositionFailuresAreVisible(t *testing.T) { @@ -226,7 +265,7 @@ func TestDecompositionFailuresAreVisible(t *testing.T) { } for i, c := range cases { parent := f.task(t, c.name) - d, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "key") + d, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "key") if e != nil { t.Fatalf("%s: %v", c.name, e) } @@ -239,7 +278,7 @@ func TestDecompositionFailuresAreVisible(t *testing.T) { t.Fatalf("%s wrote %d subtasks", c.name, len(subs)) } // A failure frees the task for another try. - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "retry"); e != nil { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "retry"); e != nil { t.Fatalf("%s retry = %v", c.name, e) } } @@ -253,7 +292,7 @@ func TestDecompositionStartRefusals(t *testing.T) { t.Fatal(e) } for _, id := range []string{draft.ID, "00000000-0000-4000-8000-000000000999"} { - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, id, "k-"+id); !errors.Is(e, taskdecomp.ErrInvalidWorkflow) { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, id, "k-"+id); !errors.Is(e, taskdecomp.ErrInvalidWorkflow) { t.Fatalf("workflow %s = %v", id, e) } } @@ -269,7 +308,7 @@ func TestDecompositionStartRefusals(t *testing.T) { if e != nil { t.Fatal(e) } - if _, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, incompatible.ID, "incompatible"); !errors.Is(e, taskdecomp.ErrWorkflowOutputRequired) { + if _, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, incompatible.ID, "incompatible"); !errors.Is(e, taskdecomp.ErrWorkflowOutputRequired) { t.Fatalf("incompatible workflow = %v", e) } after, e := f.store.WorkflowRuns(f.ctx, f.tenant, "", "") @@ -282,7 +321,7 @@ func TestDecompositionStartRefusals(t *testing.T) { // A run the workflow host refuses fails the decomposition at once, with the reason. f.runs.refuse = errors.New("没有可用的 Agent") - d, e := f.host.Start(f.ctx, f.tenant, f.owner, parent.ID, f.workflow, "refused") + d, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), parent.ID, f.workflow, "refused") if e != nil || d.Status != store.DecompositionFailed || !strings.Contains(d.Failure, "没有可用的 Agent") { t.Fatalf("refused = %+v %v", d, e) } @@ -291,11 +330,11 @@ func TestDecompositionStartRefusals(t *testing.T) { func TestRecoverEndsWhatTheLastProcessLeft(t *testing.T) { f := newFixture(t) finished, stuck := f.task(t, "跑完了"), f.task(t, "卡住了") - a, e := f.host.Start(f.ctx, f.tenant, f.owner, finished.ID, f.workflow, "a") + a, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), finished.ID, f.workflow, "a") if e != nil { t.Fatal(e) } - b, e := f.host.Start(f.ctx, f.tenant, f.owner, stuck.ID, f.workflow, "b") + b, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), stuck.ID, f.workflow, "b") if e != nil { t.Fatal(e) } @@ -341,7 +380,7 @@ func (c cancelFails) CancelWorkflowRun(context.Context, string, string) (store.W func TestRecoverStopsWhenARunCannotBeCancelled(t *testing.T) { f := newFixture(t) stuck := f.task(t, "取消失败") - d, e := f.host.Start(f.ctx, f.tenant, f.owner, stuck.ID, f.workflow, "a") + d, e := f.host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), stuck.ID, f.workflow, "a") if e != nil { t.Fatal(e) } @@ -414,7 +453,7 @@ func TestStartFreezesCheckedSnapshot(t *testing.T) { } host := taskdecomp.New(republishingStore{Store: f.store, t: t}, f.runs, nil) t.Cleanup(host.Close) - d, err := host.Start(f.ctx, f.tenant, f.owner, task.ID, f.workflow, "snapshot-race") + d, err := host.Start(f.ctx, storetest.Access(t, f.store, f.tenant, f.owner), task.ID, f.workflow, "snapshot-race") if err != nil { t.Fatal(err) } diff --git a/v2-server/internal/taskrun/result_retry_test.go b/v2-server/internal/taskrun/result_retry_test.go index 1bf13b3ea..bea5b7ea9 100644 --- a/v2-server/internal/taskrun/result_retry_test.go +++ b/v2-server/internal/taskrun/result_retry_test.go @@ -28,6 +28,11 @@ type resultStore struct { endRun func(context.Context, string, string) error } +// TenantAccess admits the caller as the workspace owner, so a Stop reaches the path under test. +func (s resultStore) TenantAccess(_ context.Context, tenant, user string) (store.Access, error) { + return store.Access{TenantID: tenant, UserID: user, Role: store.RoleOwner}, nil +} + func (s resultStore) Task(ctx context.Context, tenant, id string) (store.Task, error) { return s.task(ctx, tenant, id) } diff --git a/v2-server/internal/taskrun/taskrun.go b/v2-server/internal/taskrun/taskrun.go index 30951e960..3d8fc3a5c 100644 --- a/v2-server/internal/taskrun/taskrun.go +++ b/v2-server/internal/taskrun/taskrun.go @@ -410,8 +410,8 @@ func (h *Host) followUp(ctx context.Context, scope execution.Scope, task store.T // Stop stops a live run. A running turn is cancelled; when its session outlives the stop (the // Node kept it), the run stays live and idle, awaiting a follow-up. A run whose session ended -// with the stop, and an idle run, is ended. Any member can stop a run; it spends nobody's -// identity. +// with the stop, and an idle run, is ended. Whoever started the run, the task's creator and the +// workspace owner may stop it (store.CanStopTaskRun); anyone else gets store.ErrForbidden. // // A Stop sent while a turn ran asks to stop that turn: if the turn has ended by the time this // Stop holds the task's lock (another member's stop kept the session, or the turn finished), it @@ -423,13 +423,21 @@ func (h *Host) Stop(ctx context.Context, scope execution.Scope, taskID, runID st h.stopRead() } defer h.lock(taskID)() - if _, e := h.store.Task(ctx, scope.TenantID, taskID); e != nil { + task, e := h.store.Task(ctx, scope.TenantID, taskID) + if e != nil { return store.TaskRun{}, e } run, e := h.store.TaskRun(ctx, scope.TenantID, taskID, runID) if e != nil { return run, e } + a, e := h.store.TenantAccess(ctx, scope.TenantID, scope.UserID) + if e != nil { + return run, e + } + if !store.CanStopTaskRun(a, task, run) { + return run, store.ErrForbidden + } if !run.Live() || run.SessionID == "" { return run, ErrNoLiveRun } diff --git a/v2-server/internal/taskrun/taskrun_test.go b/v2-server/internal/taskrun/taskrun_test.go index 53ff45b3b..e6aec19ad 100644 --- a/v2-server/internal/taskrun/taskrun_test.go +++ b/v2-server/internal/taskrun/taskrun_test.go @@ -406,19 +406,28 @@ func TestOnlyTheStarterFollowsUp(t *testing.T) { func TestStopEndsTheRunAndReturnsTheTask(t *testing.T) { f := newFixture(t) task := f.task(t, opencode) - run, e := f.host.Start(f.ctx, f.owner, task.ID, "start", taskrun.StartInput{}) + run, e := f.host.Start(f.ctx, f.member, task.ID, "start", taskrun.StartInput{}) if e != nil { t.Fatal(e) } - // Any member can stop it; the session is still read and cancelled under the starter's scope. - stopped, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID) + // A member who neither started the run nor created the task cannot stop it. + token := storetest.SignIn(t, f.store, "task-bystander", "卡萝", store.RoleMember) + bystander, e := f.store.SessionUser(f.ctx, token) + if e != nil { + t.Fatal(e) + } + if _, e := f.host.Stop(f.ctx, execution.Scope{TenantID: f.tenant, UserID: bystander.ID}, task.ID, run.ID); !errors.Is(e, store.ErrForbidden) { + t.Fatalf("bystander stop = %v, want forbidden", e) + } + // The task's creator can; the session is still read and cancelled under the starter's scope. + stopped, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID) if e != nil || stopped.State != store.TaskRunEnded || stopped.EndReason != store.TaskRunStopped || stopped.LastResult != "cancelled" { t.Fatalf("stopped = %+v %v", stopped, e) } if got := f.await(t, task.ID, store.TaskPending); got.ActiveRun != nil { t.Fatalf("task after stop = %+v", got) } - if _, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID); !errors.Is(e, taskrun.ErrNoLiveRun) { + if _, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID); !errors.Is(e, taskrun.ErrNoLiveRun) { t.Fatalf("second stop = %v", e) } } @@ -430,18 +439,18 @@ func TestStopKeepsTheRunWhenItsSessionOutlivesTheTurn(t *testing.T) { f := newFixture(t) f.port.keepOnCancel = true task := f.task(t, opencode) - run, e := f.host.Start(f.ctx, f.owner, task.ID, "start", taskrun.StartInput{}) + run, e := f.host.Start(f.ctx, f.member, task.ID, "start", taskrun.StartInput{}) if e != nil { t.Fatal(e) } - stopped, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID) + stopped, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID) if e != nil || !stopped.Live() || stopped.TurnActive() || stopped.EndReason != "" || stopped.LastResult != "cancelled" { t.Fatalf("stopped = %+v %v", stopped, e) } if got := f.await(t, task.ID, store.TaskPending); got.ActiveRun == nil || got.ActiveRun.ID != run.ID { t.Fatalf("task after a kept stop = %+v", got) } - follow, e := f.host.Comment(f.ctx, f.owner, task.ID, "follow", taskrun.CommentInput{Body: "继续", ToAgent: true}) + follow, e := f.host.Comment(f.ctx, f.member, task.ID, "follow", taskrun.CommentInput{Body: "继续", ToAgent: true}) if e != nil || follow.RunID != run.ID { t.Fatalf("follow-up after the stop = %+v %v", follow, e) } @@ -452,19 +461,19 @@ func TestStopKeepsTheRunWhenItsSessionOutlivesTheTurn(t *testing.T) { // Stopping the run's idle session ends it. f.port.finish(t, again.LastTurnID, execution.StatusCompleted) f.await(t, task.ID, store.TaskReview) - if ended, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID); e != nil || ended.State != store.TaskRunEnded || ended.EndReason != store.TaskRunStopped { + if ended, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID); e != nil || ended.State != store.TaskRunEnded || ended.EndReason != store.TaskRunStopped { t.Fatalf("stop of the idle run = %+v %v", ended, e) } } -// Two members stop the same running turn at once and the session outlives the stop: the second +// Two stops of the same running turn arrive at once and the session outlives the stop: the second // Stop finds the turn it was sent for already stopped and leaves the idle run alone, instead of // ending it as a Stop of the idle run would. func TestConcurrentStopsOfAKeptTurnKeepTheRun(t *testing.T) { f := newFixture(t) f.port.keepOnCancel = true task := f.task(t, opencode) - run, e := f.host.Start(f.ctx, f.owner, task.ID, "start", taskrun.StartInput{}) + run, e := f.host.Start(f.ctx, f.member, task.ID, "start", taskrun.StartInput{}) if e != nil { t.Fatal(e) } @@ -474,7 +483,7 @@ func TestConcurrentStopsOfAKeptTurnKeepTheRun(t *testing.T) { stopped := make(chan error, 2) for range 2 { go func() { - _, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID) + _, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID) stopped <- e }() } @@ -498,7 +507,7 @@ func TestALateStopDoesNotStopTheNextTurn(t *testing.T) { f := newFixture(t) f.port.keepOnCancel = true task := f.task(t, opencode) - run, e := f.host.Start(f.ctx, f.owner, task.ID, "start", taskrun.StartInput{}) + run, e := f.host.Start(f.ctx, f.member, task.ID, "start", taskrun.StartInput{}) if e != nil { t.Fatal(e) } @@ -512,14 +521,14 @@ func TestALateStopDoesNotStopTheNextTurn(t *testing.T) { }) late := make(chan error, 1) go func() { - _, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID) + _, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID) late <- e }() <-seen - if _, e := f.host.Stop(f.ctx, f.member, task.ID, run.ID); e != nil { + if _, e := f.host.Stop(f.ctx, f.owner, task.ID, run.ID); e != nil { t.Fatal(e) } - follow, e := f.host.Comment(f.ctx, f.owner, task.ID, "follow", taskrun.CommentInput{Body: "继续", ToAgent: true}) + follow, e := f.host.Comment(f.ctx, f.member, task.ID, "follow", taskrun.CommentInput{Body: "继续", ToAgent: true}) if e != nil || follow.RunID != run.ID { t.Fatalf("follow-up after the kept stop = %+v %v", follow, e) } diff --git a/v2-server/internal/workflowhost/forms_test.go b/v2-server/internal/workflowhost/forms_test.go index 33d3652e3..6c97d20e2 100644 --- a/v2-server/internal/workflowhost/forms_test.go +++ b/v2-server/internal/workflowhost/forms_test.go @@ -82,7 +82,7 @@ func TestFormSubmissionCreatesTasksAndReusesAcrossRuns(t *testing.T) { if err != nil || len(current.WorkflowSources) != 2 { t.Fatalf("missing report associations: %+v %v", current, err) } - if _, err := f.s.UpdateTask(ctx, f.scope.TenantID, current.ID, store.TaskInput{Title: current.Title, Description: "Edited task text", ProjectID: current.ProjectID, Version: current.Version}); err != nil { + if _, err := f.s.UpdateTask(ctx, storetest.Access(t, f.s, f.scope.TenantID, f.scope.UserID), current.ID, store.TaskInput{Title: current.Title, Description: "Edited task text", ProjectID: current.ProjectID, Version: current.Version}); err != nil { t.Fatal(err) } current, err = f.s.Task(ctx, f.scope.TenantID, current.ID) From 7e1dbab81fe02cd1a7df0e365dc736528b2af4ef Mon Sep 17 00:00:00 2001 From: zhangxinhao Date: Mon, 23 Nov 2026 09:32:29 +0800 Subject: [PATCH 2/5] feat(v2): disable task actions the caller may not take and say who can MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The task page follows the server's rules: editing, reassigning and splitting name the creator, assignee or squad; stopping names the run's starter and the creator; the creator gets 退回待处理 in review, also on the board. A creator or owner who cannot run the task's Agent can still stop its run. 「我的任务」 says it keeps work handed in for review. --- .../features/collaboration/task-detail.tsx | 42 ++++++++++++++----- .../features/collaboration/task-model.test.ts | 20 +++++++-- .../src/features/collaboration/task-model.ts | 22 +++++++--- .../features/collaboration/task-page.test.tsx | 40 +++++++++++++++++- .../src/features/collaboration/task-page.tsx | 16 +++---- .../features/collaboration/task-views.test.ts | 37 +++++++++++++++- .../src/features/collaboration/task-views.ts | 40 ++++++++++++++---- 7 files changed, 182 insertions(+), 35 deletions(-) diff --git a/frontend-v2/src/features/collaboration/task-detail.tsx b/frontend-v2/src/features/collaboration/task-detail.tsx index 3c1032c8f..730557608 100644 --- a/frontend-v2/src/features/collaboration/task-detail.tsx +++ b/frontend-v2/src/features/collaboration/task-detail.tsx @@ -5,7 +5,7 @@ import type { SquadSummary } from '@/lib/squads-api/generated' import { formatTime } from './task-model' import { TaskAssigneePicker } from '@/components/task-assignee-picker' import { assigneeKindLabel, assigneeLabel, isTaskFinished, taskActions } from './task-model' -import { closeRefusal, runsAgent } from './task-views' +import { closeRefusal, manageRefusal, needsCloser, runsAgent, stopRefusal } from './task-views' import type { Task, TaskAssigneeRef, TaskExecutor, TaskStatusProperty } from './tasks-api/generated' /** The run controls' state, decided by the page from the task and its timeline. */ @@ -26,14 +26,18 @@ export interface RunControls { * One task's facts and the moves on it: who owns it, running its Agent, and the manual status * moves. While the Agent runs a turn, the run owns the status, so manual moves wait for it. */ -export function TaskDetailView({ task, me, inSquad, canClose, projectName, squads, busy, workflowActive = false, error, run, onWorkflow, onStatus, onAssign }: { +export function TaskDetailView({ task, me, inSquad, canClose, canManage, canStop, projectName, squads, busy, workflowActive = false, error, run, onWorkflow, onStatus, onAssign }: { task: Task /** The caller's user id: a person's task runs an Agent only for that person. */ me: string /** The caller is a member of the squad that owns the task. */ inSquad: boolean - /** The caller may end the task: confirm it or cancel it. */ + /** The caller may end the task (confirm or cancel it) or send it back from 待验收. */ canClose: boolean + /** The caller may edit, reassign or split the task. */ + canManage: boolean + /** The caller may stop the task's live run. */ + canStop: boolean /** The project's display name, resolved from the workspace list. */ projectName: string /** Live squads the task may be reassigned to. */ @@ -70,8 +74,12 @@ export function TaskDetailView({ task, me, inSquad, canClose, projectName, squad

指派对象

- +

当前:{assigneeLabel(task)}{task.assignee && `(${assigneeKindLabel(task)})`}。{task.assignee?.type === 'squad' && '每个队员都会收到,任一队员都能评论和用 Agent 处理。'}

+ {finished + ?

任务已结束,不能再改派。

+ : !canManage ?

{manageRefusal(task, '改派')}

+ : running &&

Agent 正在执行,等这一轮结束或先停止,再改派。

}
{runsAgent(task, me, inSquad) &&
@@ -89,9 +97,7 @@ export function TaskDetailView({ task, me, inSquad, canClose, projectName, squad {run.hasRuns ? : } {run.starting ? '正在启动…' : run.hasRuns ? '重新执行' : personal ? '用 Agent 处理' : '开始处理'} - {task.activeRun && } + {task.activeRun && }

{running @@ -105,6 +111,14 @@ export function TaskDetailView({ task, me, inSquad, canClose, projectName, squad }

} + {!runsAgent(task, me, inSquad) && task.activeRun &&
+

执行

+

{running ? `${task.activeRun.startedByName} 发起的运行正在执行。` : `${task.activeRun.startedByName} 的会话在等追问。`}

+ {canStop + ?
+ :

{stopRefusal(task)}

} +
} + {onWorkflow &&
{runsAgent(task, me, inSquad) ? @@ -121,13 +135,21 @@ export function TaskDetailView({ task, me, inSquad, canClose, projectName, squad ?

运行正在执行,结束后再推进。

: <>
{actions.map(action => { - const refused = isTaskFinished(action.status) && !canClose - return + const refused = needsCloser(task.status, action.status) && !canClose + return })}
- {!canClose &&

{task.status === 'review' ? `等待 ${task.createdByName} 验收。${closeRefusal(task, '确认完成或取消任务')}` : closeRefusal(task, '取消任务')}

} + {!canClose &&

{task.status === 'review' ? `等待 ${task.createdByName} 验收。${closeRefusal(task, '确认完成、退回或取消任务')}` : closeRefusal(task, '取消任务')}

} + {canClose && task.status === 'review' &&

不满意可以退回待处理,让负责人返工。

} }
{error &&

{error}

} } + +/** Stops the live run's turn, or ends its idle session; refused callers see who can. */ +function StopButton({ running, stopping, refusal, onStop }: { running: boolean; stopping: boolean; refusal: string; onStop: () => void }) { + return +} diff --git a/frontend-v2/src/features/collaboration/task-model.test.ts b/frontend-v2/src/features/collaboration/task-model.test.ts index ea3b0fec4..067c19c6e 100644 --- a/frontend-v2/src/features/collaboration/task-model.test.ts +++ b/frontend-v2/src/features/collaboration/task-model.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { Task } from './tasks-api/generated' import { assigneeKindLabel, assigneeLabel, isTaskFinished, MAX_TASK_TITLE, projectLabel, taskActions, - boardMoveMessageFor, decompositionMessageFor, taskMessageFor, taskRunMessageFor, taskStatusLabel, validateTask, + boardMoveMessageFor, decompositionMessageFor, stopMessageFor, taskMessageFor, taskRunMessageFor, taskStatusLabel, validateTask, } from './task-model' const task = (overrides: Partial = {}): Task => ({ @@ -21,7 +21,7 @@ describe('task status', () => { it('moves one step at a time and never reopens a finished task', () => { expect(taskActions('pending')).toEqual([{ status: 'running', label: '开始处理' }, { status: 'cancelled', label: '取消任务' }]) expect(taskActions('running').map(action => action.status)).toEqual(['review', 'cancelled']) - expect(taskActions('review').map(action => action.status)).toEqual(['done', 'cancelled']) + expect(taskActions('review').map(action => action.status)).toEqual(['done', 'pending', 'cancelled']) expect(taskActions('done')).toEqual([]) expect(taskActions('cancelled')).toEqual([]) expect(isTaskFinished('done')).toBe(true) @@ -72,6 +72,15 @@ describe('task errors', () => { expect(taskMessageFor(http(400, 'invalid_project'))).toBe('所选项目不在当前工作区,请重新选择。') }) + it('names who may change a task, and that a finished one is read-only', () => { + expect(taskMessageFor(http(403, 'forbidden'))).toBe('只有创建人、负责人或工作区管理员能修改这个任务。') + expect(taskMessageFor(http(409, 'task_closed'))).toBe('任务已结束,只能查看,不能再修改。') + expect(taskMessageFor(http(409, 'run_active'))).toBe('Agent 正在执行,等这一轮结束或先停止,再改派。') + expect(taskMessageFor(http(409, 'version_conflict'))).toBe('任务已被其他人修改,请关闭后重新打开。') + expect(stopMessageFor(http(403, 'forbidden'))).toBe('只有运行发起人、任务创建人或工作区管理员能停止这次运行。') + expect(stopMessageFor(http(409, 'no_live_run'))).toBe('这次运行已经结束了。') + }) + it('falls back for anything else', () => { expect(taskMessageFor(new Error('boom'))).toBe('操作失败,请重试。') }) @@ -81,7 +90,7 @@ describe('task errors', () => { expect(boardMoveMessageFor(http(409, 'workflow_active'))).toBe('工作流正在处理这个任务,结束后任务会自动推进,之后再改状态。') expect(boardMoveMessageFor(http(409, 'version_conflict'))).toBe('任务刚被其他人改过,看板已刷新,请再拖一次。') expect(boardMoveMessageFor(http(400, 'invalid_transition'))).toContain('待处理 → 进行中 → 待验收 → 已完成') - expect(boardMoveMessageFor(http(403, 'forbidden'))).toBe('只有任务创建人或工作区管理员能确认完成或取消任务。') + expect(boardMoveMessageFor(http(403, 'forbidden'))).toBe('只有任务创建人或工作区管理员能确认完成、退回或取消任务。') expect(taskRunMessageFor(http(400, 'workflow_role_not_found'))).toBe('工作流引用的角色在工作区角色目录里不存在,请先在设置的角色页新建同名角色再启动。') }) }) @@ -100,4 +109,9 @@ describe('decomposition refusals', () => { expect(decompositionMessageFor(fault('decomposition_output_required', { message: 7 }))).toBe('所选工作流的输出不满足拆分要求,请修改后重新发布。') expect(decompositionMessageFor(fault('invalid_workflow'))).toBe('所选工作流不存在或还没有发布,请重新选择。') }) + + it('says why a task cannot be split now', () => { + expect(decompositionMessageFor(fault('task_in_review'))).toBe('任务在待验收,不能拆分;退回待处理后再拆。') + expect(decompositionMessageFor({ isAxiosError: true, response: { status: 403, data: { code: 'forbidden', requestId: 'r' } } })).toBe('只有创建人、负责人或工作区管理员能拆分这个任务。') + }) }) diff --git a/frontend-v2/src/features/collaboration/task-model.ts b/frontend-v2/src/features/collaboration/task-model.ts index 202e091ab..1ddbbe654 100644 --- a/frontend-v2/src/features/collaboration/task-model.ts +++ b/frontend-v2/src/features/collaboration/task-model.ts @@ -34,14 +34,14 @@ export interface TaskAction { const ACTIONS: Record = { pending: [{ status: 'running', label: '开始处理' }, { status: 'cancelled', label: '取消任务' }], running: [{ status: 'review', label: '提交验收' }, { status: 'cancelled', label: '取消任务' }], - review: [{ status: 'done', label: '确认完成' }, { status: 'cancelled', label: '取消任务' }], + review: [{ status: 'done', label: '确认完成' }, { status: 'pending', label: '退回待处理' }, { status: 'cancelled', label: '取消任务' }], done: [], cancelled: [], } /** * The moves a person may make by hand. This mirrors the server's `CanTransitionTask`: review is - * never skipped, and a finished task never reopens. + * never skipped, a finished task never reopens, and 待验收 may go back to 待处理 for rework. */ export const taskActions = (status: string): TaskAction[] => ACTIONS[status as TaskStatus] ?? [] @@ -74,9 +74,13 @@ export function validateTask(title: string, description: string): Record{ const handedToMe = (status: Task['status']) => task({ status, createdBy: 'user-lead', createdByName: '陈默', assignee: { type: 'human', id: 'user-me', displayName: '演示用户' } }) -it('keeps 确认完成 and 取消任务 from an assignee, and says who decides', async () => { +it('keeps 确认完成, 退回待处理 and 取消任务 from an assignee, and says who decides', async () => { workspace.role = 'member' vi.mocked(api.getTask).mockResolvedValue(handedToMe('review')) renderPage() expect(await screen.findByRole('button', { name: '确认完成' })).toBeDisabled() + expect(screen.getByRole('button', { name: '退回待处理' })).toBeDisabled() expect(screen.getByRole('button', { name: '取消任务' })).toBeDisabled() - expect(screen.getByText('等待 陈默 验收。只有创建人 陈默 或工作区管理员能确认完成或取消任务。')).toBeInTheDocument() + expect(screen.getByText('等待 陈默 验收。只有创建人 陈默 或工作区管理员能确认完成、退回或取消任务。')).toBeInTheDocument() + // Editing stays with whoever does the work. + expect(screen.getByRole('button', { name: '编辑' })).toBeEnabled() +}) + +it('lets the creator send work in 待验收 back for rework', async () => { + workspace.role = 'member' + const askedByMe = (status: Task['status']) => task({ status, createdBy: 'user-me', createdByName: '演示用户', assignee: { type: 'human', id: 'user-doer', displayName: '鲍勃' } }) + vi.mocked(api.getTask).mockResolvedValue(askedByMe('review')) + vi.mocked(api.setTaskStatus).mockResolvedValue(askedByMe('pending')) + renderPage() + await userEvent.click(await screen.findByRole('button', { name: '退回待处理' })) + await waitFor(() => expect(api.setTaskStatus).toHaveBeenCalledWith('tenant', 'task-1', { status: 'pending', version: 1 })) +}) + +it('keeps editing, reassigning and stopping from a member with no part in the task, and says who can', async () => { + workspace.role = 'member' + vi.mocked(api.getTask).mockResolvedValue(task({ status: 'running', createdBy: 'user-lead', createdByName: '陈默', + assignee: { type: 'human', id: 'user-doer', displayName: '鲍勃' }, + activeRun: { id: 'run-1', state: 'running', startedBy: 'user-doer', startedByName: '鲍勃', executorName: 'Claude Code / Sonnet' } })) + renderPage() + const edit = await screen.findByRole('button', { name: '编辑' }) + expect(edit).toBeDisabled() + expect(edit).toHaveAttribute('title', '只有创建人 陈默、负责人 鲍勃 或工作区管理员能编辑。') + expect(screen.getByText('只有创建人 陈默、负责人 鲍勃 或工作区管理员能改派。')).toBeInTheDocument() + expect(screen.getByText('只有发起人 鲍勃、创建人 陈默 或工作区管理员能停止这次运行。')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: '停止' })).not.toBeInTheDocument() +}) + +it('lets the creator stop a run on work assigned to someone else', async () => { + workspace.role = 'member' + vi.mocked(api.getTask).mockResolvedValue(task({ status: 'running', createdBy: 'user-me', createdByName: '演示用户', + assignee: { type: 'human', id: 'user-doer', displayName: '鲍勃' }, + activeRun: { id: 'run-1', state: 'running', startedBy: 'user-doer', startedByName: '鲍勃', executorName: 'Claude Code / Sonnet' } })) + renderPage() + expect(await screen.findByRole('button', { name: '停止' })).toBeEnabled() }) it('leaves an assignee the moves that are theirs', async () => { diff --git a/frontend-v2/src/features/collaboration/task-page.tsx b/frontend-v2/src/features/collaboration/task-page.tsx index 20ca648b1..49a430d41 100644 --- a/frontend-v2/src/features/collaboration/task-page.tsx +++ b/frontend-v2/src/features/collaboration/task-page.tsx @@ -22,12 +22,12 @@ import { TaskForm, type TaskDraft } from './task-form' import { TaskWorkflowDialog } from './task-workflow-dialog' import { TaskWorkflows } from './task-workflows' import { statusOf } from '@/lib/api-client' -import { projectLabel, taskMessageFor, taskMoveMessageFor, taskRunMessageFor, taskStatusLabel } from './task-model' +import { isTaskFinished, projectLabel, stopMessageFor, taskMessageFor, taskMoveMessageFor, taskRunMessageFor, taskStatusLabel } from './task-model' import { createTaskComment, getTask, getTaskTimeline, listTaskExecutors, setTaskAssignee, setTaskStatus, startTaskRun, stopTaskRun, updateTask, type Task, type TaskAssigneeRef, type TaskComment, type TaskStatusProperty, } from './tasks-api/generated' -import { canCloseTask, canDecompose, runsAgent } from './task-views' +import { canCloseTask, canDecompose, canManageTask, canStopRun, manageRefusal, runsAgent } from './task-views' import { useDecompositions, useMySquadTasks, useWorkspace } from './workspace' /** Fresh idempotency key for one submission: a retry of the same click reuses it. */ @@ -211,7 +211,7 @@ export default function TaskPage() { const stop = useMutation({ mutationFn: (runId: string) => stopTaskRun(tenantId, taskId, runId), onSuccess: async () => { setError(''); await refresh() }, - onError: e => setError(taskRunMessageFor(e)), + onError: e => setError(stopMessageFor(e)), }) const commentKeyRef = useRef<{ signature: string; key: string } | null>(null) const comment = useMutation({ @@ -242,16 +242,18 @@ export default function TaskPage() { } const projectList = projects.data?.items ?? [] + const canManage = canManageTask(task, me.id, role, inSquad) + const editRefusal = isTaskFinished(task.status) ? '任务已结束,只能查看。' : canManage ? '' : manageRefusal(task, '编辑') return
{taskStatusLabel(task.status)}

{task.title}

- {canDecompose(task) && } + {canDecompose(task) && } {(newestRun || selected) && } - +
} {!workspaceShown &&