From 2b16a53d6d2e6795f34ce842ff9e8481bc63d011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= <57680069+zeval@users.noreply.github.com> Date: Thu, 28 May 2026 23:54:42 +0100 Subject: [PATCH] fix: inherit parent workspace for subtasks (UI + MCP) (#1131) * fix(backend): inherit parent workspace for subtasks on all start paths Subtasks with workspace_mode inherit_parent were provisioning a fresh worktree and tasks folder instead of reusing the parent's. Two causes: - propagateInheritedEnvironment ran only in PrepareTaskSession, so the direct start path (startTask, used by MCP auto-start) never bound the child session to the parent's TaskEnvironment. Moved it into prepareSessionForStart so every launch entry point inherits. - The service CreateTask path did not inherit the parent's repositories when none were supplied (the UI omits them expecting inheritance), so the child was repo-less and could not establish/reuse a worktree. Now mirrors the MCP path: inherit RepositoryID + BaseBranch, drop CheckoutBranch. * fix(web): hide executor profile for inherit-parent subtasks When a subtask inherits the parent's materialized workspace, its executor is inherited too, so picking an executor profile is meaningless. Hide the selector under inherit_parent and omit executor_profile_id from the create payload. * fix(backend): fail fast when subtask parent-repo inheritance lookup errors Return the error from inheritParentRepositories instead of swallowing it: a subtask silently created with no repositories would reintroduce the fresh-worktree bug at launch. Also clarified that inheritance applies to any repo-less subtask, matching the MCP path. --- .../orchestrator/handoff_inheritance_test.go | 43 +++++++++ .../internal/orchestrator/task_operations.go | 36 ++++--- .../task/service/service_child_task_test.go | 93 +++++++++++++++++++ .../internal/task/service/service_tasks.go | 46 +++++++++ .../task/new-subtask-form-parts.tsx | 53 +++++++---- .../web/components/task/use-subtask-submit.ts | 5 +- 6 files changed, 247 insertions(+), 29 deletions(-) diff --git a/apps/backend/internal/orchestrator/handoff_inheritance_test.go b/apps/backend/internal/orchestrator/handoff_inheritance_test.go index 0ed53b42f0..b50e57702e 100644 --- a/apps/backend/internal/orchestrator/handoff_inheritance_test.go +++ b/apps/backend/internal/orchestrator/handoff_inheritance_test.go @@ -67,6 +67,49 @@ func TestInheritFromParentEnvironment_FallsBackToGroupEnv(t *testing.T) { } } +// RC1 regression: inherited-environment propagation must run on the direct +// start path (prepareSessionForStart), not only PrepareTaskSession. MCP-created +// subtasks auto-start through startTask, which prepares the session via +// prepareSessionForStart. Without propagation there, an inherit_parent subtask +// would provision a fresh worktree instead of reusing the parent's. +func TestPrepareSessionForStart_PropagatesInheritedEnvironment(t *testing.T) { + repo := setupTestRepo(t) + svc := createTestServiceWithScheduler(repo, newMockStepGetter(), newMockTaskRepo(), &mockAgentManager{repoForExecutionLookup: repo}) + ctx := context.Background() + now := time.Now().UTC() + + ws := &models.Workspace{ID: "ws1", Name: "WS", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkspace(ctx, ws) + wf := &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkflow(ctx, wf) + parent := &models.Task{ID: "parent", WorkspaceID: "ws1", WorkflowID: "wf1", Title: "P", State: v1.TaskStateInProgress, CreatedAt: now, UpdatedAt: now} + _ = repo.CreateTask(ctx, parent) + child := &models.Task{ID: "child", ParentID: "parent", WorkspaceID: "ws1", WorkflowID: "wf1", Title: "C", State: v1.TaskStateInProgress, CreatedAt: now, UpdatedAt: now} + _ = repo.CreateTask(ctx, child) + _ = repo.CreateTaskSession(ctx, &models.TaskSession{ + ID: "ps1", TaskID: "parent", State: models.TaskSessionStateRunning, + IsPrimary: true, TaskEnvironmentID: "env-parent", StartedAt: now, UpdatedAt: now, + }) + + childTask := &v1.Task{ + ID: "child", + ParentID: "parent", + Metadata: map[string]interface{}{"workspace": map[string]interface{}{"mode": "inherit_parent"}}, + } + sessionID, err := svc.prepareSessionForStart(ctx, childTask, "profile-1", "exec-1", "", "") + if err != nil { + t.Fatalf("prepareSessionForStart: %v", err) + } + + got, err := repo.GetTaskSession(ctx, sessionID) + if err != nil || got == nil { + t.Fatalf("get session: %v", err) + } + if got.TaskEnvironmentID != "env-parent" { + t.Errorf("TaskEnvironmentID = %q, want env-parent (inherited via start path)", got.TaskEnvironmentID) + } +} + // When the parent has a primary session with an env, that takes // precedence over the group fallback. func TestInheritFromParentEnvironment_ParentSessionWins(t *testing.T) { diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index b9638aa61a..995274b9d8 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -183,6 +183,8 @@ func (s *Service) PrepareTaskSession(ctx context.Context, taskID string, agentPr // Create session entry in database. Office tasks route through // EnsureSessionForAgent so runs + advanced-mode reuse one row. + // prepareSessionForStart also propagates any inherited workspace + // environment (inherit_parent / shared_group) onto the new session. sessionID, err := s.prepareSessionForStart(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) if err != nil { s.logger.Error("failed to prepare session", @@ -191,15 +193,6 @@ func (s *Service) PrepareTaskSession(ctx context.Context, taskID string, agentPr return "", err } - // Office task-handoffs phase 4: when this task's workspace policy says - // inherit_parent, propagate the parent task's primary-session - // TaskEnvironmentID to the new session so executor lookup binds to the - // existing materialized environment instead of provisioning a fresh one. - // shared_group is handled the same way once the group has been - // materialized by an earlier launch — we look up the group's - // MaterializedEnvironmentID via the same propagation hook. - s.propagateInheritedEnvironment(ctx, task, sessionID) - // Notify the frontend that a new CREATED session exists. The start path // transitions through updateTaskSessionState which broadcasts; the prepare // path writes the row directly, so without this the per-task session list @@ -643,11 +636,32 @@ func (s *Service) isOfficeTask(ctx context.Context, taskID string) bool { return err == nil && dbTask != nil && dbTask.AssigneeAgentProfileID != "" } -// prepareSessionForStart picks the right session-creation path for the task: +// prepareSessionForStart creates the session for a launch and propagates any +// inherited workspace environment onto it. +// +// The propagation (inherit_parent / shared_group) lives here rather than only +// in PrepareTaskSession so every launch entry point inherits consistently — +// including the direct start path (startTask), which MCP-created subtasks reach +// via auto-start. Without this, an inherit_parent subtask launched through +// startTask would provision a fresh worktree instead of reusing the parent's. +// propagateInheritedEnvironment is a no-op for tasks without a workspace policy. +func (s *Service) prepareSessionForStart( + ctx context.Context, task *v1.Task, + agentProfileID, executorID, executorProfileID, workflowStepID string, +) (string, error) { + sessionID, err := s.createStartSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID) + if err != nil { + return "", err + } + s.propagateInheritedEnvironment(ctx, task, sessionID) + return sessionID, nil +} + +// createStartSession picks the right session-creation path for the task: // office tasks with an assignee use the per-(task, agent) EnsureSessionForAgent // (so runs reuse one row across turns); kanban / quick-chat fall through to // the per-launch PrepareSession used since day one. -func (s *Service) prepareSessionForStart( +func (s *Service) createStartSession( ctx context.Context, task *v1.Task, agentProfileID, executorID, executorProfileID, workflowStepID string, ) (string, error) { diff --git a/apps/backend/internal/task/service/service_child_task_test.go b/apps/backend/internal/task/service/service_child_task_test.go index 0443a6e6e6..f819246e7f 100644 --- a/apps/backend/internal/task/service/service_child_task_test.go +++ b/apps/backend/internal/task/service/service_child_task_test.go @@ -79,6 +79,99 @@ func TestCreateChildTask_OverridesWorkflow(t *testing.T) { } } +func TestCreateTask_Subtask_InheritsParentRepositories(t *testing.T) { + svc, repo := setupOfficeTest(t) + ctx := context.Background() + + if err := repo.CreateRepository(ctx, &models.Repository{ID: "repo-x", WorkspaceID: "ws-1", Name: "Repo"}); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + parent, err := svc.CreateTask(ctx, &CreateTaskRequest{ + WorkspaceID: "ws-1", + Title: "Parent", + ProjectID: "proj-1", + Repositories: []TaskRepositoryInput{{ + RepositoryID: "repo-x", + BaseBranch: "main", + CheckoutBranch: "feature/parent", + }}, + }) + if err != nil { + t.Fatalf("create parent: %v", err) + } + + // Child created without explicit repositories — mirrors the UI inherit_parent + // flow, which omits repositories expecting the backend to inherit them. + child, err := svc.CreateTask(ctx, &CreateTaskRequest{ + WorkspaceID: "ws-1", + Title: "Child", + ParentID: parent.ID, + ProjectID: "proj-1", + }) + if err != nil { + t.Fatalf("create child: %v", err) + } + + childRepos, err := repo.ListTaskRepositories(ctx, child.ID) + if err != nil { + t.Fatalf("ListTaskRepositories: %v", err) + } + if len(childRepos) != 1 { + t.Fatalf("child repos = %d, want 1 inherited from parent", len(childRepos)) + } + if childRepos[0].RepositoryID != "repo-x" { + t.Errorf("repository_id = %q, want repo-x", childRepos[0].RepositoryID) + } + if childRepos[0].BaseBranch != "main" { + t.Errorf("base_branch = %q, want inherited main", childRepos[0].BaseBranch) + } + // CheckoutBranch is dropped: two worktrees can't share a working branch. + if childRepos[0].CheckoutBranch != "" { + t.Errorf("checkout_branch = %q, want empty (dropped on inherit)", childRepos[0].CheckoutBranch) + } +} + +func TestCreateTask_Subtask_ExplicitRepositoriesNotOverridden(t *testing.T) { + svc, repo := setupOfficeTest(t) + ctx := context.Background() + + for _, id := range []string{"repo-a", "repo-b"} { + if err := repo.CreateRepository(ctx, &models.Repository{ID: id, WorkspaceID: "ws-1", Name: id}); err != nil { + t.Fatalf("CreateRepository %s: %v", id, err) + } + } + + parent, err := svc.CreateTask(ctx, &CreateTaskRequest{ + WorkspaceID: "ws-1", + Title: "Parent", + ProjectID: "proj-1", + Repositories: []TaskRepositoryInput{{RepositoryID: "repo-a", BaseBranch: "main"}}, + }) + if err != nil { + t.Fatalf("create parent: %v", err) + } + + child, err := svc.CreateTask(ctx, &CreateTaskRequest{ + WorkspaceID: "ws-1", + Title: "Child", + ParentID: parent.ID, + ProjectID: "proj-1", + Repositories: []TaskRepositoryInput{{RepositoryID: "repo-b", BaseBranch: "dev"}}, + }) + if err != nil { + t.Fatalf("create child: %v", err) + } + + childRepos, err := repo.ListTaskRepositories(ctx, child.ID) + if err != nil { + t.Fatalf("ListTaskRepositories: %v", err) + } + if len(childRepos) != 1 || childRepos[0].RepositoryID != "repo-b" { + t.Fatalf("child repos = %+v, want only explicit repo-b", childRepos) + } +} + func TestCreateChildTask_RequiresParent(t *testing.T) { svc, _ := setupOfficeTest(t) _, err := svc.CreateChildTask(context.Background(), nil, ChildTaskSpec{Title: "X"}) diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index 52257a153f..45db511434 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -54,6 +54,14 @@ func (s *Service) CreateTask(ctx context.Context, req *CreateTaskRequest) (*mode return nil, err } + // Subtasks created without explicit repositories inherit the parent's, so + // an inherit_parent subtask resolves a repo at launch and can reuse the + // parent's worktree (the UI omits repositories expecting this). Mirrors the + // MCP create_task path so UI- and agent-created subtasks behave identically. + if err := s.inheritParentRepositories(ctx, req); err != nil { + return nil, err + } + // For office tasks, resolve workflow from workspace if isOfficeRequest(req) && req.WorkflowID == "" { if err := s.resolveOfficeWorkflow(ctx, req); err != nil { @@ -101,6 +109,44 @@ func (s *Service) CreateTask(ctx context.Context, req *CreateTaskRequest) (*mode return task, nil } +// inheritParentRepositories fills req.Repositories from the parent task when a +// subtask is created without explicit repositories. This applies to any +// repo-less subtask (not only inherit_parent ones), matching the MCP +// create_task path (mcp/handlers.inheritedRepoInputs) so UI- and agent-created +// subtasks behave identically — the UI's new_workspace mode always sends repos, +// so in practice only inherit_parent reaches here empty. RepositoryID and +// BaseBranch carry over; CheckoutBranch is dropped on purpose because two +// worktrees can't share a working branch, so the subtask branches off the same +// base as the parent. +// +// A lookup failure is returned rather than swallowed: a subtask silently +// created with no repositories can't establish a worktree, which would +// reintroduce the exact fresh-worktree bug this inheritance is meant to fix — +// failing fast surfaces the problem at creation time instead. +func (s *Service) inheritParentRepositories(ctx context.Context, req *CreateTaskRequest) error { + if req.ParentID == "" || len(req.Repositories) > 0 { + return nil + } + parentRepos, err := s.taskRepos.ListTaskRepositories(ctx, req.ParentID) + if err != nil { + return fmt.Errorf("list parent repositories for subtask inheritance: %w", err) + } + inherited := make([]TaskRepositoryInput, 0, len(parentRepos)) + for _, r := range parentRepos { + if r == nil || r.RepositoryID == "" { + continue + } + inherited = append(inherited, TaskRepositoryInput{ + RepositoryID: r.RepositoryID, + BaseBranch: r.BaseBranch, + }) + } + if len(inherited) > 0 { + req.Repositories = inherited + } + return nil +} + // validateCreateTaskRequest validates constraints for task creation. func (s *Service) validateCreateTaskRequest(req *CreateTaskRequest) error { isOffice := isOfficeRequest(req) diff --git a/apps/web/components/task/new-subtask-form-parts.tsx b/apps/web/components/task/new-subtask-form-parts.tsx index d1770681f9..3cfa86c0bc 100644 --- a/apps/web/components/task/new-subtask-form-parts.tsx +++ b/apps/web/components/task/new-subtask-form-parts.tsx @@ -45,6 +45,12 @@ type SelectorsRowProps = { onAgentProfileChange: (value: string) => void; onExecutorProfileChange: (value: string) => void; disabled: boolean; + /** + * When true, hide the executor-profile selector. The subtask reuses the + * parent's materialized environment (inherit_parent), so choosing an + * executor would be meaningless — the parent's executor is always used. + */ + hideExecutor: boolean; }; export function SelectorsRow({ @@ -55,10 +61,11 @@ export function SelectorsRow({ onAgentProfileChange, onExecutorProfileChange, disabled, + hideExecutor, }: SelectorsRowProps) { const noAgents = profileOptions.length === 0; return ( -