fix: isolate task state when switching workspaces (#1951)
This commit is contained in:
@@ -98,6 +98,7 @@ func NewTestServer(t *testing.T) *TestServer {
|
||||
Reviews: taskRepo,
|
||||
}, eventBus, log, taskservice.RepositoryDiscoveryConfig{})
|
||||
taskSvc.SetWorkflowStepCreator(workflowSvc)
|
||||
taskSvc.SetWorkflowStepGetter(workflowSvc)
|
||||
taskSvc.SetWorkspaceBootstrapper(taskRepo)
|
||||
|
||||
// Create WebSocket gateway
|
||||
|
||||
@@ -301,6 +301,7 @@ func NewOrchestratorTestServer(t *testing.T) *OrchestratorTestServer {
|
||||
Reviews: taskRepo,
|
||||
}, eventBus, log, taskservice.RepositoryDiscoveryConfig{})
|
||||
taskSvc.SetWorkflowStepCreator(workflowSvc)
|
||||
taskSvc.SetWorkflowStepGetter(workflowSvc)
|
||||
taskSvc.SetWorkspaceBootstrapper(taskRepo)
|
||||
|
||||
// Create simulated agent manager
|
||||
|
||||
@@ -646,7 +646,9 @@ func (h *Handlers) handleCreateTask(ctx context.Context, msg *ws.Message) (*ws.M
|
||||
h.logger.Error("failed to create task", zap.Error(err))
|
||||
// Defense-in-depth: resolveTaskRepositories already catches this for the
|
||||
// MCP path, but non-MCP callers (UI, internal engine) reach here directly.
|
||||
if errors.Is(err, service.ErrSubtaskDepthExceeded) {
|
||||
if errors.Is(err, service.ErrSubtaskDepthExceeded) ||
|
||||
errors.Is(err, service.ErrInvalidTaskWorkflow) ||
|
||||
isMCPWorkflowNotFoundError(err) {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil)
|
||||
}
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create task", nil)
|
||||
|
||||
@@ -41,6 +41,29 @@ func newTestTaskService(t *testing.T) (*service.Service, *sqliterepo.Repository)
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
type staticWorkflowStepGetter struct {
|
||||
steps map[string]*workflowmodels.WorkflowStep
|
||||
}
|
||||
|
||||
func (g *staticWorkflowStepGetter) GetStep(
|
||||
_ context.Context,
|
||||
stepID string,
|
||||
) (*workflowmodels.WorkflowStep, error) {
|
||||
step := g.steps[stepID]
|
||||
if step == nil {
|
||||
return nil, fmt.Errorf("workflow step not found: %s", stepID)
|
||||
}
|
||||
return step, nil
|
||||
}
|
||||
|
||||
func (*staticWorkflowStepGetter) GetNextStepByPosition(
|
||||
context.Context,
|
||||
string,
|
||||
int,
|
||||
) (*workflowmodels.WorkflowStep, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func newTestTaskServiceWithEventBus(t *testing.T) (*service.Service, *sqliterepo.Repository, *bus.MemoryEventBus) {
|
||||
t.Helper()
|
||||
dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "test.db"))
|
||||
@@ -1206,6 +1229,43 @@ func TestHandleCreateTask_InvalidWorkflowReturnsValidationError(t *testing.T) {
|
||||
assert.Contains(t, ep.Message, "was not found")
|
||||
}
|
||||
|
||||
func TestHandleCreateTask_StepOutsideWorkflowReturnsValidationError(t *testing.T) {
|
||||
svc, _ := newTestTaskService(t)
|
||||
ctx := context.Background()
|
||||
workspaces, err := svc.ListWorkspaces(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, workspaces, 1)
|
||||
workflows, err := svc.ListWorkflows(ctx, workspaces[0].ID, false)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, workflows, 1)
|
||||
svc.SetWorkflowStepGetter(&staticWorkflowStepGetter{
|
||||
steps: map[string]*workflowmodels.WorkflowStep{
|
||||
"foreign-step": {ID: "foreign-step", WorkflowID: "foreign-workflow"},
|
||||
},
|
||||
})
|
||||
|
||||
h := &Handlers{
|
||||
taskSvc: svc,
|
||||
logger: testLogger(t).WithFields(),
|
||||
}
|
||||
msg := makeWSMessage(t, ws.ActionMCPCreateTask, map[string]interface{}{
|
||||
"workspace_id": workspaces[0].ID,
|
||||
"workflow_id": workflows[0].ID,
|
||||
"workflow_step_id": "foreign-step",
|
||||
"title": "Task with mismatched step",
|
||||
"agent_profile_id": "profile-1",
|
||||
"start_agent": false,
|
||||
})
|
||||
|
||||
resp, err := h.handleCreateTask(ctx, msg)
|
||||
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
var ep ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(resp.Payload, &ep))
|
||||
assert.Contains(t, ep.Message, "workflow step not found")
|
||||
}
|
||||
|
||||
func TestHandleCreateTask_StartAgentUsesWorkspaceDefaultAgentProfile(t *testing.T) {
|
||||
svc, _ := newTestTaskService(t)
|
||||
ctx := context.Background()
|
||||
@@ -1888,6 +1948,11 @@ func TestHandleCreateTask_SubtaskCanRequestNewWorkspaceMode(t *testing.T) {
|
||||
|
||||
func TestHandleCreateTask_SubtaskHonorsExplicitWorkspaceAndWorkflow(t *testing.T) {
|
||||
svc, repo := newTestTaskService(t)
|
||||
svc.SetWorkflowStepGetter(&staticWorkflowStepGetter{
|
||||
steps: map[string]*workflowmodels.WorkflowStep{
|
||||
"step-other": {ID: "step-other", WorkflowID: "wf-2"},
|
||||
},
|
||||
})
|
||||
ctx := context.Background()
|
||||
parentID := seedParentWithRepo(t, svc, repo)
|
||||
require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-2", Name: "Other"}))
|
||||
|
||||
@@ -68,6 +68,9 @@ func TestHandleListTasks_IncludesAssociatedPRs(t *testing.T) {
|
||||
require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{
|
||||
ID: "ws-pr", Name: "PR WS", CreatedAt: now, UpdatedAt: now,
|
||||
}))
|
||||
require.NoError(t, repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-pr", WorkspaceID: "ws-pr", Name: "PR Workflow", CreatedAt: now, UpdatedAt: now,
|
||||
}))
|
||||
require.NoError(t, repo.CreateTask(ctx, &models.Task{
|
||||
ID: "task-pr", WorkspaceID: "ws-pr", WorkflowID: "wf-pr",
|
||||
Title: "Has a PR", State: v1.TaskStateReview, CreatedAt: now, UpdatedAt: now,
|
||||
|
||||
@@ -82,3 +82,11 @@ func isValidationError(err error) bool {
|
||||
strings.Contains(msg, "invalid") ||
|
||||
strings.Contains(msg, "not allowed in a git ref name")
|
||||
}
|
||||
|
||||
func isTaskCreateValidationError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return isValidationError(err) ||
|
||||
strings.Contains(strings.ToLower(err.Error()), "workflow not found")
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
taskrepository "github.com/kandev/kandev/internal/task/repository"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
usermodels "github.com/kandev/kandev/internal/user/models"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
)
|
||||
@@ -315,6 +316,14 @@ type captureCreateTaskRepo struct {
|
||||
updateStateErr error
|
||||
}
|
||||
|
||||
type missingWorkflowCreateTaskRepo struct {
|
||||
captureCreateTaskRepo
|
||||
}
|
||||
|
||||
func (*missingWorkflowCreateTaskRepo) GetWorkflow(_ context.Context, id string) (*models.Workflow, error) {
|
||||
return nil, fmt.Errorf("workflow not found: %s", id)
|
||||
}
|
||||
|
||||
type captureTaskCreateLastUsedRecorder struct {
|
||||
calls int
|
||||
got usermodels.TaskCreateLastUsed
|
||||
@@ -330,6 +339,22 @@ func (m *captureCreateTaskRepo) GetWorkspaceTaskPrefix(_ context.Context, _ stri
|
||||
return "KAN", "wf-office", nil
|
||||
}
|
||||
|
||||
func (m *captureCreateTaskRepo) GetWorkflow(_ context.Context, id string) (*models.Workflow, error) {
|
||||
return &models.Workflow{ID: id, WorkspaceID: "ws-1"}, nil
|
||||
}
|
||||
|
||||
func (m *captureCreateTaskRepo) GetStep(_ context.Context, id string) (*wfmodels.WorkflowStep, error) {
|
||||
return &wfmodels.WorkflowStep{ID: id, WorkflowID: "wf-1"}, nil
|
||||
}
|
||||
|
||||
func (m *captureCreateTaskRepo) GetNextStepByPosition(
|
||||
context.Context,
|
||||
string,
|
||||
int,
|
||||
) (*wfmodels.WorkflowStep, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *captureCreateTaskRepo) GetRepository(_ context.Context, id string) (*models.Repository, error) {
|
||||
if id == "repo-2" {
|
||||
return &models.Repository{ID: id, WorkspaceID: "ws-1", DefaultBranch: "main"}, nil
|
||||
@@ -410,6 +435,7 @@ func TestHTTPCreateTaskRecordsFinalLastUsedSelections(t *testing.T) {
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
recorder := &captureTaskCreateLastUsedRecorder{}
|
||||
h := &TaskHandlers{service: svc, taskCreateLastUsedRecorder: recorder, logger: log}
|
||||
|
||||
@@ -454,6 +480,7 @@ func TestHTTPCreateTaskRecordsRepositoryWithoutProfileIDs(t *testing.T) {
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
recorder := &captureTaskCreateLastUsedRecorder{}
|
||||
h := &TaskHandlers{service: svc, taskCreateLastUsedRecorder: recorder, logger: log}
|
||||
|
||||
@@ -575,6 +602,7 @@ func TestWSCreateTaskRecordsFinalLastUsedSelections(t *testing.T) {
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
recorder := &captureTaskCreateLastUsedRecorder{}
|
||||
h := &TaskHandlers{service: svc, taskCreateLastUsedRecorder: recorder, logger: log}
|
||||
|
||||
@@ -616,6 +644,7 @@ func TestWSCreateTaskRecordsFreshBranchRequestBase(t *testing.T) {
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
recorder := &captureTaskCreateLastUsedRecorder{}
|
||||
h := &TaskHandlers{service: svc, taskCreateLastUsedRecorder: recorder, logger: log}
|
||||
|
||||
@@ -644,6 +673,67 @@ func TestWSCreateTaskRecordsFreshBranchRequestBase(t *testing.T) {
|
||||
}, recorder.got)
|
||||
}
|
||||
|
||||
func TestWSCreateTaskReturnsValidationErrorForMissingWorkflow(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
repo := &missingWorkflowCreateTaskRepo{}
|
||||
svc := service.NewService(service.Repos{
|
||||
Workspaces: repo, Tasks: repo, TaskRepos: repo,
|
||||
Workflows: repo, Messages: repo, Turns: repo,
|
||||
Sessions: repo, GitSnapshots: repo, RepoEntities: repo,
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
h := &TaskHandlers{service: svc, logger: log}
|
||||
|
||||
msg, err := ws.NewRequest("msg-1", ws.ActionTaskCreate, map[string]any{
|
||||
"workspace_id": "ws-1",
|
||||
"workflow_id": "missing-workflow",
|
||||
"title": "Broken workflow",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := h.wsCreateTask(context.Background(), msg)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ws.MessageTypeError, resp.Type)
|
||||
var payload ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(resp.Payload, &payload))
|
||||
assert.Equal(t, ws.ErrorCodeValidation, payload.Code)
|
||||
assert.Contains(t, payload.Message, "workflow not found")
|
||||
}
|
||||
|
||||
func TestWSCreateTaskReturnsValidationErrorForStepOutsideWorkflow(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
repo := &captureCreateTaskRepo{}
|
||||
svc := service.NewService(service.Repos{
|
||||
Workspaces: repo, Tasks: repo, TaskRepos: repo,
|
||||
Workflows: repo, Messages: repo, Turns: repo,
|
||||
Sessions: repo, GitSnapshots: repo, RepoEntities: repo,
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
h := &TaskHandlers{service: svc, logger: log}
|
||||
|
||||
msg, err := ws.NewRequest("msg-1", ws.ActionTaskCreate, map[string]any{
|
||||
"workspace_id": "ws-1",
|
||||
"workflow_id": "wf-2",
|
||||
"workflow_step_id": "step-1",
|
||||
"title": "Broken step",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := h.wsCreateTask(context.Background(), msg)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ws.MessageTypeError, resp.Type)
|
||||
var payload ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(resp.Payload, &payload))
|
||||
assert.Equal(t, ws.ErrorCodeValidation, payload.Code)
|
||||
assert.Contains(t, payload.Message, "workflow step not found")
|
||||
}
|
||||
|
||||
func TestHTTPCreateTask_StartAgentReturnsSchedulingTask(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
log := newTestLogger(t)
|
||||
@@ -656,6 +746,7 @@ func TestHTTPCreateTask_StartAgentReturnsSchedulingTask(t *testing.T) {
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
startCreatedCalled := make(chan struct{}, 1)
|
||||
orch := &captureOrchestrator{startCreatedCalled: startCreatedCalled}
|
||||
h := &TaskHandlers{service: svc, orchestrator: orch, logger: log}
|
||||
@@ -697,6 +788,7 @@ func TestHTTPCreateTask_StartAgentKeepsCreatedStateWhenSchedulingUpdateFails(t *
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkflowStepGetter(repo)
|
||||
startCreatedCalled := make(chan struct{}, 1)
|
||||
orch := &captureOrchestrator{startCreatedCalled: startCreatedCalled}
|
||||
h := &TaskHandlers{service: svc, orchestrator: orch, logger: log}
|
||||
|
||||
@@ -171,6 +171,9 @@ func (h *TaskHandlers) wsCreateTask(ctx context.Context, msg *ws.Message) (*ws.M
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create task", zap.Error(err))
|
||||
if isTaskCreateValidationError(err) {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil)
|
||||
}
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create task", nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
)
|
||||
|
||||
func eventBusHasType(bus *MockEventBus, eventType string) bool {
|
||||
@@ -45,6 +46,12 @@ func (f *fakeBaseBranchPusher) snapshot() []fakeBaseBranchPusherCall {
|
||||
return out
|
||||
}
|
||||
|
||||
func setBranchUpdateWorkflowStep(svc *Service) {
|
||||
svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{
|
||||
"step-1": {ID: "step-1", WorkflowID: "wf-1", Name: "Step"},
|
||||
}})
|
||||
}
|
||||
|
||||
// TestUpdateRepositoryBaseBranch_ResetsSessionBases confirms the picker
|
||||
// path also clears session.base_commit_sha and rewrites session.base_branch
|
||||
// for affected (task, repo) pairs. Without this the commits panel and
|
||||
@@ -53,6 +60,7 @@ func (f *fakeBaseBranchPusher) snapshot() []fakeBaseBranchPusherCall {
|
||||
func TestUpdateRepositoryBaseBranch_ResetsSessionBases(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
setBranchUpdateWorkflowStep(svc)
|
||||
svc.SetAgentBaseBranchPusher(&fakeBaseBranchPusher{})
|
||||
|
||||
_ = repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "WS"})
|
||||
@@ -101,6 +109,7 @@ func TestUpdateRepositoryBaseBranch_ResetsSessionBases(t *testing.T) {
|
||||
func TestUpdateRepositoryBaseBranch_PersistsAndPushes(t *testing.T) {
|
||||
svc, bus, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
setBranchUpdateWorkflowStep(svc)
|
||||
pusher := &fakeBaseBranchPusher{}
|
||||
svc.SetAgentBaseBranchPusher(pusher)
|
||||
|
||||
@@ -177,6 +186,7 @@ func TestUpdateRepositoryBaseBranch_PersistsAndPushes(t *testing.T) {
|
||||
func TestUpdateRepositoryBaseBranch_NoChangeSkipsWork(t *testing.T) {
|
||||
svc, bus, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
setBranchUpdateWorkflowStep(svc)
|
||||
pusher := &fakeBaseBranchPusher{}
|
||||
svc.SetAgentBaseBranchPusher(pusher)
|
||||
|
||||
@@ -224,6 +234,7 @@ func TestUpdateRepositoryBaseBranch_NoChangeSkipsWork(t *testing.T) {
|
||||
func TestUpdateRepositoryBaseBranch_RejectsUnsafeRefs(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
setBranchUpdateWorkflowStep(svc)
|
||||
pusher := &fakeBaseBranchPusher{}
|
||||
svc.SetAgentBaseBranchPusher(pusher)
|
||||
|
||||
@@ -257,6 +268,7 @@ func TestUpdateRepositoryBaseBranch_RejectsUnsafeRefs(t *testing.T) {
|
||||
func TestUpdateRepositoryBaseBranch_NotFound(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
setBranchUpdateWorkflowStep(svc)
|
||||
_ = repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "WS"})
|
||||
_ = repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-1", WorkspaceID: "ws-1", Name: "WF"})
|
||||
_ = repo.CreateRepository(ctx, &models.Repository{ID: "repo-1", WorkspaceID: "ws-1", Name: "frontend", DefaultBranch: "main"})
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestCreateChildTask_HappyPath_InheritsWorkflow(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCreateChildTask_OverridesWorkflow(t *testing.T) {
|
||||
svc, _ := setupOfficeTest(t)
|
||||
svc, repo := setupOfficeTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
parent, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
@@ -64,10 +64,13 @@ func TestCreateChildTask_OverridesWorkflow(t *testing.T) {
|
||||
t.Fatalf("create parent: %v", err)
|
||||
}
|
||||
|
||||
// Override with a workflow id different from parent's. The repository
|
||||
// stores whatever workflow id we pass — even if there's no rows for
|
||||
// it in workflow_steps, we just want to confirm the request shape.
|
||||
// Override with another workflow in the parent's workspace.
|
||||
otherWorkflowID := parent.WorkflowID + "-override"
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: otherWorkflowID, WorkspaceID: parent.WorkspaceID, Name: "Override",
|
||||
}); err != nil {
|
||||
t.Fatalf("create override workflow: %v", err)
|
||||
}
|
||||
childID, err := svc.CreateChildTask(ctx, parent, ChildTaskSpec{
|
||||
Title: "Switch flow",
|
||||
WorkflowID: otherWorkflowID,
|
||||
|
||||
@@ -591,6 +591,9 @@ func (s *Service) DeleteWorkflow(ctx context.Context, id string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if workflow == nil {
|
||||
return fmt.Errorf("workflow not found: %s", id)
|
||||
}
|
||||
|
||||
tasks, err := s.tasks.ListTasks(ctx, id)
|
||||
if err != nil {
|
||||
@@ -600,6 +603,19 @@ func (s *Service) DeleteWorkflow(ctx context.Context, id string) error {
|
||||
}
|
||||
archived := 0
|
||||
for _, task := range tasks {
|
||||
if task == nil || task.WorkspaceID != workflow.WorkspaceID {
|
||||
taskID, taskWorkspaceID := "", ""
|
||||
if task != nil {
|
||||
taskID = task.ID
|
||||
taskWorkspaceID = task.WorkspaceID
|
||||
}
|
||||
s.logger.Warn("skipping task outside workflow workspace during workflow delete cascade",
|
||||
zap.String("workflow_id", id),
|
||||
zap.String("workflow_workspace_id", workflow.WorkspaceID),
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("task_workspace_id", taskWorkspaceID))
|
||||
continue
|
||||
}
|
||||
if err := s.ArchiveTask(ctx, task.ID); err != nil {
|
||||
// Concurrent archive between ListTasks and here is a no-op:
|
||||
// the task is already in the desired state, keep cascading.
|
||||
|
||||
@@ -1085,6 +1085,64 @@ func TestService_DeleteWorkflow_ArchivesChildTasks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_DeleteWorkflow_IgnoresLegacyTaskFromAnotherWorkspace(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, workspace := range []*models.Workspace{
|
||||
{ID: "ws-victim", Name: "Victim", OwnerID: "user-victim"},
|
||||
{ID: "ws-foreign", Name: "Foreign", OwnerID: "user-foreign"},
|
||||
} {
|
||||
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
|
||||
t.Fatalf("CreateWorkspace %s: %v", workspace.ID, err)
|
||||
}
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-victim", WorkspaceID: "ws-victim", Name: "Victim workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
for _, task := range []*models.Task{
|
||||
{
|
||||
ID: "task-valid", WorkspaceID: "ws-victim", WorkflowID: "wf-victim",
|
||||
WorkflowStepID: "step-1", Title: "Valid",
|
||||
},
|
||||
{
|
||||
ID: "task-legacy-foreign", WorkspaceID: "ws-foreign", WorkflowID: "wf-victim",
|
||||
WorkflowStepID: "step-1", Title: "Legacy foreign",
|
||||
},
|
||||
} {
|
||||
if err := repo.CreateTask(ctx, task); err != nil {
|
||||
t.Fatalf("CreateTask %s: %v", task.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := svc.DeleteWorkflow(ctxAs("user-victim"), "wf-victim"); err != nil {
|
||||
t.Fatalf("DeleteWorkflow: %v", err)
|
||||
}
|
||||
|
||||
if _, err := repo.GetWorkflow(ctx, "wf-victim"); err == nil {
|
||||
t.Fatal("victim workflow still exists after deletion")
|
||||
}
|
||||
valid, err := repo.GetTask(ctx, "task-valid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask valid: %v", err)
|
||||
}
|
||||
if valid.ArchivedAt == nil {
|
||||
t.Fatal("valid same-workspace task was not archived")
|
||||
}
|
||||
foreign, err := repo.GetTask(ctx, "task-legacy-foreign")
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask legacy foreign: %v", err)
|
||||
}
|
||||
if foreign.ArchivedAt != nil {
|
||||
t.Fatalf("legacy foreign task was mutated: archived_at=%v", foreign.ArchivedAt)
|
||||
}
|
||||
if foreign.WorkspaceID != "ws-foreign" || foreign.WorkflowID != "wf-victim" {
|
||||
t.Fatalf("legacy foreign task identity changed: %+v", foreign)
|
||||
}
|
||||
}
|
||||
|
||||
// leakyListTaskRepo wraps the real TaskRepository and injects extra tasks
|
||||
// into ListTasks results, simulating a TOCTOU race where a task is archived
|
||||
// between the snapshot and the cascade loop.
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
taskrepository "github.com/kandev/kandev/internal/task/repository"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
type nilWorkflowRepository struct {
|
||||
taskrepository.WorkflowRepository
|
||||
}
|
||||
|
||||
func (nilWorkflowRepository) GetWorkflow(context.Context, string) (*models.Workflow, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsWorkflowOutsideRequestedWorkspace(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, workspace := range []*models.Workspace{
|
||||
{ID: "ws-a", Name: "A", OwnerID: "user-a"},
|
||||
{ID: "ws-b", Name: "B", OwnerID: "user-b"},
|
||||
} {
|
||||
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
|
||||
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
|
||||
}
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-b", WorkspaceID: "ws-b", Name: "B workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
|
||||
_, err := svc.CreateTask(ctxAs("user-a"), &CreateTaskRequest{
|
||||
WorkspaceID: "ws-a",
|
||||
WorkflowID: "wf-b",
|
||||
Title: "cross-workspace task",
|
||||
})
|
||||
if !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
|
||||
t.Fatalf("CreateTask error = %v, want workspace not found", err)
|
||||
}
|
||||
|
||||
tasks, listErr := repo.ListTasks(ctx, "wf-b")
|
||||
if listErr != nil {
|
||||
t.Fatalf("ListTasks: %v", listErr)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("persisted %d cross-workspace tasks, want none", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsNonexistentWorkflow(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "missing-workflow",
|
||||
Title: "orphaned task",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("CreateTask succeeded with a nonexistent workflow")
|
||||
}
|
||||
|
||||
tasks, listErr := repo.ListTasks(ctx, "missing-workflow")
|
||||
if listErr != nil {
|
||||
t.Fatalf("ListTasks: %v", listErr)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("persisted %d tasks with a nonexistent workflow, want none", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsNilWorkflowResult(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
svc.workflows = nilWorkflowRepository{WorkflowRepository: repo}
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "missing-workflow",
|
||||
Title: "orphaned task",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidTaskWorkflow) {
|
||||
t.Fatalf("CreateTask error = %v, want invalid task workflow", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsExplicitStepOutsideRequestedWorkflow(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
for _, workflow := range []*models.Workflow{
|
||||
{ID: "wf-a", WorkspaceID: "ws-1", Name: "A workflow"},
|
||||
{ID: "wf-b", WorkspaceID: "ws-1", Name: "B workflow"},
|
||||
} {
|
||||
if err := repo.CreateWorkflow(ctx, workflow); err != nil {
|
||||
t.Fatalf("CreateWorkflow(%s): %v", workflow.ID, err)
|
||||
}
|
||||
}
|
||||
svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{
|
||||
"step-b": {ID: "step-b", WorkflowID: "wf-b", Name: "B step"},
|
||||
}})
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "wf-a",
|
||||
WorkflowStepID: "step-b",
|
||||
Title: "cross-workflow step task",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidTaskWorkflow) {
|
||||
t.Fatalf("CreateTask error = %v, want invalid task workflow", err)
|
||||
}
|
||||
|
||||
tasks, listErr := repo.ListTasks(ctx, "wf-a")
|
||||
if listErr != nil {
|
||||
t.Fatalf("ListTasks: %v", listErr)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("persisted %d cross-workflow step tasks, want none", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsNonexistentExplicitStep(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-1", WorkspaceID: "ws-1", Name: "Workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{}})
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "wf-1",
|
||||
WorkflowStepID: "missing-step",
|
||||
Title: "orphaned step task",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidTaskWorkflow) {
|
||||
t.Fatalf("CreateTask error = %v, want invalid task workflow", err)
|
||||
}
|
||||
|
||||
tasks, listErr := repo.ListTasks(ctx, "wf-1")
|
||||
if listErr != nil {
|
||||
t.Fatalf("ListTasks: %v", listErr)
|
||||
}
|
||||
if len(tasks) != 0 {
|
||||
t.Fatalf("persisted %d tasks with a nonexistent explicit step, want none", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsExplicitStepWhenValidationUnavailable(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
svc.SetWorkflowStepGetter(nil)
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-1", WorkspaceID: "ws-1", Name: "Workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "wf-1",
|
||||
WorkflowStepID: "step-1",
|
||||
Title: "unvalidated step task",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidTaskWorkflow) {
|
||||
t.Fatalf("CreateTask error = %v, want invalid task workflow", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsExplicitStepWithoutWorkflow(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
|
||||
_, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowStepID: "step-1",
|
||||
Title: "orphaned step task",
|
||||
IsEphemeral: true,
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidTaskWorkflow) {
|
||||
t.Fatalf("CreateTask error = %v, want invalid task workflow", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskAcceptsConsistentWorkflowAndExplicitStep(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-1", WorkspaceID: "ws-1", Name: "Workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
svc.SetWorkflowStepGetter(&fakeWorkflowStepGetter{steps: map[string]*wfmodels.WorkflowStep{
|
||||
"step-1": {ID: "step-1", WorkflowID: "wf-1", Name: "Step"},
|
||||
}})
|
||||
|
||||
task, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "wf-1",
|
||||
WorkflowStepID: "step-1",
|
||||
Title: "consistent task",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
if task.WorkspaceID != "ws-1" || task.WorkflowID != "wf-1" || task.WorkflowStepID != "step-1" {
|
||||
t.Fatalf("created task has inconsistent IDs: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskAcceptsEphemeralTaskWithoutWorkflow(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
|
||||
task, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-1",
|
||||
Title: "quick chat",
|
||||
IsEphemeral: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
if task.WorkflowID != "" || task.WorkflowStepID != "" || !task.IsEphemeral {
|
||||
t.Fatalf("created ephemeral task has unexpected workflow fields: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListTasksExcludesLegacyRowsFromAnotherWorkspace(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, workspace := range []*models.Workspace{
|
||||
{ID: "ws-a", Name: "A", OwnerID: "user-a"},
|
||||
{ID: "ws-b", Name: "B", OwnerID: "user-b"},
|
||||
} {
|
||||
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
|
||||
t.Fatalf("CreateWorkspace(%s): %v", workspace.ID, err)
|
||||
}
|
||||
}
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "wf-b", WorkspaceID: "ws-b", Name: "B workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateWorkflow: %v", err)
|
||||
}
|
||||
for _, task := range []*models.Task{
|
||||
{
|
||||
ID: "valid-b", WorkspaceID: "ws-b", WorkflowID: "wf-b",
|
||||
Title: "valid", State: v1.TaskStateCreated, Priority: defaultPriority,
|
||||
},
|
||||
{
|
||||
ID: "legacy-a", WorkspaceID: "ws-a", WorkflowID: "wf-b",
|
||||
Title: "legacy inconsistent", State: v1.TaskStateCreated, Priority: defaultPriority,
|
||||
},
|
||||
} {
|
||||
if err := repo.CreateTask(ctx, task); err != nil {
|
||||
t.Fatalf("CreateTask(%s): %v", task.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
tasks, err := svc.ListTasks(ctxAs("user-b"), "wf-b")
|
||||
if err != nil {
|
||||
t.Fatalf("ListTasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 1 || tasks[0].ID != "valid-b" {
|
||||
t.Fatalf("ListTasks returned %+v, want only valid-b", tasks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListTasksRejectsNilWorkflowResult(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
svc.workflows = nilWorkflowRepository{WorkflowRepository: repo}
|
||||
|
||||
if _, err := svc.ListTasks(context.Background(), "missing-workflow"); err == nil {
|
||||
t.Fatal("ListTasks succeeded with a nil workflow result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteWorkflowRejectsNilWorkflowResult(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if err := repo.CreateTask(ctx, &models.Task{
|
||||
ID: "legacy-task",
|
||||
WorkspaceID: "ws-1",
|
||||
WorkflowID: "missing-workflow",
|
||||
Title: "Legacy task",
|
||||
State: v1.TaskStateCreated,
|
||||
Priority: defaultPriority,
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
svc.workflows = nilWorkflowRepository{WorkflowRepository: repo}
|
||||
|
||||
if err := svc.DeleteWorkflow(ctx, "missing-workflow"); err == nil {
|
||||
t.Fatal("DeleteWorkflow succeeded with a nil workflow result")
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
taskrepo "github.com/kandev/kandev/internal/task/repository"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
)
|
||||
|
||||
@@ -42,6 +43,10 @@ const defaultKandevTaskWorktreePathSegment = "/.kandev/tasks/"
|
||||
// intentionally exempt.
|
||||
var ErrSubtaskDepthExceeded = fmt.Errorf("cannot create a subtask of a subtask — maximum nesting depth is 1 for kanban tasks. Create a sibling task under the same parent or a top-level task instead")
|
||||
|
||||
// ErrInvalidTaskWorkflow identifies task creation requests whose explicit
|
||||
// workflow or workflow step relationship is inconsistent.
|
||||
var ErrInvalidTaskWorkflow = errors.New("invalid task workflow")
|
||||
|
||||
// ErrTaskAlreadyArchived is returned by ArchiveTask when the target task
|
||||
// already has archived_at set. Sentinel so cascade callers (e.g.
|
||||
// DeleteWorkflow) can treat a concurrent archive as a no-op instead of
|
||||
@@ -114,6 +119,9 @@ func (s *Service) CreateTask(ctx context.Context, req *CreateTaskRequest) (*mode
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.validateTaskWorkflow(ctx, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
workflowStepID := s.resolveWorkflowStep(ctx, req)
|
||||
task := s.buildTask(req, workflowStepID)
|
||||
@@ -208,6 +216,39 @@ func (s *Service) validateCreateTaskRequest(req *CreateTaskRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) validateTaskWorkflow(ctx context.Context, req *CreateTaskRequest) error {
|
||||
if req.WorkflowID == "" {
|
||||
if req.WorkflowStepID != "" {
|
||||
return fmt.Errorf("%w: workflow_step_id requires workflow_id", ErrInvalidTaskWorkflow)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
workflow, err := s.workflows.GetWorkflow(ctx, req.WorkflowID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if workflow == nil {
|
||||
return fmt.Errorf("%w: workflow not found", ErrInvalidTaskWorkflow)
|
||||
}
|
||||
if workflow.WorkspaceID != req.WorkspaceID {
|
||||
return repoerrors.ErrWorkspaceNotFound
|
||||
}
|
||||
if req.WorkflowStepID == "" {
|
||||
return nil
|
||||
}
|
||||
if s.workflowStepGetter == nil {
|
||||
return fmt.Errorf("%w: workflow step validation unavailable", ErrInvalidTaskWorkflow)
|
||||
}
|
||||
step, err := s.workflowStepGetter.GetStep(ctx, req.WorkflowStepID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: workflow_step_id: %w", ErrInvalidTaskWorkflow, err)
|
||||
}
|
||||
if step == nil || step.WorkflowID != req.WorkflowID {
|
||||
return fmt.Errorf("%w: workflow step not found: %s", ErrInvalidTaskWorkflow, req.WorkflowStepID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateSubtaskDepth prevents nesting deeper than one level for kanban
|
||||
// (non-office) tasks. Office task trees intentionally allow arbitrary depth.
|
||||
func (s *Service) validateSubtaskDepth(ctx context.Context, req *CreateTaskRequest) error {
|
||||
@@ -2392,10 +2433,18 @@ func (s *Service) ListTasks(ctx context.Context, workflowID string) ([]*models.T
|
||||
if err := s.authorizeWorkflowID(ctx, workflowID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
workflow, err := s.workflows.GetWorkflow(ctx, workflowID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if workflow == nil {
|
||||
return nil, fmt.Errorf("workflow not found: %s", workflowID)
|
||||
}
|
||||
tasks, err := s.tasks.ListTasks(ctx, workflowID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = filterTasksByWorkspace(tasks, workflow.WorkspaceID)
|
||||
|
||||
if err := s.loadTaskRepositoriesBatch(ctx, tasks); err != nil {
|
||||
s.logger.Error("failed to batch-load task repositories", zap.Error(err))
|
||||
@@ -2405,6 +2454,16 @@ func (s *Service) ListTasks(ctx context.Context, workflowID string) ([]*models.T
|
||||
return tasks, nil
|
||||
}
|
||||
|
||||
func filterTasksByWorkspace(tasks []*models.Task, workspaceID string) []*models.Task {
|
||||
filtered := tasks[:0]
|
||||
for _, task := range tasks {
|
||||
if task != nil && task.WorkspaceID == workspaceID {
|
||||
filtered = append(filtered, task)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// ListTasksByWorkspace returns paginated tasks for a workspace with task repositories loaded.
|
||||
// If query is non-empty, filters by task title, description, repository name, or repository path.
|
||||
// workflowID and repositoryID, when non-empty, further restrict results to that workflow/repository.
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository"
|
||||
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
workflowrepo "github.com/kandev/kandev/internal/workflow/repository"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
@@ -87,6 +88,45 @@ func createTestService(t *testing.T) (*Service, *MockEventBus, *sqliterepo.Repos
|
||||
})
|
||||
}
|
||||
|
||||
// testWorkflowStepGetter keeps legacy service tests focused on their own
|
||||
// behavior while mirroring production's required workflow-step dependency.
|
||||
// Integrity tests install an exact getter (or nil) for boundary assertions.
|
||||
type testWorkflowStepGetter struct {
|
||||
repo *sqliterepo.Repository
|
||||
}
|
||||
|
||||
func (g *testWorkflowStepGetter) GetStep(ctx context.Context, stepID string) (*wfmodels.WorkflowStep, error) {
|
||||
rows, err := g.repo.DB().QueryContext(ctx, `SELECT id FROM workflows ORDER BY created_at DESC, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
workflowIDs := make([]string, 0, 1)
|
||||
derivedWorkflowID := strings.Replace(stepID, "step", "wf", 1)
|
||||
for rows.Next() {
|
||||
var workflowID string
|
||||
if err := rows.Scan(&workflowID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if workflowID == derivedWorkflowID {
|
||||
return &wfmodels.WorkflowStep{ID: stepID, WorkflowID: workflowID}, nil
|
||||
}
|
||||
workflowIDs = append(workflowIDs, workflowID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(workflowIDs) > 0 {
|
||||
return &wfmodels.WorkflowStep{ID: stepID, WorkflowID: workflowIDs[0]}, nil
|
||||
}
|
||||
return nil, errors.New("workflow step not found")
|
||||
}
|
||||
|
||||
func (*testWorkflowStepGetter) GetNextStepByPosition(context.Context, string, int) (*wfmodels.WorkflowStep, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// createTestServiceWithSessionsRepo mirrors createTestService but lets a
|
||||
// caller substitute the Sessions repository (e.g. to wrap it with a test-only
|
||||
// hook) while reusing the same DB setup, migrations, and cleanup-worker
|
||||
@@ -148,6 +188,7 @@ func createTestServiceWithSessionsRepo(
|
||||
ResourceCleanups: repo,
|
||||
}, eventBus, log, RepositoryDiscoveryConfig{})
|
||||
svc.SetWorkspaceBootstrapper(repo)
|
||||
svc.SetWorkflowStepGetter(&testWorkflowStepGetter{repo: repo})
|
||||
if err := svc.StartTaskResourceCleanupWorker(context.Background()); err != nil {
|
||||
t.Fatalf("failed to start task resource cleanup worker: %v", err)
|
||||
}
|
||||
|
||||
@@ -38,13 +38,16 @@ const storeState = {
|
||||
items: [
|
||||
{ id: "w1", name: "Default Workspace", office_workflow_id: "" },
|
||||
{ id: "w2", name: "Office Workspace", office_workflow_id: "wf-office" },
|
||||
{ id: "w3", name: "Alternate Workspace", office_workflow_id: "" },
|
||||
],
|
||||
activeId: "w1",
|
||||
},
|
||||
setActiveWorkspace: vi.fn(),
|
||||
resetKanbanWorkspaceContext: vi.fn(),
|
||||
};
|
||||
const KANBAN_WORKSPACE_ITEM = "sidebar-workspace-item-w1";
|
||||
const OFFICE_WORKSPACE_ITEM = "sidebar-workspace-item-w2";
|
||||
const ALTERNATE_KANBAN_WORKSPACE_ITEM = "sidebar-workspace-item-w3";
|
||||
// jsdom over http drops `secure` cookies, so intercept the setter to capture
|
||||
// the write directly rather than reading `document.cookie` back.
|
||||
let cookieWrites: string[] = [];
|
||||
@@ -55,6 +58,7 @@ function resetWorkspaceSelectTest() {
|
||||
storeState.features.office = false;
|
||||
storeState.workspaces.activeId = "w1";
|
||||
storeState.setActiveWorkspace = vi.fn();
|
||||
storeState.resetKanbanWorkspaceContext = vi.fn();
|
||||
cookieWrites = [];
|
||||
cookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, "cookie");
|
||||
Object.defineProperty(document, "cookie", {
|
||||
@@ -156,6 +160,20 @@ describe("AppSidebarWorkspacePicker — workspace select", () => {
|
||||
expect(navigationMock.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears stale kanban context and routes to another kanban workspace with office disabled", () => {
|
||||
storeState.features.office = false;
|
||||
render(<AppSidebarWorkspacePicker />);
|
||||
|
||||
fireEvent.click(screen.getByTestId(ALTERNATE_KANBAN_WORKSPACE_ITEM));
|
||||
|
||||
expect(storeState.resetKanbanWorkspaceContext).toHaveBeenCalledOnce();
|
||||
expect(storeState.resetKanbanWorkspaceContext.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
storeState.setActiveWorkspace.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(storeState.setActiveWorkspace).toHaveBeenCalledWith("w3");
|
||||
expect(navigationMock.push).toHaveBeenCalledWith("/?workspaceId=w3");
|
||||
});
|
||||
|
||||
it("calls onActionComplete when selecting a different workspace", () => {
|
||||
const onActionComplete = vi.fn();
|
||||
storeState.features.office = false;
|
||||
|
||||
@@ -215,6 +215,7 @@ export function AppSidebarWorkspacePicker({
|
||||
const officeEnabled = useFeature("office");
|
||||
const workspaces = useAppStore((s) => s.workspaces);
|
||||
const setActiveWorkspace = useAppStore((s) => s.setActiveWorkspace);
|
||||
const resetKanbanWorkspaceContext = useAppStore((s) => s.resetKanbanWorkspaceContext);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const activeWorkspace = workspaces.items.find((w) => w.id === workspaces.activeId);
|
||||
@@ -241,15 +242,25 @@ export function AppSidebarWorkspacePicker({
|
||||
rememberLastOfficeWorkspace(workspace);
|
||||
}
|
||||
rememberLastKanbanWorkspace(workspace);
|
||||
resetKanbanWorkspaceContext();
|
||||
setActiveWorkspace(id);
|
||||
if (officeEnabled) {
|
||||
const target = type === "office" ? "/office" : "/";
|
||||
router.push(`${target}?workspaceId=${id}`);
|
||||
if (type === "kanban") {
|
||||
router.push(`/?workspaceId=${id}`);
|
||||
} else if (officeEnabled) {
|
||||
router.push(`/office?workspaceId=${id}`);
|
||||
}
|
||||
setOpen(false);
|
||||
onActionComplete?.();
|
||||
},
|
||||
[activeId, activeWorkspace, router, setActiveWorkspace, officeEnabled, onActionComplete],
|
||||
[
|
||||
activeId,
|
||||
activeWorkspace,
|
||||
router,
|
||||
setActiveWorkspace,
|
||||
resetKanbanWorkspaceContext,
|
||||
officeEnabled,
|
||||
onActionComplete,
|
||||
],
|
||||
);
|
||||
const handleNavigate = useCallback(
|
||||
(href: string) => {
|
||||
|
||||
@@ -25,7 +25,7 @@ export const test = base.extend<{ testPage: Page }, OfficeFixtures>({
|
||||
// Worker-scoped: complete onboarding once per worker and expose the
|
||||
// resulting workspace/agent/project IDs to all tests in the suite.
|
||||
officeSeed: [
|
||||
async ({ officeApi, seedData }, use) => {
|
||||
async ({ officeApi, apiClient, seedData }, use) => {
|
||||
const result = await officeApi.completeOnboarding({
|
||||
workspaceName: "E2E Workspace",
|
||||
taskPrefix: "E2E",
|
||||
@@ -33,11 +33,20 @@ export const test = base.extend<{ testPage: Page }, OfficeFixtures>({
|
||||
agentProfileId: seedData.agentProfileId,
|
||||
executorPreference: "local_pc",
|
||||
});
|
||||
const { workspaces } = await apiClient.listWorkspaces();
|
||||
const workflowId = workspaces.find(
|
||||
(workspace) => workspace.id === result.workspaceId,
|
||||
)?.office_workflow_id;
|
||||
if (!workflowId) {
|
||||
throw new Error(
|
||||
`E2E office seed failed: workspace ${result.workspaceId} has no office workflow`,
|
||||
);
|
||||
}
|
||||
await use({
|
||||
workspaceId: result.workspaceId,
|
||||
agentId: result.agentId,
|
||||
projectId: result.projectId,
|
||||
workflowId: seedData.workflowId,
|
||||
workflowId,
|
||||
});
|
||||
},
|
||||
{ scope: "worker" },
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { useRegularMode } from "../../helpers/regular-mode";
|
||||
import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
|
||||
|
||||
useRegularMode();
|
||||
|
||||
test("mobile creates in the selected workspace after leaving an open task", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const workspaceA = await apiClient.createWorkspace("Mobile Workspace A");
|
||||
const { workflows: workspaceAWorkflows } = await apiClient.listWorkflows(workspaceA.id);
|
||||
const workflowA = workspaceAWorkflows[0];
|
||||
if (!workflowA) throw new Error("mobile workspace A has no bootstrap workflow");
|
||||
const { steps: workspaceASteps } = await apiClient.listWorkflowSteps(workflowA.id);
|
||||
const startStepA = workspaceASteps.find((step) => step.is_start_step) ?? workspaceASteps[0];
|
||||
if (!startStepA) throw new Error("mobile workspace A workflow has no steps");
|
||||
const taskA = await apiClient.createTask(workspaceA.id, "Mobile Workspace A Task", {
|
||||
workflow_id: workflowA.id,
|
||||
workflow_step_id: startStepA.id,
|
||||
});
|
||||
|
||||
const mobile = new MobileKanbanPage(testPage);
|
||||
await mobile.goto();
|
||||
await mobile.mobileMenuButton.tap();
|
||||
await testPage.getByTestId("mobile-workspace-trigger").tap();
|
||||
await testPage.getByTestId(`mobile-workspace-item-${workspaceA.id}`).tap();
|
||||
await expect(mobile.taskCard(taskA.id)).toBeVisible({ timeout: 10_000 });
|
||||
await mobile.taskCard(taskA.id).tap();
|
||||
await expect(testPage).toHaveURL(new RegExp(`/t/${taskA.id}$`));
|
||||
await expect(
|
||||
testPage.locator("header").getByText("Mobile Workspace A Task", { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
// The phone task workbench has no workspace picker. Its existing back action
|
||||
// returns to the board, whose responsive Menu drawer owns workspace switching.
|
||||
await testPage.locator('header a[href="/"]').tap();
|
||||
await expect(mobile.mobileKanbanLayout()).toBeVisible();
|
||||
await mobile.mobileMenuButton.tap();
|
||||
await testPage.getByTestId("mobile-workspace-trigger").tap();
|
||||
await testPage.getByTestId(`mobile-workspace-item-${seedData.workspaceId}`).tap();
|
||||
|
||||
await expect(testPage).toHaveURL(
|
||||
(url) => url.pathname === "/" && url.searchParams.get("workspaceId") === seedData.workspaceId,
|
||||
);
|
||||
await expect(mobile.taskCard(taskA.id)).not.toBeVisible();
|
||||
|
||||
const createdTitle = "Mobile Workspace B UI Task";
|
||||
await mobile.mobileFab.tap();
|
||||
const dialog = testPage.getByTestId("create-task-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByTestId("source-mode-scratch").tap();
|
||||
await dialog.getByTestId("task-title-input").fill(createdTitle);
|
||||
await dialog.getByTestId("task-description-input").fill("Created after changing workspace");
|
||||
const createOnly = dialog.getByRole("button", { name: "Create only" });
|
||||
await expect(createOnly).toBeEnabled();
|
||||
|
||||
const createdResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().endsWith("/api/v1/tasks") && response.request().method() === "POST",
|
||||
);
|
||||
await createOnly.tap();
|
||||
const createdTask = (await createdResponse).json() as Promise<{ id: string }>;
|
||||
const createdTaskId = (await createdTask).id;
|
||||
|
||||
await expect(dialog).not.toBeVisible();
|
||||
await expect(mobile.taskCard(createdTaskId)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(mobile.taskCard(taskA.id)).not.toBeVisible();
|
||||
|
||||
await mobile.mobileMenuButton.tap();
|
||||
await testPage.getByTestId("mobile-workspace-trigger").tap();
|
||||
await testPage.getByTestId(`mobile-workspace-item-${workspaceA.id}`).tap();
|
||||
await expect(mobile.taskCard(taskA.id)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(mobile.taskCard(createdTaskId)).not.toBeVisible();
|
||||
});
|
||||
@@ -30,14 +30,12 @@ function taskInList(page: Page, title: string): Locator {
|
||||
return page.getByTestId("tasks-list").getByText(title);
|
||||
}
|
||||
|
||||
// Office off: the picker routes a workspace switch to `/office` only when the
|
||||
// office feature is on, and `/office` requires onboarding this regular fixture
|
||||
// doesn't perform (it errors). With office off the switch happens in place on
|
||||
// the board, exercising the same cross-workspace isolation.
|
||||
// The production default has Office disabled. Kanban workspace navigation must
|
||||
// still leave an open task route and land on the selected workspace's board.
|
||||
useRegularMode();
|
||||
|
||||
test.describe("Sidebar — cross-workspace isolation", () => {
|
||||
test("tasks from the previous workspace do not leak into the sidebar after switching", async ({
|
||||
test("tasks from the previous workspace do not leak after switching", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
@@ -53,6 +51,9 @@ test.describe("Sidebar — cross-workspace isolation", () => {
|
||||
// --- Create workspace B with its own workflow, repo, and task ---
|
||||
const workspaceB = await apiClient.createWorkspace("Workspace B");
|
||||
const workflowB = await apiClient.createWorkflow(workspaceB.id, "Workflow B", "simple");
|
||||
await apiClient.updateWorkflow(workflowB.id, {
|
||||
agent_profile_id: seedData.agentProfileId,
|
||||
});
|
||||
const { steps: stepsB } = await apiClient.listWorkflowSteps(workflowB.id);
|
||||
const startStepB = [...stepsB]
|
||||
.sort((a, b) => a.position - b.position)
|
||||
@@ -79,47 +80,120 @@ test.describe("Sidebar — cross-workspace isolation", () => {
|
||||
repository_ids: [repoB.id],
|
||||
});
|
||||
|
||||
// --- Land on kanban with workspace A active; task A visible, task B not ---
|
||||
// --- Open task A so the route and task/session context belong to workspace A ---
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
await expect(kanban.taskCard(taskA.id)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(kanban.taskCard(taskB.id)).not.toBeVisible();
|
||||
await kanban.taskCard(taskA.id).click();
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForLoad();
|
||||
await expect(testPage).toHaveURL(new RegExp(`/t/${taskA.id}$`));
|
||||
|
||||
// --- Switch to workspace B via the sidebar workspace picker ---
|
||||
// The picker (top of the sidebar) is now the only workspace switcher. With
|
||||
// office off it switches in place (no /office redirect, no full reload), so
|
||||
// the board re-renders from the in-memory store with workspace B's tasks and
|
||||
// none of workspace A's.
|
||||
await testPage.getByTestId("sidebar-workspace-trigger").click();
|
||||
await testPage.getByTestId(`sidebar-workspace-item-${workspaceB.id}`).click();
|
||||
|
||||
await expect(testPage).toHaveURL(
|
||||
(url) => url.pathname === "/" && url.searchParams.get("workspaceId") === workspaceB.id,
|
||||
);
|
||||
await expect(kanban.board).toBeVisible();
|
||||
await expect(testPage.getByTestId("dockview-task-layout")).toHaveCount(0);
|
||||
await expect(kanban.taskCard(taskB.id)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(kanban.taskCard(taskA.id)).not.toBeVisible();
|
||||
await expect.poll(() => activeWorkspaceCookie(testPage)).toBe(workspaceB.id);
|
||||
|
||||
// A hard reload must bootstrap the same active workspace from the cookie,
|
||||
// before client-side effects have a chance to switch from the default seed workspace.
|
||||
// A hard reload and the task-list route must bootstrap the same cookie-backed
|
||||
// workspace before client effects can fall back to the seed workspace.
|
||||
await testPage.reload();
|
||||
await kanban.board.waitFor({ state: "visible" });
|
||||
await expect(kanban.taskCard(taskB.id)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(kanban.taskCard(taskA.id)).not.toBeVisible();
|
||||
|
||||
// --- Open task B; verify sidebar shows only workspace B's task ---
|
||||
await kanban.taskCard(taskB.id).click();
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForLoad();
|
||||
await expect(session.sidebar).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await expect(session.sidebar.getByText("Workspace B Task", { exact: true })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
|
||||
await expect(session.sidebar.getByText("Workspace A Task", { exact: true })).toHaveCount(0);
|
||||
await expect(session.sidebar.getByTestId("sidebar-repo-group-Unassigned")).toHaveCount(0);
|
||||
|
||||
// Direct route bootstrapping should use the same cookie-backed workspace.
|
||||
await gotoTaskList(testPage);
|
||||
await expect(taskInList(testPage, "Workspace B Task")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(taskInList(testPage, "Workspace A Task")).not.toBeVisible();
|
||||
});
|
||||
|
||||
test("creates only in the selected workspace after switching from an open task", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const workspaceA = await apiClient.createWorkspace("Workspace A Create Source");
|
||||
const { workflows: workspaceAWorkflows } = await apiClient.listWorkflows(workspaceA.id);
|
||||
const workflowA = workspaceAWorkflows[0];
|
||||
if (!workflowA) throw new Error("workspace A has no bootstrap workflow");
|
||||
const { steps: workspaceASteps } = await apiClient.listWorkflowSteps(workflowA.id);
|
||||
const startStepA = workspaceASteps.find((step) => step.is_start_step) ?? workspaceASteps[0];
|
||||
if (!startStepA) throw new Error("workspace A workflow has no steps");
|
||||
const taskA = await apiClient.createTask(workspaceA.id, "Workspace A Create Source", {
|
||||
workflow_id: workflowA.id,
|
||||
workflow_step_id: startStepA.id,
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
await testPage.getByTestId("sidebar-workspace-trigger").click();
|
||||
await testPage.getByTestId(`sidebar-workspace-item-${workspaceA.id}`).click();
|
||||
await expect(kanban.taskCard(taskA.id)).toBeVisible({ timeout: 10_000 });
|
||||
await kanban.taskCard(taskA.id).click();
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForLoad();
|
||||
|
||||
await testPage.getByTestId("sidebar-workspace-trigger").click();
|
||||
await testPage.getByTestId(`sidebar-workspace-item-${seedData.workspaceId}`).click();
|
||||
await expect(testPage).toHaveURL(
|
||||
(url) => url.pathname === "/" && url.searchParams.get("workspaceId") === seedData.workspaceId,
|
||||
);
|
||||
await expect(kanban.board).toBeVisible();
|
||||
await expect(testPage.getByTestId("dockview-task-layout")).toHaveCount(0);
|
||||
await expect(kanban.taskCard(taskA.id)).not.toBeVisible();
|
||||
|
||||
const createdTitle = "Workspace B UI Task";
|
||||
await kanban.createTaskButton.first().click();
|
||||
const dialog = testPage.getByTestId("create-task-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByTestId("source-mode-scratch").click();
|
||||
await dialog.getByTestId("task-title-input").fill(createdTitle);
|
||||
await dialog
|
||||
.getByTestId("task-description-input")
|
||||
.fill("Created after switching away from an open task");
|
||||
await expect(dialog.getByTestId("submit-start-agent-chevron")).toBeEnabled();
|
||||
|
||||
const createdResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().endsWith("/api/v1/tasks") && response.request().method() === "POST",
|
||||
);
|
||||
await dialog.getByTestId("submit-start-agent-chevron").click();
|
||||
await testPage.getByTestId("submit-create-without-agent").click();
|
||||
const createdTask = (await createdResponse).json() as Promise<{ id: string }>;
|
||||
const createdTaskId = (await createdTask).id;
|
||||
|
||||
await expect(dialog).not.toBeVisible();
|
||||
await expect(testPage).toHaveURL(new RegExp(`/t/${createdTaskId}$`));
|
||||
await expect(session.sidebar.getByText(createdTitle, { exact: true })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(
|
||||
session.sidebar.getByText("Workspace A Create Source", { exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
// The new task is on B's board and absent after switching back to A.
|
||||
await testPage.goto(`/?workspaceId=${seedData.workspaceId}`);
|
||||
await kanban.board.waitFor({ state: "visible" });
|
||||
await expect(kanban.taskCard(createdTaskId)).toBeVisible({ timeout: 10_000 });
|
||||
await testPage.getByTestId("sidebar-workspace-trigger").click();
|
||||
await testPage.getByTestId(`sidebar-workspace-item-${workspaceA.id}`).click();
|
||||
await expect(kanban.taskCard(taskA.id)).toBeVisible({ timeout: 10_000 });
|
||||
await expect(kanban.taskCard(createdTaskId)).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,8 @@ type SnapshotTask = {
|
||||
type MockState = {
|
||||
connection: { status: string };
|
||||
workflows: { items: Workflow[] };
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
kanbanMulti: {
|
||||
snapshots: Record<
|
||||
string,
|
||||
@@ -60,6 +62,8 @@ function resetState() {
|
||||
mocks.state = {
|
||||
connection: { status: "connected" },
|
||||
workflows: { items: [{ id: WORKFLOW_ID, workspaceId: WORKSPACE_ID, name: "A" }] },
|
||||
workspaces: { activeId: WORKSPACE_ID },
|
||||
workspaceContextGeneration: 0,
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
clearKanbanMulti: mocks.clearKanbanMulti,
|
||||
setKanbanMultiLoading: mocks.setKanbanMultiLoading,
|
||||
|
||||
@@ -9,6 +9,8 @@ const mockFetchWorkflowSnapshot = vi.fn();
|
||||
type Workflow = { id: string; workspaceId: string; name: string };
|
||||
type MockState = {
|
||||
connection: { status: string };
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
workflows: { items: Workflow[] };
|
||||
kanbanMulti: { snapshots: Record<string, unknown>; isLoading: boolean };
|
||||
clearKanbanMulti: typeof mockClearKanbanMulti;
|
||||
@@ -18,6 +20,8 @@ type MockState = {
|
||||
|
||||
let mockState: MockState = {
|
||||
connection: { status: "connected" },
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
workflows: { items: [] },
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
clearKanbanMulti: mockClearKanbanMulti,
|
||||
@@ -41,6 +45,8 @@ function resetMocks(workflows: Workflow[] = []) {
|
||||
mockFetchWorkflowSnapshot.mockResolvedValue({ steps: [], tasks: [] });
|
||||
mockState = {
|
||||
connection: { status: "connected" },
|
||||
workspaces: { activeId: workflows[0]?.workspaceId ?? null },
|
||||
workspaceContextGeneration: 0,
|
||||
workflows: { items: workflows },
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
clearKanbanMulti: mockClearKanbanMulti,
|
||||
@@ -150,7 +156,12 @@ describe("useAllWorkflowSnapshots — fetch guards", () => {
|
||||
// Switch to workspace B before A's fetch resolves. Wait for B's fetch
|
||||
// to settle (positive signal) so the new-gen effect is fully in place.
|
||||
mockFetchWorkflowSnapshot.mockResolvedValueOnce({ steps: [], tasks: [] });
|
||||
mockState.workflows = { items: [{ id: "wf-B", workspaceId: "ws-B", name: "B" }] };
|
||||
mockState = {
|
||||
...mockState,
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
workflows: { items: [{ id: "wf-B", workspaceId: "ws-B", name: "B" }] },
|
||||
};
|
||||
rerender({ workspaceId: "ws-B" });
|
||||
await waitFor(() =>
|
||||
expect(mockSetWorkflowSnapshot).toHaveBeenCalledWith("wf-B", expect.anything()),
|
||||
@@ -165,6 +176,33 @@ describe("useAllWorkflowSnapshots — fetch guards", () => {
|
||||
const writtenIds = mockSetWorkflowSnapshot.mock.calls.map((args) => args[0]);
|
||||
expect(writtenIds).not.toContain("wf-A");
|
||||
});
|
||||
|
||||
it("discards an A snapshot after reset activates B but before rerender", async () => {
|
||||
let resolveA: (value: { steps: []; tasks: [] }) => void = () => {};
|
||||
mockFetchWorkflowSnapshot.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveA = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => useAllWorkflowSnapshots("ws-A"));
|
||||
await waitFor(() =>
|
||||
expect(mockFetchWorkflowSnapshot).toHaveBeenCalledWith("wf-A", expect.anything()),
|
||||
);
|
||||
|
||||
mockState = {
|
||||
...mockState,
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
};
|
||||
resolveA({ steps: [], tasks: [] });
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
|
||||
expect(mockSetWorkflowSnapshot).not.toHaveBeenCalled();
|
||||
expect(mockSetKanbanMultiLoading).not.toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useAllWorkflowSnapshots — snapshot mapping", () => {
|
||||
|
||||
@@ -6,9 +6,11 @@ import type { KanbanState, WorkflowSnapshotData } from "@/lib/state/slices/kanba
|
||||
import type { Task } from "@/lib/types/http";
|
||||
import type { StoreApi } from "zustand";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import { isCurrentWorkspaceContext } from "@/lib/state/workspace-context";
|
||||
|
||||
type KanbanTask = KanbanState["tasks"][number];
|
||||
type Workflow = { id: string; name: string };
|
||||
type WorkspaceContextRequest = { workspaceId: string; generation: number };
|
||||
|
||||
function isBootHydratedSnapshot(snapshot: WorkflowSnapshotData | undefined): boolean {
|
||||
return !!snapshot && snapshot.isPlaceholder !== true;
|
||||
@@ -19,12 +21,18 @@ async function fetchAndWriteSnapshot(
|
||||
store: StoreApi<AppState>,
|
||||
fetchGenRef: MutableRefObject<number>,
|
||||
myGen: number,
|
||||
request: WorkspaceContextRequest,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const snapshotAtFetchStart = store.getState().kanbanMulti.snapshots[wf.id];
|
||||
const taskIdsAtFetchStart = new Set((snapshotAtFetchStart?.tasks ?? []).map((t) => t.id));
|
||||
const snapshot = await fetchWorkflowSnapshot(wf.id, { cache: "no-store" });
|
||||
if (fetchGenRef.current !== myGen) return;
|
||||
if (
|
||||
fetchGenRef.current !== myGen ||
|
||||
!isCurrentWorkspaceContext(store.getState(), request.workspaceId, request.generation)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const steps = snapshot.steps.map((step) => ({
|
||||
id: step.id,
|
||||
@@ -140,12 +148,21 @@ export function useAllWorkflowSnapshots(workspaceId: string | null) {
|
||||
lastFetchedRef.current = key;
|
||||
|
||||
const myGen = fetchGenRef.current;
|
||||
const request = {
|
||||
workspaceId,
|
||||
generation: store.getState().workspaceContextGeneration,
|
||||
};
|
||||
store.getState().setKanbanMultiLoading(true);
|
||||
|
||||
Promise.all(
|
||||
workspaceWorkflows.map((wf) => fetchAndWriteSnapshot(wf, store, fetchGenRef, myGen)),
|
||||
workspaceWorkflows.map((wf) => fetchAndWriteSnapshot(wf, store, fetchGenRef, myGen, request)),
|
||||
).finally(() => {
|
||||
if (fetchGenRef.current !== myGen) return;
|
||||
if (
|
||||
fetchGenRef.current !== myGen ||
|
||||
!isCurrentWorkspaceContext(store.getState(), request.workspaceId, request.generation)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
store.getState().setKanbanMultiLoading(false);
|
||||
});
|
||||
}, [workspaceId, workflows, connectionStatus, store]);
|
||||
|
||||
@@ -9,12 +9,16 @@ type Task = { id: string; title: string };
|
||||
type MockState = {
|
||||
connection: { status: string };
|
||||
kanban: { workflowId: string | null; tasks: Task[]; steps: unknown[]; isLoading?: boolean };
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
hydrate: typeof mockHydrate;
|
||||
};
|
||||
|
||||
let mockState: MockState = {
|
||||
connection: { status: "connected" },
|
||||
kanban: { workflowId: null, tasks: [], steps: [] },
|
||||
workspaces: { activeId: "ws-1" },
|
||||
workspaceContextGeneration: 0,
|
||||
hydrate: mockHydrate,
|
||||
};
|
||||
|
||||
@@ -57,6 +61,8 @@ describe("useTasks — loading and matching", () => {
|
||||
mockState = {
|
||||
connection: { status: "connected" },
|
||||
kanban: { workflowId: null, tasks: [], steps: [], isLoading: false },
|
||||
workspaces: { activeId: "ws-1" },
|
||||
workspaceContextGeneration: 0,
|
||||
hydrate: mockHydrate,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -14,12 +14,16 @@ type MockKanban = {
|
||||
type MockState = {
|
||||
connection: { status: string };
|
||||
kanban: MockKanban;
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
hydrate: typeof mockHydrate;
|
||||
};
|
||||
|
||||
let mockState: MockState = {
|
||||
connection: { status: "connected" },
|
||||
kanban: { workflowId: null, tasks: [], steps: [], isLoading: false },
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
hydrate: mockHydrate,
|
||||
};
|
||||
|
||||
@@ -56,6 +60,8 @@ function resetState(kanban: Partial<MockKanban> = {}) {
|
||||
isLoading: false,
|
||||
...kanban,
|
||||
},
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
hydrate: mockHydrate,
|
||||
};
|
||||
}
|
||||
@@ -143,4 +149,29 @@ describe("useWorkflowSnapshot — kanban.isLoading", () => {
|
||||
expect(mockHydrate).not.toHaveBeenCalled();
|
||||
expect(mockState.kanban.isLoading).toBe(true);
|
||||
});
|
||||
|
||||
it("discards an A snapshot that resolves after reset activates B but before rerender", async () => {
|
||||
let resolveA: (snapshot: { steps: unknown[]; tasks: unknown[] }) => void = () => {};
|
||||
mockFetchWorkflowSnapshot.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveA = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => useWorkflowSnapshot("wf-A"));
|
||||
expect(mockState.kanban.isLoading).toBe(true);
|
||||
|
||||
mockState = {
|
||||
...mockState,
|
||||
kanban: { workflowId: null, steps: [], tasks: [], isLoading: false },
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
};
|
||||
resolveA({ steps: [], tasks: [] });
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
|
||||
expect(mockHydrate).not.toHaveBeenCalled();
|
||||
expect(mockState.kanban.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef } from "react";
|
||||
import { fetchWorkflowSnapshot } from "@/lib/api";
|
||||
import { snapshotToState } from "@/lib/ssr/mapper";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { isCurrentWorkspaceContext } from "@/lib/state/workspace-context";
|
||||
|
||||
export function useWorkflowSnapshot(workflowId: string | null) {
|
||||
const store = useAppStoreApi();
|
||||
@@ -11,7 +12,10 @@ export function useWorkflowSnapshot(workflowId: string | null) {
|
||||
useEffect(() => {
|
||||
if (!workflowId) return;
|
||||
let cancelled = false;
|
||||
const existing = store.getState().kanban;
|
||||
const requestState = store.getState();
|
||||
const requestedWorkspaceId = requestState.workspaces.activeId;
|
||||
const requestedGeneration = requestState.workspaceContextGeneration;
|
||||
const existing = requestState.kanban;
|
||||
if (
|
||||
!skippedInitialHydratedRef.current &&
|
||||
existing.workflowId === workflowId &&
|
||||
@@ -26,17 +30,33 @@ export function useWorkflowSnapshot(workflowId: string | null) {
|
||||
}
|
||||
fetchWorkflowSnapshot(workflowId, { cache: "no-store" })
|
||||
.then((snapshot) => {
|
||||
if (cancelled) return;
|
||||
if (
|
||||
cancelled ||
|
||||
!isCurrentWorkspaceContext(store.getState(), requestedWorkspaceId, requestedGeneration)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
store.getState().hydrate(snapshotToState(snapshot));
|
||||
})
|
||||
.catch((error) => {
|
||||
// Suppress superseded-fetch noise; retry happens on WS reconnect.
|
||||
if (cancelled) return;
|
||||
if (
|
||||
cancelled ||
|
||||
!isCurrentWorkspaceContext(store.getState(), requestedWorkspaceId, requestedGeneration)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
console.warn("[useWorkflowSnapshot] failed to load snapshot:", error);
|
||||
})
|
||||
.finally(() => {
|
||||
// Only clear the flag this effect raised; skip when cancelled or when a concurrent caller owns it.
|
||||
if (cancelled || !setLoading) return;
|
||||
if (
|
||||
cancelled ||
|
||||
!setLoading ||
|
||||
!isCurrentWorkspaceContext(store.getState(), requestedWorkspaceId, requestedGeneration)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
|
||||
});
|
||||
return () => {
|
||||
|
||||
@@ -7,17 +7,20 @@ const mockSetWorkflows = vi.fn();
|
||||
type MockState = {
|
||||
workflows: { items: Array<{ id: string; workspaceId: string; name: string }> };
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
setWorkflows: typeof mockSetWorkflows;
|
||||
};
|
||||
|
||||
let mockState: MockState = {
|
||||
workflows: { items: [] },
|
||||
workspaces: { activeId: null },
|
||||
workspaceContextGeneration: 0,
|
||||
setWorkflows: mockSetWorkflows,
|
||||
};
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (s: MockState) => unknown) => selector(mockState),
|
||||
useAppStoreApi: () => ({ getState: () => mockState }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
@@ -44,11 +47,36 @@ describe("useWorkflows — stale response guard", () => {
|
||||
vi.clearAllMocks();
|
||||
mockState = {
|
||||
workflows: { items: [] },
|
||||
workspaces: { activeId: null },
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
setWorkflows: mockSetWorkflows,
|
||||
};
|
||||
});
|
||||
|
||||
it("discards an A response that resolves after reset activates B but before rerender", async () => {
|
||||
let resolveA: (value: { workflows: ReturnType<typeof makeWorkflow>[] }) => void = () => {};
|
||||
mockState.workspaces.activeId = "ws-A";
|
||||
mockListWorkflows.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveA = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => useWorkflows("ws-A", true));
|
||||
await waitFor(() => expect(mockListWorkflows).toHaveBeenCalledWith("ws-A", expect.anything()));
|
||||
|
||||
mockState = {
|
||||
...mockState,
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
};
|
||||
resolveA({ workflows: [makeWorkflow("wf-A", "ws-A")] });
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
|
||||
expect(mockSetWorkflows).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("discards a stale in-flight response when the workspace switches mid-fetch", async () => {
|
||||
let resolveStale: (v: unknown) => void = () => {};
|
||||
mockListWorkflows.mockImplementationOnce(
|
||||
@@ -65,6 +93,11 @@ describe("useWorkflows — stale response guard", () => {
|
||||
await waitFor(() => expect(mockListWorkflows).toHaveBeenCalledWith("ws-A", expect.anything()));
|
||||
|
||||
// Switch to workspace B before A's fetch resolves; B resolves first.
|
||||
mockState = {
|
||||
...mockState,
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
};
|
||||
mockListWorkflows.mockResolvedValueOnce({ workflows: [makeWorkflow("wf-B", "ws-B")] });
|
||||
rerender({ workspaceId: "ws-B" });
|
||||
await waitFor(() =>
|
||||
@@ -98,6 +131,11 @@ describe("useWorkflows — stale response guard", () => {
|
||||
await waitFor(() => expect(mockListWorkflows).toHaveBeenCalledWith("ws-A", expect.anything()));
|
||||
|
||||
// Switch to workspace B; B resolves with data.
|
||||
mockState = {
|
||||
...mockState,
|
||||
workspaces: { activeId: "ws-B" },
|
||||
workspaceContextGeneration: 1,
|
||||
};
|
||||
mockListWorkflows.mockResolvedValueOnce({ workflows: [makeWorkflow("wf-B", "ws-B")] });
|
||||
rerender({ workspaceId: "ws-B" });
|
||||
await waitFor(() =>
|
||||
@@ -130,6 +168,30 @@ describe("useWorkflows — stale response guard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("useWorkflows — explicit workspace selection", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockState = {
|
||||
workflows: { items: [] },
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
setWorkflows: mockSetWorkflows,
|
||||
};
|
||||
});
|
||||
|
||||
it("loads workflows when the selected workspace is not globally active", async () => {
|
||||
mockListWorkflows.mockResolvedValueOnce({ workflows: [makeWorkflow("wf-B", "ws-B")] });
|
||||
|
||||
renderHook(() => useWorkflows("ws-B", true));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockSetWorkflows).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ id: "wf-B", workspaceId: "ws-B" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useEnsureWorkspaceWorkflows", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -137,6 +199,7 @@ describe("useEnsureWorkspaceWorkflows", () => {
|
||||
mockState = {
|
||||
workflows: { items: [] },
|
||||
workspaces: { activeId: "ws-A" },
|
||||
workspaceContextGeneration: 0,
|
||||
setWorkflows: mockSetWorkflows,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useEffect } from "react";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { listWorkflows } from "@/lib/api";
|
||||
import type { WorkflowsState } from "@/lib/state/slices";
|
||||
import { isCurrentWorkspaceContext } from "@/lib/state/workspace-context";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import type { StoreApi } from "zustand";
|
||||
|
||||
type StoreWorkflow = WorkflowsState["items"][number];
|
||||
type SetWorkflows = (workflows: StoreWorkflow[]) => void;
|
||||
@@ -15,14 +18,23 @@ type SetWorkflows = (workflows: StoreWorkflow[]) => void;
|
||||
function useWorkflowsFetchEffect(
|
||||
workspaceId: string | null,
|
||||
enabled: boolean,
|
||||
requireActiveWorkspace: boolean,
|
||||
setWorkflows: SetWorkflows,
|
||||
store: StoreApi<AppState>,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (!enabled || !workspaceId) return;
|
||||
let cancelled = false;
|
||||
const generation = store.getState().workspaceContextGeneration;
|
||||
listWorkflows(workspaceId, { cache: "no-store", includeHidden: true })
|
||||
.then((response) => {
|
||||
if (cancelled) return;
|
||||
const state = store.getState();
|
||||
const staleWorkspaceContext = requireActiveWorkspace
|
||||
? !isCurrentWorkspaceContext(state, workspaceId, generation)
|
||||
: state.workspaceContextGeneration !== generation;
|
||||
if (cancelled || staleWorkspaceContext) {
|
||||
return;
|
||||
}
|
||||
const mapped = response.workflows.map((workflow) => ({
|
||||
id: workflow.id,
|
||||
workspaceId: workflow.workspace_id,
|
||||
@@ -43,7 +55,7 @@ function useWorkflowsFetchEffect(
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [enabled, setWorkflows, workspaceId]);
|
||||
}, [enabled, requireActiveWorkspace, setWorkflows, store, workspaceId]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,14 +65,16 @@ function useWorkflowsFetchEffect(
|
||||
* collapsed and its children (which consume workflows) are unmounted.
|
||||
*/
|
||||
export function useEnsureWorkspaceWorkflows() {
|
||||
const store = useAppStoreApi();
|
||||
const workspaceId = useAppStore((state) => state.workspaces.activeId);
|
||||
const setWorkflows = useAppStore((state) => state.setWorkflows);
|
||||
useWorkflowsFetchEffect(workspaceId, true, setWorkflows);
|
||||
useWorkflowsFetchEffect(workspaceId, true, true, setWorkflows, store);
|
||||
}
|
||||
|
||||
export function useWorkflows(workspaceId: string | null, enabled = true) {
|
||||
const store = useAppStoreApi();
|
||||
const workflows = useAppStore((state) => state.workflows.items);
|
||||
const setWorkflows = useAppStore((state) => state.setWorkflows);
|
||||
useWorkflowsFetchEffect(workspaceId, enabled, setWorkflows);
|
||||
useWorkflowsFetchEffect(workspaceId, enabled, false, setWorkflows, store);
|
||||
return { workflows };
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createKanbanSlice } from "./kanban-slice";
|
||||
import type { KanbanSlice } from "./types";
|
||||
|
||||
const TASK_ID = "task-1";
|
||||
const WORKFLOW_ID = "workflow-a";
|
||||
const AUTO_SESSION_ID = "session-auto";
|
||||
const PINNED_SESSION_ID = "session-pinned";
|
||||
|
||||
@@ -68,3 +69,60 @@ describe("kanban slice active session selection", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("kanban slice workspace transition", () => {
|
||||
it("clears workflow, board, and active task context before loading another workspace", () => {
|
||||
const store = makeStore();
|
||||
store.setState({
|
||||
kanban: {
|
||||
workflowId: WORKFLOW_ID,
|
||||
steps: [{ id: "step-a", title: "Todo", color: "blue", position: 0 }],
|
||||
tasks: [
|
||||
{
|
||||
id: TASK_ID,
|
||||
workflowStepId: "step-a",
|
||||
title: "Workspace A task",
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
kanbanMulti: {
|
||||
snapshots: {
|
||||
[WORKFLOW_ID]: {
|
||||
workflowId: WORKFLOW_ID,
|
||||
workflowName: "Workflow A",
|
||||
steps: [],
|
||||
tasks: [],
|
||||
},
|
||||
},
|
||||
isLoading: true,
|
||||
},
|
||||
workflows: {
|
||||
items: [{ id: WORKFLOW_ID, workspaceId: "workspace-a", name: "Workflow A" }],
|
||||
activeId: WORKFLOW_ID,
|
||||
},
|
||||
workspaceContextGeneration: 7,
|
||||
tasks: {
|
||||
activeTaskId: TASK_ID,
|
||||
activeSessionId: PINNED_SESSION_ID,
|
||||
pinnedSessionId: PINNED_SESSION_ID,
|
||||
lastSessionByTaskId: { [TASK_ID]: PINNED_SESSION_ID },
|
||||
},
|
||||
});
|
||||
|
||||
store.getState().resetKanbanWorkspaceContext();
|
||||
|
||||
expect(store.getState()).toMatchObject({
|
||||
kanban: { workflowId: null, steps: [], tasks: [] },
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
workflows: { items: [], activeId: null },
|
||||
workspaceContextGeneration: 8,
|
||||
tasks: {
|
||||
activeTaskId: null,
|
||||
activeSessionId: null,
|
||||
pinnedSessionId: null,
|
||||
lastSessionByTaskId: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ export const defaultKanbanState: KanbanSliceState = {
|
||||
kanban: { workflowId: null, steps: [], tasks: [] },
|
||||
kanbanMulti: { snapshots: {}, isLoading: false },
|
||||
workflows: { items: [], activeId: null },
|
||||
workspaceContextGeneration: 0,
|
||||
tasks: {
|
||||
activeTaskId: null,
|
||||
activeSessionId: null,
|
||||
@@ -20,6 +21,12 @@ export const createKanbanSlice: StateCreator<
|
||||
KanbanSlice
|
||||
> = (set) => ({
|
||||
...defaultKanbanState,
|
||||
resetKanbanWorkspaceContext: () =>
|
||||
set((draft) => {
|
||||
const nextGeneration = draft.workspaceContextGeneration + 1;
|
||||
Object.assign(draft, defaultKanbanState);
|
||||
draft.workspaceContextGeneration = nextGeneration;
|
||||
}),
|
||||
setActiveWorkflow: (workflowId) =>
|
||||
set((draft) => {
|
||||
if (draft.workflows.activeId === workflowId) return;
|
||||
|
||||
@@ -148,10 +148,12 @@ export type KanbanSliceState = {
|
||||
kanban: KanbanState;
|
||||
kanbanMulti: KanbanMultiState;
|
||||
workflows: WorkflowsState;
|
||||
workspaceContextGeneration: number;
|
||||
tasks: TaskState;
|
||||
};
|
||||
|
||||
export type KanbanSliceActions = {
|
||||
resetKanbanWorkspaceContext: () => void;
|
||||
setActiveWorkflow: (workflowId: string | null) => void;
|
||||
setWorkflows: (workflows: WorkflowsState["items"]) => void;
|
||||
reorderWorkflowItems: (workflowIds: string[]) => void;
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
createAutomationsSlice,
|
||||
createSystemSlice,
|
||||
createPluginsSlice,
|
||||
defaultKanbanState,
|
||||
defaultWorkspaceState,
|
||||
defaultSettingsState,
|
||||
defaultSessionState,
|
||||
@@ -51,7 +50,6 @@ import {
|
||||
defaultSystemState,
|
||||
defaultPluginsState,
|
||||
type WorkspaceState,
|
||||
type WorkflowsState,
|
||||
type ExecutorsState,
|
||||
type SettingsAgentsState,
|
||||
type AgentDiscoveryState,
|
||||
@@ -84,6 +82,7 @@ import {
|
||||
type LinearSliceActions,
|
||||
type OfficeSliceActions,
|
||||
type PluginsSliceActions,
|
||||
type KanbanSlice,
|
||||
} from "./slices";
|
||||
import type {
|
||||
AvailableCommand,
|
||||
@@ -101,13 +100,7 @@ import type {
|
||||
export type * from "./store-reexports";
|
||||
|
||||
// Combined AppState type
|
||||
export type AppState = {
|
||||
// Kanban slice
|
||||
kanban: (typeof defaultKanbanState)["kanban"];
|
||||
kanbanMulti: (typeof defaultKanbanState)["kanbanMulti"];
|
||||
workflows: (typeof defaultKanbanState)["workflows"];
|
||||
tasks: (typeof defaultKanbanState)["tasks"];
|
||||
|
||||
export type AppState = KanbanSlice & {
|
||||
// Workspace slice
|
||||
workspaces: (typeof defaultWorkspaceState)["workspaces"];
|
||||
repositories: (typeof defaultWorkspaceState)["repositories"];
|
||||
@@ -240,20 +233,6 @@ export type AppState = {
|
||||
hydrate: (state: HydrationState, options?: HydrationOptions) => void;
|
||||
setActiveWorkspace: (workspaceId: string | null) => void;
|
||||
setWorkspaces: (workspaces: WorkspaceState["items"]) => void;
|
||||
setActiveWorkflow: (workflowId: string | null) => void;
|
||||
setWorkflows: (workflows: WorkflowsState["items"]) => void;
|
||||
reorderWorkflowItems: (workflowIds: string[]) => void;
|
||||
setWorkflowSnapshot: (
|
||||
workflowId: string,
|
||||
data: import("./slices/kanban/types").WorkflowSnapshotData,
|
||||
) => void;
|
||||
setKanbanMultiLoading: (loading: boolean) => void;
|
||||
clearKanbanMulti: () => void;
|
||||
updateMultiTask: (
|
||||
workflowId: string,
|
||||
task: import("./slices/kanban/types").KanbanState["tasks"][number],
|
||||
) => void;
|
||||
removeMultiTask: (workflowId: string, taskId: string) => void;
|
||||
setExecutors: (executors: ExecutorsState["items"]) => void;
|
||||
setSettingsAgents: (agents: SettingsAgentsState["items"]) => void;
|
||||
setAgentDiscovery: (agents: AgentDiscoveryState["items"]) => void;
|
||||
@@ -380,10 +359,6 @@ export type AppState = {
|
||||
meta: { hasMore?: boolean; isLoading?: boolean; oldestCursor?: string | null },
|
||||
) => void;
|
||||
setMessagesLoading: (sessionId: string, loading: boolean) => void;
|
||||
setActiveSession: (taskId: string, sessionId: string) => void;
|
||||
setActiveSessionAuto: (taskId: string, sessionId: string) => void;
|
||||
setActiveTask: (taskId: string) => void;
|
||||
clearActiveSession: () => void;
|
||||
setTaskSession: (session: TaskSession) => void;
|
||||
removeTaskSession: (taskId: string, sessionId: string) => void;
|
||||
setTaskSessionsForTask: (taskId: string, sessions: TaskSession[]) => void;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
export type WorkspaceContextState = {
|
||||
workspaces: { activeId: string | null };
|
||||
workspaceContextGeneration: number;
|
||||
};
|
||||
|
||||
export function isCurrentWorkspaceContext(
|
||||
state: WorkspaceContextState,
|
||||
requestedWorkspaceId: string | null,
|
||||
requestedGeneration: number,
|
||||
): boolean {
|
||||
return (
|
||||
state.workspaces.activeId === requestedWorkspaceId &&
|
||||
state.workspaceContextGeneration === requestedGeneration
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user