diff --git a/apps/backend/internal/backendapp/boot_state_routes.go b/apps/backend/internal/backendapp/boot_state_routes.go index 664e509dd0..f39197fc17 100644 --- a/apps/backend/internal/backendapp/boot_state_routes.go +++ b/apps/backend/internal/backendapp/boot_state_routes.go @@ -15,6 +15,7 @@ import ( usermodels "github.com/kandev/kandev/internal/user/models" ) +// tasksPageBootData builds the tasks page boot payload: workspaces, repositories, workflows, steps, tasks, and the user's settings. func (b bootStateBuilder) tasksPageBootData(ctx context.Context, req *http.Request) (map[string]any, map[string]any) { if b.p.taskSvc == nil { return nil, nil @@ -89,6 +90,7 @@ func (b bootStateBuilder) tasksPageBootData(ctx context.Context, req *http.Reque return state, routeData } +// routeContextBootData builds the workspace/route context boot payload (workspaces, active workspace, workflows). func (b bootStateBuilder) routeContextBootData(ctx context.Context, req *http.Request) (map[string]any, map[string]any) { if b.p.taskSvc == nil { return nil, nil @@ -148,6 +150,7 @@ func (b bootStateBuilder) routeContextBootData(ctx context.Context, req *http.Re } } +// workspaceIDSet collects the ids of all workspaces into a set. func workspaceIDSet(workspaces []*taskmodels.Workspace) map[string]bool { result := make(map[string]bool, len(workspaces)) for _, workspace := range workspaces { @@ -158,6 +161,7 @@ func workspaceIDSet(workspaces []*taskmodels.Workspace) map[string]bool { return result } +// workspaceItemStates maps each workspace to its boot state shape. func workspaceItemStates(workspaces []*taskmodels.Workspace) []map[string]any { items := make([]map[string]any, 0, len(workspaces)) for _, workspace := range workspaces { @@ -168,6 +172,7 @@ func workspaceItemStates(workspaces []*taskmodels.Workspace) []map[string]any { return items } +// resolveHomeWorkflowID picks the home workflow: the query param, else the saved settings workflow, else the first valid one. func resolveHomeWorkflowID( workflows []*taskmodels.Workflow, queryWorkflowID string, @@ -183,6 +188,7 @@ func resolveHomeWorkflowID( return firstWorkflowID(workflows) } +// validWorkflowOrEmpty returns the workflow id when it exists in the list, otherwise empty. func validWorkflowOrEmpty(workflows []*taskmodels.Workflow, workflowID string) string { for _, workflow := range workflows { if workflow != nil && workflow.ID == workflowID { @@ -192,6 +198,7 @@ func validWorkflowOrEmpty(workflows []*taskmodels.Workflow, workflowID string) s return "" } +// repositoriesForState loads the workspace repositories for the boot payload, logging and returning empty on failure. func (b bootStateBuilder) repositoriesForState(ctx context.Context, workspaceID string, state map[string]any) []taskdto.RepositoryDTO { repositories, err := b.p.taskSvc.ListRepositories(ctx, workspaceID) if err != nil { @@ -207,6 +214,7 @@ func (b bootStateBuilder) repositoriesForState(ctx context.Context, workspaceID return items } +// repositoriesToDTOs maps repository models to DTOs. func repositoriesToDTOs(repositories []*taskmodels.Repository) []taskdto.RepositoryDTO { items := make([]taskdto.RepositoryDTO, 0, len(repositories)) for _, repository := range repositories { @@ -217,6 +225,7 @@ func repositoriesToDTOs(repositories []*taskmodels.Repository) []taskdto.Reposit return items } +// workflowsToDTOs maps workflow models to DTOs. func workflowsToDTOs(workflows []*taskmodels.Workflow) []taskdto.WorkflowDTO { items := make([]taskdto.WorkflowDTO, 0, len(workflows)) for _, workflow := range workflows { @@ -227,6 +236,7 @@ func workflowsToDTOs(workflows []*taskmodels.Workflow) []taskdto.WorkflowDTO { return items } +// workflowStepsForWorkspace loads the workflow steps for a workspace, returning empty when the service is unavailable. func (b bootStateBuilder) workflowStepsForWorkspace(ctx context.Context, workspaceID string) []taskdto.WorkflowStepDTO { if b.p.services == nil || b.p.services.Workflow == nil { return []taskdto.WorkflowStepDTO{} @@ -245,6 +255,7 @@ func (b bootStateBuilder) workflowStepsForWorkspace(ctx context.Context, workspa return items } +// tasksForWorkspace loads the task page's task list for a workspace/workflow, returning empty on failure. func (b bootStateBuilder) tasksForWorkspace(ctx context.Context, workspaceID, workflowID, repositoryID, sort string) ([]taskdto.TaskDTO, int) { tasks, total, err := b.p.taskSvc.ListTasksByWorkspace(ctx, workspaceID, workflowID, repositoryID, "", 1, 25, sort, false, false, false, false) if err != nil { @@ -254,12 +265,14 @@ func (b bootStateBuilder) tasksForWorkspace(ctx context.Context, workspaceID, wo return b.taskDTOsWithSessionInfo(ctx, tasks), total } +// mergeBootState overlays src key/value pairs onto dst. func mergeBootState(dst map[string]any, src map[string]any) { for key, value := range src { dst[key] = value } } +// addPromptsState merges the prompts listing into the boot state when available. func (b bootStateBuilder) addPromptsState(ctx context.Context, state map[string]any) { if b.p.promptCtrl == nil { return @@ -276,6 +289,7 @@ func (b bootStateBuilder) addPromptsState(ctx context.Context, state map[string] } } +// addEditorsState merges the editors listing into the boot state when available. func (b bootStateBuilder) addEditorsState(ctx context.Context, state map[string]any) { if b.p.editorCtrl == nil { return @@ -292,6 +306,7 @@ func (b bootStateBuilder) addEditorsState(ctx context.Context, state map[string] } } +// addOfficeRouteState merges office route state into the boot state when the office feature is enabled. func (b bootStateBuilder) addOfficeRouteState(ctx context.Context, req *http.Request, state map[string]any) { if !b.p.features.Office || b.p.services == nil || b.p.services.OfficeSvcs == nil { return @@ -321,6 +336,7 @@ func (b bootStateBuilder) addOfficeRouteState(ctx context.Context, req *http.Req state["office"] = b.officeState(ctx, activeID) } +// officeWorkspaces resolves the office workspaces and the active workspace id from the request cookie. func (b bootStateBuilder) officeWorkspaces(ctx context.Context, req *http.Request) ([]taskdto.WorkspaceDTO, string, error) { if b.p.taskSvc == nil { return nil, "", nil @@ -344,6 +360,7 @@ func (b bootStateBuilder) officeWorkspaces(ctx context.Context, req *http.Reques return items, resolveActiveOfficeWorkspaceID(officeItems, readActiveWorkspaceCookie(req)), nil } +// officeState assembles the office boot state (agents, projects, inbox, dashboard) for the active workspace. func (b bootStateBuilder) officeState(ctx context.Context, activeID string) map[string]any { agents := b.officeAgents(ctx, activeID) projects := b.officeProjects(ctx, activeID) @@ -382,6 +399,7 @@ func (b bootStateBuilder) officeState(ctx context.Context, activeID string) map[ } } +// officeAgents loads the office agent list for a workspace, returning empty when unavailable. func (b bootStateBuilder) officeAgents(ctx context.Context, activeID string) any { if activeID == "" || b.p.services.OfficeSvcs.Agents == nil { return []any{} @@ -394,6 +412,7 @@ func (b bootStateBuilder) officeAgents(ctx context.Context, activeID string) any return result } +// officeProjects loads the office project list with counts, returning empty when unavailable. func (b bootStateBuilder) officeProjects(ctx context.Context, activeID string) any { if activeID == "" || b.p.services.OfficeSvcs.Projects == nil { return []any{} @@ -406,6 +425,7 @@ func (b bootStateBuilder) officeProjects(ctx context.Context, activeID string) a return result } +// officeInbox loads the office inbox items and count, returning empty when unavailable. func (b bootStateBuilder) officeInbox(ctx context.Context, activeID string) (any, int) { if activeID == "" || b.p.services.OfficeSvcs.Dashboard == nil { return []any{}, 0 @@ -418,6 +438,7 @@ func (b bootStateBuilder) officeInbox(ctx context.Context, activeID string) (any return result, len(result) } +// officeDashboard loads the office dashboard data, returning nil when unavailable. func (b bootStateBuilder) officeDashboard(ctx context.Context, activeID string) any { if activeID == "" || b.p.services.OfficeSvcs.Dashboard == nil { return nil @@ -435,6 +456,7 @@ func (b bootStateBuilder) officeDashboard(ctx context.Context, activeID string) return officedashboard.NewDashboardResponse(data, summaries) } +// mapUserSettingsState converts a user settings response to the SPA boot shape, preferring the given workspace id. func mapUserSettingsState(response userdto.UserSettingsResponse, workspaceID string) map[string]any { settings := response.Settings effectiveWorkspaceID := nullString(settings.WorkspaceID) @@ -458,6 +480,7 @@ func mapUserSettingsState(response userdto.UserSettingsResponse, workspaceID str "chatSubmitKey": defaultString(settings.ChatSubmitKey, "cmd_enter"), "reviewAutoMarkOnScroll": settings.ReviewAutoMarkOnScroll, "confirmTaskArchive": settings.ConfirmTaskArchive, + "preventAutoStartAgentOnOpen": settings.PreventAutoStartAgentOnOpen, "unreadDivider": settings.UnreadDivider, "agentGeneratedTaskTitles": settings.AgentGeneratedTaskTitles, "mcpTaskAgentProfileDefault": usermodels.NormalizeMCPTaskAgentProfileDefault(settings.MCPTaskAgentProfileDefault), @@ -500,12 +523,14 @@ func mapUserSettingsState(response userdto.UserSettingsResponse, workspaceID str } } +// mapUserSettingsStateWithWorkflow adds the resolved workflow id onto the settings boot shape. func mapUserSettingsStateWithWorkflow(response userdto.UserSettingsResponse, workspaceID, workflowID string) map[string]any { state := mapUserSettingsState(response, workspaceID) state["workflowId"] = nullString(workflowID) return state } +// mapWorkspaceItemState maps a workspace DTO to its SPA boot shape. func mapWorkspaceItemState(workspace taskdto.WorkspaceDTO) map[string]any { return map[string]any{ "id": workspace.ID, @@ -522,6 +547,7 @@ func mapWorkspaceItemState(workspace taskdto.WorkspaceDTO) map[string]any { } } +// mapWorkflowItemState maps a workflow DTO to its SPA boot shape. func mapWorkflowItemState(workflow taskdto.WorkflowDTO) map[string]any { return map[string]any{ "id": workflow.ID, @@ -535,6 +561,7 @@ func mapWorkflowItemState(workflow taskdto.WorkflowDTO) map[string]any { } } +// mapKanbanStepState maps a workflow step DTO to the kanban step boot shape. func mapKanbanStepState(step taskdto.WorkflowStepDTO) map[string]any { return map[string]any{ "id": step.ID, @@ -551,6 +578,7 @@ func mapKanbanStepState(step taskdto.WorkflowStepDTO) map[string]any { } } +// mapKanbanTaskState maps a task DTO to the kanban task boot shape. func mapKanbanTaskState(task taskdto.TaskDTO) map[string]any { repositories := make([]map[string]any, 0, len(task.Repositories)) var primaryRepositoryID any @@ -589,6 +617,7 @@ func mapKanbanTaskState(task taskdto.TaskDTO) map[string]any { } } +// mapSidebarViews maps sidebar views to the SPA boot shape. func mapSidebarViews(views []usermodels.SidebarView) []map[string]any { if len(views) == 0 { return []map[string]any{} @@ -607,6 +636,7 @@ func mapSidebarViews(views []usermodels.SidebarView) []map[string]any { return result } +// mapSidebarDraft maps the sidebar draft (nil-safe) to the boot shape. func mapSidebarDraft(draft *usermodels.SidebarViewDraft) map[string]any { if draft == nil { return nil @@ -619,6 +649,7 @@ func mapSidebarDraft(draft *usermodels.SidebarViewDraft) map[string]any { } } +// mapSidebarTaskPrefs maps sidebar task prefs to the boot shape. func mapSidebarTaskPrefs(prefs usermodels.SidebarTaskPrefs) map[string]any { return map[string]any{ "pinnedTaskIds": stringSlice(prefs.PinnedTaskIDs), @@ -627,6 +658,7 @@ func mapSidebarTaskPrefs(prefs usermodels.SidebarTaskPrefs) map[string]any { } } +// mapAppStatusBarOrder maps the status bar order to the boot shape. func mapAppStatusBarOrder(order usermodels.AppStatusBarOrder) map[string]any { return map[string]any{ "leftItemIds": stringSlice(order.LeftItemIDs), @@ -634,6 +666,7 @@ func mapAppStatusBarOrder(order usermodels.AppStatusBarOrder) map[string]any { } } +// mapTaskCreateLastUsed maps the last task-creation choices to the boot shape. func mapTaskCreateLastUsed(value usermodels.TaskCreateLastUsed) map[string]any { workflowIDsByWorkspace := value.WorkflowIDsByWorkspace if workflowIDsByWorkspace == nil { @@ -650,6 +683,7 @@ func mapTaskCreateLastUsed(value usermodels.TaskCreateLastUsed) map[string]any { } } +// mapVoiceMode maps the voice mode settings to the boot shape with defaults. func mapVoiceMode(value usermodels.VoiceModeSettings) map[string]any { return map[string]any{ "enabled": value.Enabled, @@ -661,6 +695,7 @@ func mapVoiceMode(value usermodels.VoiceModeSettings) map[string]any { } } +// resolveActiveOfficeWorkspaceID returns the cookie workspace id when it is valid, otherwise the first workspace id. func resolveActiveOfficeWorkspaceID(workspaces []taskdto.WorkspaceDTO, cookieWorkspaceID string) string { for _, workspace := range workspaces { if workspace.ID == cookieWorkspaceID { @@ -673,6 +708,7 @@ func resolveActiveOfficeWorkspaceID(workspaces []taskdto.WorkspaceDTO, cookieWor return "" } +// firstValidID returns the first non-empty candidate present in the valid set. func firstValidID(valid map[string]bool, candidates ...string) string { for _, candidate := range candidates { value := strings.TrimSpace(candidate) @@ -683,6 +719,7 @@ func firstValidID(valid map[string]bool, candidates ...string) string { return "" } +// firstWorkspaceID returns the first workspace id in the list. func firstWorkspaceID(workspaces []*taskmodels.Workspace) string { for _, workspace := range workspaces { if workspace != nil && workspace.ID != "" { @@ -692,6 +729,7 @@ func firstWorkspaceID(workspaces []*taskmodels.Workspace) string { return "" } +// firstWorkflowID returns the first workflow id in the list. func firstWorkflowID(workflows []*taskmodels.Workflow) string { for _, workflow := range workflows { if workflow != nil && workflow.ID != "" { @@ -701,6 +739,7 @@ func firstWorkflowID(workflows []*taskmodels.Workflow) string { return "" } +// queryValue reads a trimmed query parameter, returning empty when absent. func queryValue(req *http.Request, name string) string { if req == nil || req.URL == nil { return "" @@ -719,6 +758,7 @@ func queryValue(req *http.Request, name string) string { return strings.TrimSpace(parsed.Query().Get(name)) } +// tasksListSortForRoute prefers a valid query sort, falling back to the saved settings value. func tasksListSortForRoute(queryValue, settingsValue string) string { if usermodels.IsValidTasksListSort(queryValue) { return strings.TrimSpace(queryValue) @@ -726,6 +766,7 @@ func tasksListSortForRoute(queryValue, settingsValue string) string { return usermodels.NormalizeTasksListSort(settingsValue) } +// tasksListGroupForRoute prefers a valid query group, falling back to the saved settings value. func tasksListGroupForRoute(queryValue, settingsValue string) string { if usermodels.IsValidTasksListGroup(queryValue) { return strings.TrimSpace(queryValue) @@ -733,6 +774,7 @@ func tasksListGroupForRoute(queryValue, settingsValue string) string { return usermodels.NormalizeTasksListGroup(settingsValue) } +// readActiveWorkspaceCookie reads the active workspace id from the cookies. func readActiveWorkspaceCookie(req *http.Request) string { if req == nil { return "" @@ -748,6 +790,7 @@ func readActiveWorkspaceCookie(req *http.Request) string { return "" } +// nullString returns nil for an empty string (JSON null). func nullString(value string) any { if value == "" { return nil @@ -755,6 +798,7 @@ func nullString(value string) any { return value } +// nullInt returns nil for a zero int (JSON null). func nullInt(value int) any { if value == 0 { return nil @@ -762,6 +806,7 @@ func nullInt(value int) any { return value } +// stringSlice returns an empty slice instead of nil. func stringSlice(value []string) []string { if value == nil { return []string{} @@ -769,6 +814,7 @@ func stringSlice(value []string) []string { return value } +// stringSliceMap returns an empty map instead of nil. func stringSliceMap(value map[string][]string) map[string][]string { if value == nil { return map[string][]string{} @@ -776,6 +822,7 @@ func stringSliceMap(value map[string][]string) map[string][]string { return value } +// mapStringAny returns an empty map instead of nil. func mapStringAny(value map[string]any) map[string]any { if value == nil { return map[string]any{} @@ -783,6 +830,7 @@ func mapStringAny(value map[string]any) map[string]any { return value } +// mapStringMap returns an empty map instead of nil. func mapStringMap(value map[string]map[string]any) map[string]map[string]any { if value == nil { return map[string]map[string]any{} @@ -790,6 +838,7 @@ func mapStringMap(value map[string]map[string]any) map[string]map[string]any { return value } +// defaultString returns the fallback when the value is empty. func defaultString(value, fallback string) string { if value == "" { return fallback @@ -797,6 +846,7 @@ func defaultString(value, fallback string) string { return value } +// terminalLinkBehavior normalizes the terminal link behavior to new_tab or browser_panel. func terminalLinkBehavior(value string) string { if value == "browser_panel" { return "browser_panel" @@ -804,6 +854,7 @@ func terminalLinkBehavior(value string) string { return "new_tab" } +// changesPanelLayout normalizes the changes panel layout to flat or tree. func changesPanelLayout(value string) string { if value == "flat" { return "flat" @@ -811,6 +862,7 @@ func changesPanelLayout(value string) string { return "tree" } +// logBootError logs a debug entry when optional boot data failed to load. func (b bootStateBuilder) logBootError(operation string, err error) { if err == nil || b.p.log == nil { return diff --git a/apps/backend/internal/orchestrator/handlers/handlers.go b/apps/backend/internal/orchestrator/handlers/handlers.go index bc737629f5..f3f1d4656e 100644 --- a/apps/backend/internal/orchestrator/handlers/handlers.go +++ b/apps/backend/internal/orchestrator/handlers/handlers.go @@ -60,6 +60,7 @@ func (h *Handlers) wsGetStatus(ctx context.Context, msg *ws.Message) (*ws.Messag return ws.NewResponse(msg.ID, msg.Action, resp) } +// wsGetQueue returns the queue of tasks waiting for an agent. func (h *Handlers) wsGetQueue(ctx context.Context, msg *ws.Message) (*ws.Message, error) { queuedTasks := h.service.GetQueuedTasks() tasks := make([]dto.QueuedTaskDTO, 0, len(queuedTasks)) @@ -77,6 +78,7 @@ func (h *Handlers) wsGetQueue(ctx context.Context, msg *ws.Message) (*ws.Message return ws.NewResponse(msg.ID, msg.Action, resp) } +// wsLaunchSession starts or resumes a task's agent session. func (h *Handlers) wsLaunchSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req orchestrator.LaunchSessionRequest if err := msg.ParsePayload(&req); err != nil { @@ -109,9 +111,11 @@ func (h *Handlers) wsLaunchSession(ctx context.Context, msg *ws.Message) (*ws.Me } type wsEnsureSessionRequest struct { - TaskID string `json:"task_id"` + TaskID string `json:"task_id"` + AutoStart *bool `json:"auto_start,omitempty"` } +// wsEnsureSession ensures a task has a session, honoring the auto_start override. func (h *Handlers) wsEnsureSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsEnsureSessionRequest if err := msg.ParsePayload(&req); err != nil { @@ -121,7 +125,7 @@ func (h *Handlers) wsEnsureSession(ctx context.Context, msg *ws.Message) (*ws.Me return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) } - resp, err := h.service.EnsureSession(ctx, req.TaskID) + resp, err := h.service.EnsureSession(ctx, req.TaskID, orchestrator.EnsureSessionOptions{AutoStart: req.AutoStart}) if err != nil { h.logger.Error("failed to ensure session", zap.String("task_id", req.TaskID), @@ -141,6 +145,7 @@ type wsResetContextRequest struct { SessionID string `json:"session_id"` } +// wsResetContext clears the session's agent context window. func (h *Handlers) wsResetContext(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsResetContextRequest if err := msg.ParsePayload(&req); err != nil { @@ -167,6 +172,7 @@ type wsSetPlanModeRequest struct { Enabled bool `json:"enabled"` } +// wsSetPlanMode toggles plan mode for a session. func (h *Handlers) wsSetPlanMode(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsSetPlanModeRequest if err := msg.ParsePayload(&req); err != nil { @@ -196,6 +202,7 @@ type wsRecoverSessionRequest struct { Action string `json:"action"` // "resume", "fresh_start", or "cancel_retry" } +// wsRecoverSession recovers a session by id (resume or fresh start). func (h *Handlers) wsRecoverSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsRecoverSessionRequest if err := msg.ParsePayload(&req); err != nil { @@ -237,6 +244,7 @@ type wsStopTaskRequest struct { Force bool `json:"force,omitempty"` } +// wsStopTask stops the agent running for a task. func (h *Handlers) wsStopTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsStopTaskRequest if err := msg.ParsePayload(&req); err != nil { @@ -268,6 +276,7 @@ type wsPermissionRespondRequest struct { Rejected bool `json:"rejected,omitempty"` } +// wsRespondToPermission forwards the user's permission decision. func (h *Handlers) wsRespondToPermission(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsPermissionRespondRequest if err := msg.ParsePayload(&req); err != nil { @@ -330,6 +339,7 @@ func (h *Handlers) wsCheckSessionAssociation( return ws.NewResponse(msg.ID, msg.Action, map[string]bool{"found": found}) } +// wsCheckSessionPR refreshes the PR association for a session. func (h *Handlers) wsCheckSessionPR(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsCheckSessionAssociationRequest if err := msg.ParsePayload(&req); err != nil { @@ -338,6 +348,7 @@ func (h *Handlers) wsCheckSessionPR(ctx context.Context, msg *ws.Message) (*ws.M return h.wsCheckSessionAssociation(ctx, msg, req, h.service.CheckSessionPR, "session PR") } +// wsCheckSessionMR refreshes the MR association for a session. func (h *Handlers) wsCheckSessionMR(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsCheckSessionAssociationRequest if err := msg.ParsePayload(&req); err != nil { @@ -351,6 +362,7 @@ type wsGetTaskSessionStatusRequest struct { TaskSessionID string `json:"session_id"` } +// wsGetTaskSessionStatus returns a task session's detailed status. func (h *Handlers) wsGetTaskSessionStatus(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsGetTaskSessionStatusRequest if err := msg.ParsePayload(&req); err != nil { @@ -382,6 +394,7 @@ type wsSessionActionRequest struct { Force bool `json:"force,omitempty"` } +// parseSessionAction parses a session-scoped action request, returning an error message on failure. func (h *Handlers) parseSessionAction(msg *ws.Message) (*wsSessionActionRequest, *ws.Message) { var req wsSessionActionRequest if err := msg.ParsePayload(&req); err != nil { @@ -395,6 +408,7 @@ func (h *Handlers) parseSessionAction(msg *ws.Message) (*wsSessionActionRequest, return &req, nil } +// wsStopSession stops a session's agent. func (h *Handlers) wsStopSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { req, errResp := h.parseSessionAction(msg) if errResp != nil { @@ -411,6 +425,7 @@ func (h *Handlers) wsStopSession(ctx context.Context, msg *ws.Message) (*ws.Mess return ws.NewResponse(msg.ID, msg.Action, dto.SuccessResponse{Success: true}) } +// wsDeleteSession deletes a session. func (h *Handlers) wsDeleteSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { req, errResp := h.parseSessionAction(msg) if errResp != nil { @@ -423,6 +438,7 @@ func (h *Handlers) wsDeleteSession(ctx context.Context, msg *ws.Message) (*ws.Me return ws.NewResponse(msg.ID, msg.Action, dto.SuccessResponse{Success: true}) } +// wsSetPrimarySession marks a session as the task's primary session. func (h *Handlers) wsSetPrimarySession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { req, errResp := h.parseSessionAction(msg) if errResp != nil { @@ -440,6 +456,7 @@ type wsRenameSessionRequest struct { Name string `json:"name"` } +// wsRenameSession renames a session. func (h *Handlers) wsRenameSession(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsRenameSessionRequest if err := msg.ParsePayload(&req); err != nil { @@ -459,6 +476,7 @@ type wsCancelAgentRequest struct { SessionID string `json:"session_id"` } +// wsCancelAgent cancels the in-flight agent turn. func (h *Handlers) wsCancelAgent(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req wsCancelAgentRequest if err := msg.ParsePayload(&req); err != nil { diff --git a/apps/backend/internal/orchestrator/handlers/handlers_test.go b/apps/backend/internal/orchestrator/handlers/handlers_test.go index a9805839dd..e287dfc9fb 100644 --- a/apps/backend/internal/orchestrator/handlers/handlers_test.go +++ b/apps/backend/internal/orchestrator/handlers/handlers_test.go @@ -37,3 +37,30 @@ func TestWsRecoverSessionCancelRetryReportsServiceResult(t *testing.T) { require.NoError(t, json.Unmarshal(response.Payload, &payload)) require.False(t, payload.Cancelled) } + +func TestWsEnsureSessionRequestParsesAutoStartOverride(t *testing.T) { + tests := []struct { + name string + payload map[string]interface{} + wantSet bool + wantValue bool + }{ + {name: "absent auto_start stays nil", payload: map[string]interface{}{"task_id": "t1"}, wantSet: false}, + {name: "auto_start false parses", payload: map[string]interface{}{"task_id": "t1", "auto_start": false}, wantSet: true, wantValue: false}, + {name: "auto_start true parses", payload: map[string]interface{}{"task_id": "t1", "auto_start": true}, wantSet: true, wantValue: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + msg := createTestMessage(t, ws.ActionSessionEnsure, tt.payload) + var req wsEnsureSessionRequest + require.NoError(t, msg.ParsePayload(&req)) + if tt.wantSet { + require.NotNil(t, req.AutoStart, "auto_start should be set") + require.Equal(t, tt.wantValue, *req.AutoStart) + } else { + require.Nil(t, req.AutoStart, "auto_start should be absent") + } + }) + } +} diff --git a/apps/backend/internal/orchestrator/session_ensure.go b/apps/backend/internal/orchestrator/session_ensure.go index b09bc6e0cc..2ed7694655 100644 --- a/apps/backend/internal/orchestrator/session_ensure.go +++ b/apps/backend/internal/orchestrator/session_ensure.go @@ -28,6 +28,13 @@ type EnsureSessionOptions struct { // but the agent process (agentctl) is not running. Used by office advanced // mode to bring up file/terminal/changes panels. EnsureExecution bool + // AutoStart overrides the workflow-step auto-start decision. When + // explicitly false, the session is created workspace-only (prepare, + // CREATED) even when the step's on-enter has auto_start_agent, and the + // launch is marked NoAgentLaunch so passthrough profiles are never + // upgraded into an agent start. Absent (nil) keeps the step-derived + // decision. + AutoStart *bool } // ensureLocks serializes EnsureSession calls per task id so concurrent callers @@ -38,6 +45,8 @@ type EnsureSessionOptions struct { // Growth is bounded by the number of distinct task IDs (~160 B per entry). var ensureLocks sync.Map // map[taskID]*sync.Mutex +// acquireEnsureLock serializes concurrent EnsureSession calls per task, +// returning an unlock function. func acquireEnsureLock(taskID string) func() { v, _ := ensureLocks.LoadOrStore(taskID, &sync.Mutex{}) mu := v.(*sync.Mutex) @@ -85,6 +94,9 @@ func (s *Service) EnsureSession(ctx context.Context, taskID string, opts ...Ensu agentProfileID, step := s.resolveTaskAgentProfile(ctx, task) autoStart := stepAllowsAutoStart(step) + if o.AutoStart != nil { + autoStart = *o.AutoStart + } intent := IntentPrepare source := "created_prepare" @@ -100,6 +112,7 @@ func (s *Service) EnsureSession(ctx context.Context, taskID string, opts ...Ensu WorkflowStepID: task.WorkflowStepID, LaunchWorkspace: true, AutoStart: intent == IntentStart, + NoAgentLaunch: o.AutoStart != nil && !*o.AutoStart, }) if err != nil { return nil, err @@ -191,6 +204,8 @@ func WithViewerAgent(ctx context.Context, agentInstanceID string) context.Contex return context.WithValue(ctx, viewerAgentContextKey, agentInstanceID) } +// existingResponse builds an ensure response for a pre-existing session, +// attaching the task's workspace path when the session row lacks one. func (s *Service) existingResponse(ctx context.Context, taskID string, sess *models.TaskSession, source string) *EnsureSessionResponse { resp := &EnsureSessionResponse{ Success: true, @@ -251,6 +266,8 @@ func (s *Service) resolveTaskAgentProfile(ctx context.Context, task *models.Task return "", step } +// lookupWorkflowStep loads a workflow step by id, returning nil when the id +// is empty, the getter is unavailable, or the lookup fails. func (s *Service) lookupWorkflowStep(ctx context.Context, stepID string) *wfmodels.WorkflowStep { if stepID == "" || s.workflowStepGetter == nil { return nil diff --git a/apps/backend/internal/orchestrator/session_ensure_test.go b/apps/backend/internal/orchestrator/session_ensure_test.go index 94840e1b21..3a2c8ad000 100644 --- a/apps/backend/internal/orchestrator/session_ensure_test.go +++ b/apps/backend/internal/orchestrator/session_ensure_test.go @@ -527,3 +527,152 @@ func TestResolveTaskAgentProfile_StepThenWorkflowThenWorkspace(t *testing.T) { } }) } + +func TestEnsureSession_AutoStartFalsePreparesInsteadOfStarting(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + now := time.Now().UTC() + stepGetter := newMockStepGetter() + stepGetter.steps["step-start"] = &wfmodels.WorkflowStep{ + ID: "step-start", + Events: wfmodels.StepEvents{ + OnEnter: []wfmodels.OnEnterAction{{Type: wfmodels.OnEnterAutoStartAgent}}, + }, + } + agentMgr := &mockAgentManager{ + launchAgentFunc: func(_ context.Context, _ *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + return &executor.LaunchAgentResponse{AgentExecutionID: "exec-1"}, nil + }, + } + taskRepo := newMockTaskRepo() + svc := createTestServiceWithScheduler(repo, stepGetter, taskRepo, agentMgr) + + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "Test Workflow", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + + seedTask := func(taskID string) { + if err := repo.CreateTask(ctx, &models.Task{ID: taskID, WorkflowID: "wf1", WorkspaceID: "ws1", WorkflowStepID: "step-start", Title: "T", Metadata: map[string]interface{}{"agent_profile_id": "profile1"}, CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed task %s: %v", taskID, err) + } + taskRepo.tasks[taskID] = &v1.Task{ + ID: taskID, + WorkspaceID: "ws1", + Metadata: map[string]any{"agent_profile_id": "profile1"}, + } + } + + t.Run("control: no override starts on an auto-start step", func(t *testing.T) { + seedTask("task-start") + resp, err := svc.EnsureSession(ctx, "task-start") + if err != nil { + t.Fatalf("ensure session: %v", err) + } + if resp.Source != "created_start" { + t.Fatalf("Source = %q, want created_start", resp.Source) + } + }) + + t.Run("auto_start false prepares instead of starting", func(t *testing.T) { + seedTask("task-prepare") + falseVal := false + resp, err := svc.EnsureSession(ctx, "task-prepare", EnsureSessionOptions{AutoStart: &falseVal}) + if err != nil { + t.Fatalf("ensure session: %v", err) + } + if resp.Source != "created_prepare" { + t.Fatalf("Source = %q, want created_prepare", resp.Source) + } + if resp.State != string(models.TaskSessionStateCreated) { + t.Fatalf("State = %q, want %q", resp.State, models.TaskSessionStateCreated) + } + }) +} + +func TestEnsureSession_AutoStartFalseNeverUpgradesPassthrough(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + now := time.Now().UTC() + stepGetter := newMockStepGetter() + // A step WITHOUT auto_start_agent forces the prepare path, where the + // passthrough upgrade would otherwise fire. + stepGetter.steps["step-plain"] = &wfmodels.WorkflowStep{ID: "step-plain"} + stepGetter.steps["step-start"] = &wfmodels.WorkflowStep{ + ID: "step-start", + Events: wfmodels.StepEvents{ + OnEnter: []wfmodels.OnEnterAction{{Type: wfmodels.OnEnterAutoStartAgent}}, + }, + } + taskRepo := newMockTaskRepo() + agentMgr := &mockAgentManager{ + isPassthrough: true, + launchAgentFunc: func(_ context.Context, _ *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + return &executor.LaunchAgentResponse{AgentExecutionID: "exec-1"}, nil + }, + } + svc := createTestServiceWithScheduler(repo, stepGetter, taskRepo, agentMgr) + + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "Test Workflow", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed workflow: %v", err) + } + + seedPassthroughTask := func(taskID, stepID string) { + if err := repo.CreateTask(ctx, &models.Task{ID: taskID, WorkflowID: "wf1", WorkspaceID: "ws1", WorkflowStepID: stepID, Title: "T", Metadata: map[string]interface{}{"agent_profile_id": "passthrough-profile"}, CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("seed task %s: %v", taskID, err) + } + taskRepo.tasks[taskID] = &v1.Task{ + ID: taskID, + WorkspaceID: "ws1", + Metadata: map[string]any{"agent_profile_id": "passthrough-profile"}, + } + } + + t.Run("passthrough prepare without override still upgrades (existing behavior)", func(t *testing.T) { + seedPassthroughTask("ptask-upgrade", "step-plain") + resp, err := svc.EnsureSession(ctx, "ptask-upgrade") + if err != nil { + t.Fatalf("ensure session: %v", err) + } + // The passthrough prepare is eagerly upgraded into a full launch, so + // the session reaches STARTING (agent process started synchronously). + if resp.State != string(models.TaskSessionStateStarting) { + t.Fatalf("State = %q, want %q (eager passthrough upgrade)", resp.State, models.TaskSessionStateStarting) + } + }) + + t.Run("passthrough prepare with auto_start false stays prepared", func(t *testing.T) { + seedPassthroughTask("ptask-no-launch", "step-plain") + falseVal := false + resp, err := svc.EnsureSession(ctx, "ptask-no-launch", EnsureSessionOptions{AutoStart: &falseVal}) + if err != nil { + t.Fatalf("ensure session: %v", err) + } + if resp.Source != "created_prepare" { + t.Fatalf("Source = %q, want created_prepare", resp.Source) + } + if resp.State != string(models.TaskSessionStateCreated) { + t.Fatalf("State = %q, want %q (override must not launch the passthrough agent)", resp.State, models.TaskSessionStateCreated) + } + }) + + t.Run("passthrough auto-start step with auto_start false stays prepared", func(t *testing.T) { + seedPassthroughTask("ptask-start-step", "step-start") + falseVal := false + resp, err := svc.EnsureSession(ctx, "ptask-start-step", EnsureSessionOptions{AutoStart: &falseVal}) + if err != nil { + t.Fatalf("ensure session: %v", err) + } + if resp.Source != "created_prepare" { + t.Fatalf("Source = %q, want created_prepare", resp.Source) + } + if resp.State != string(models.TaskSessionStateCreated) { + t.Fatalf("State = %q, want %q (override must not launch the passthrough agent)", resp.State, models.TaskSessionStateCreated) + } + }) +} diff --git a/apps/backend/internal/orchestrator/session_launch.go b/apps/backend/internal/orchestrator/session_launch.go index ef68f1f6b5..fd04c5f354 100644 --- a/apps/backend/internal/orchestrator/session_launch.go +++ b/apps/backend/internal/orchestrator/session_launch.go @@ -49,6 +49,14 @@ type LaunchSessionRequest struct { LaunchWorkspace bool `json:"launch_workspace,omitempty"` SkipMessageRecord bool `json:"skip_message_record,omitempty"` AutoStart bool `json:"auto_start,omitempty"` + // NoAgentLaunch marks a prepare request that must NEVER be upgraded into an + // agent launch, even for passthrough profiles (whose prepare would normally + // be eagerly upgraded so the PTY exists). It backs the session.ensure + // auto_start=false override used by the prevent-auto-start-on-open + // preference: the session is created workspace-only (CREATED) and the + // Start agent button launches it later. It is an internal server-side flag + // set from EnsureSessionOptions, kept off the wire protocol (`json:"-"`). + NoAgentLaunch bool `json:"-"` // DeferredStart marks a prepare whose caller will follow up with an explicit // IntentStartCreated that carries the prompt (the two-phase create flow: // cheap sync prepare + async start). It suppresses the passthrough @@ -206,9 +214,14 @@ func (s *Service) launchPrepare(ctx context.Context, req *LaunchSessionRequest) // imminent prompt-bearing start) get the eager launch. See launchPrepare for // why AutoStart and DeferredStart each suppress it. func (s *Service) shouldUpgradePassthroughPrepare(ctx context.Context, req *LaunchSessionRequest) bool { + if req.NoAgentLaunch { + return false + } return !req.AutoStart && !req.DeferredStart && s.isPassthroughProfile(ctx, req.AgentProfileID) } +// isPassthroughProfile reports whether the agent profile is a CLI +// passthrough provider. func (s *Service) isPassthroughProfile(ctx context.Context, profileID string) bool { if profileID == "" || s.agentManager == nil { return false @@ -375,6 +388,8 @@ func (s *Service) RecoverSession(ctx context.Context, taskID, sessionID, action return resp, nil } +// normalizeRecoverSessionError maps a missing-profile resume failure to a +// user-actionable message. func normalizeRecoverSessionError(err error) error { if err == nil { return nil @@ -385,6 +400,8 @@ func normalizeRecoverSessionError(err error) error { return err } +// isMissingProfileResumeError reports whether the error indicates the +// session's agent profile no longer exists. func isMissingProfileResumeError(err error) bool { msg := strings.ToLower(err.Error()) return strings.Contains(msg, "failed to resolve agent profile") || diff --git a/apps/backend/internal/user/controller/controller.go b/apps/backend/internal/user/controller/controller.go index bddaaa96ed..f6254eafdb 100644 --- a/apps/backend/internal/user/controller/controller.go +++ b/apps/backend/internal/user/controller/controller.go @@ -8,14 +8,18 @@ import ( "github.com/kandev/kandev/internal/user/service" ) +// Controller exposes the user settings HTTP handlers backed by the user +// service. type Controller struct { svc *service.Service } +// NewController builds a user settings controller. func NewController(svc *service.Service) *Controller { return &Controller{svc: svc} } +// GetCurrentUser returns the authenticated user together with their settings. func (c *Controller) GetCurrentUser(ctx context.Context) (dto.UserResponse, error) { user, err := c.svc.GetCurrentUser(ctx) if err != nil { @@ -31,6 +35,7 @@ func (c *Controller) GetCurrentUser(ctx context.Context) (dto.UserResponse, erro }, nil } +// GetUserSettings returns the current user's settings and OS shell options. func (c *Controller) GetUserSettings(ctx context.Context) (dto.UserSettingsResponse, error) { settings, err := c.svc.GetUserSettings(ctx) if err != nil { @@ -42,6 +47,8 @@ func (c *Controller) GetUserSettings(ctx context.Context) (dto.UserSettingsRespo }, nil } +// UpdateUserSettings applies a partial settings patch and returns the +// resulting settings with OS shell options. func (c *Controller) UpdateUserSettings(ctx context.Context, req dto.UpdateUserSettingsRequest) (dto.UserSettingsResponse, error) { settings, err := c.svc.UpdateUserSettings(ctx, &service.UpdateUserSettingsRequest{ WorkspaceID: req.WorkspaceID, @@ -59,6 +66,7 @@ func (c *Controller) UpdateUserSettings(ctx context.Context, req dto.UpdateUserS ChatSubmitKey: req.ChatSubmitKey, ReviewAutoMarkOnScroll: req.ReviewAutoMarkOnScroll, ConfirmTaskArchive: req.ConfirmTaskArchive, + PreventAutoStartAgentOnOpen: req.PreventAutoStartAgentOnOpen, UnreadDivider: req.UnreadDivider, AgentGeneratedTaskTitles: req.AgentGeneratedTaskTitles, MCPTaskAgentProfileDefault: req.MCPTaskAgentProfileDefault, @@ -109,6 +117,8 @@ func (c *Controller) UpdateUserSettings(ctx context.Context, req dto.UpdateUserS }, nil } +// systemMetricsDisplayPatch maps the API patch shape to the service layer, +// returning nil when the patch is omitted. func systemMetricsDisplayPatch(patch *dto.SystemMetricsDisplaySettingsPatch) *service.SystemMetricsDisplaySettingsPatch { if patch == nil { return nil @@ -119,6 +129,8 @@ func systemMetricsDisplayPatch(patch *dto.SystemMetricsDisplaySettingsPatch) *se } } +// shellOptionsForOS returns the shell choices offered in settings for the +// current operating system. func shellOptionsForOS() []dto.ShellOption { switch runtime.GOOS { case "windows": diff --git a/apps/backend/internal/user/dto/dto.go b/apps/backend/internal/user/dto/dto.go index 50f765b2c5..f0c8e51a26 100644 --- a/apps/backend/internal/user/dto/dto.go +++ b/apps/backend/internal/user/dto/dto.go @@ -31,6 +31,7 @@ type UserSettingsDTO struct { ChatSubmitKey string `json:"chat_submit_key"` ReviewAutoMarkOnScroll bool `json:"review_auto_mark_on_scroll"` ConfirmTaskArchive bool `json:"confirm_task_archive"` + PreventAutoStartAgentOnOpen bool `json:"prevent_auto_start_agent_on_open"` UnreadDivider bool `json:"unread_divider"` AgentGeneratedTaskTitles bool `json:"agent_generated_task_titles"` MCPTaskAgentProfileDefault string `json:"mcp_task_agent_profile_default"` @@ -106,6 +107,7 @@ type UpdateUserSettingsRequest struct { ChatSubmitKey *string `json:"chat_submit_key,omitempty"` ReviewAutoMarkOnScroll *bool `json:"review_auto_mark_on_scroll,omitempty"` ConfirmTaskArchive *bool `json:"confirm_task_archive,omitempty"` + PreventAutoStartAgentOnOpen *bool `json:"prevent_auto_start_agent_on_open,omitempty"` UnreadDivider *bool `json:"unread_divider,omitempty"` AgentGeneratedTaskTitles *bool `json:"agent_generated_task_titles,omitempty"` MCPTaskAgentProfileDefault *string `json:"mcp_task_agent_profile_default,omitempty"` @@ -161,10 +163,13 @@ type NullableSidebarDraft struct { Value *models.SidebarViewDraft } +// NewNullableSidebarDraft wraps a draft value as explicitly-set. func NewNullableSidebarDraft(value *models.SidebarViewDraft) NullableSidebarDraft { return NullableSidebarDraft{Set: true, Value: value} } +// UnmarshalJSON decodes an explicit null as "set with nil value" so the +// PATCH distinction survives JSON decoding. func (n *NullableSidebarDraft) UnmarshalJSON(data []byte) error { n.Set = true if string(data) == "null" { @@ -179,6 +184,9 @@ func (n *NullableSidebarDraft) UnmarshalJSON(data []byte) error { return nil } +// ServiceValue returns a **SidebarViewDraft suitable for the service layer: +// nil when the field was omitted, otherwise a pointer to the value (possibly +// nil when explicitly cleared). func (n NullableSidebarDraft) ServiceValue() **models.SidebarViewDraft { if !n.Set { return nil @@ -193,6 +201,8 @@ type NullableRawMessage struct { Value *json.RawMessage } +// UnmarshalJSON decodes an explicit null as "set with nil value" so the +// PATCH distinction survives JSON decoding. func (n *NullableRawMessage) UnmarshalJSON(data []byte) error { n.Set = true if string(data) == "null" { @@ -207,6 +217,9 @@ func (n *NullableRawMessage) UnmarshalJSON(data []byte) error { return nil } +// ServiceValue returns a **json.RawMessage suitable for the service layer: +// nil when the field was omitted, otherwise a pointer to the value (possibly +// nil when explicitly cleared). func (n NullableRawMessage) ServiceValue() **json.RawMessage { if !n.Set { return nil @@ -214,6 +227,7 @@ func (n NullableRawMessage) ServiceValue() **json.RawMessage { return &n.Value } +// FromUser maps a user model to its API DTO. func FromUser(user *models.User) UserDTO { return UserDTO{ ID: user.ID, @@ -223,6 +237,8 @@ func FromUser(user *models.User) UserDTO { } } +// FromUserSettings maps a settings model to its API DTO, normalizing enum +// fields (startup page, MCP default, LSP location) to canonical values. func FromUserSettings(settings *models.UserSettings) UserSettingsDTO { return UserSettingsDTO{ UserID: settings.UserID, @@ -241,6 +257,7 @@ func FromUserSettings(settings *models.UserSettings) UserSettingsDTO { ChatSubmitKey: settings.ChatSubmitKey, ReviewAutoMarkOnScroll: settings.ReviewAutoMarkOnScroll, ConfirmTaskArchive: settings.ConfirmTaskArchive, + PreventAutoStartAgentOnOpen: settings.PreventAutoStartAgentOnOpen, UnreadDivider: settings.UnreadDivider, AgentGeneratedTaskTitles: settings.AgentGeneratedTaskTitles, MCPTaskAgentProfileDefault: models.NormalizeMCPTaskAgentProfileDefault(settings.MCPTaskAgentProfileDefault), diff --git a/apps/backend/internal/user/models/models.go b/apps/backend/internal/user/models/models.go index 8a2523bc0f..b31500ae89 100644 --- a/apps/backend/internal/user/models/models.go +++ b/apps/backend/internal/user/models/models.go @@ -12,6 +12,9 @@ const ( LspStatusLocationStatusBar = "status_bar" ) +// NormalizeMCPTaskAgentProfileDefault returns the canonical MCP task agent +// profile default: workspace_default is accepted as-is, anything else is +// coerced to current_task. func NormalizeMCPTaskAgentProfileDefault(value string) string { if value == MCPTaskAgentProfileDefaultWorkspaceDefault { return value @@ -19,6 +22,8 @@ func NormalizeMCPTaskAgentProfileDefault(value string) string { return MCPTaskAgentProfileDefaultCurrentTask } +// NormalizeLspStatusLocation returns the canonical LSP status location: +// status_bar is accepted as-is, anything else is coerced to toolbar. func NormalizeLspStatusLocation(value string) string { if value == LspStatusLocationStatusBar { return value @@ -31,6 +36,8 @@ const ( StartupPageLastTask = "last_task" ) +// NormalizeStartupPage returns the canonical startup page: last_task is +// accepted as-is, anything else is coerced to task_overview. func NormalizeStartupPage(value string) string { if value == StartupPageLastTask { return value @@ -80,6 +87,7 @@ type UserSettings struct { ChatSubmitKey string `json:"chat_submit_key"` // "enter" | "cmd_enter" ReviewAutoMarkOnScroll bool `json:"review_auto_mark_on_scroll"` ConfirmTaskArchive bool `json:"confirm_task_archive"` + PreventAutoStartAgentOnOpen bool `json:"prevent_auto_start_agent_on_open"` UnreadDivider bool `json:"unread_divider"` AgentGeneratedTaskTitles bool `json:"agent_generated_task_titles"` MCPTaskAgentProfileDefault string `json:"mcp_task_agent_profile_default"` diff --git a/apps/backend/internal/user/service/service.go b/apps/backend/internal/user/service/service.go index cfb5736940..3d12e20811 100644 --- a/apps/backend/internal/user/service/service.go +++ b/apps/backend/internal/user/service/service.go @@ -51,6 +51,7 @@ type UpdateUserSettingsRequest struct { ChatSubmitKey *string ReviewAutoMarkOnScroll *bool ConfirmTaskArchive *bool + PreventAutoStartAgentOnOpen *bool UnreadDivider *bool AgentGeneratedTaskTitles *bool MCPTaskAgentProfileDefault *string @@ -98,6 +99,8 @@ type SystemMetricsDisplaySettingsPatch struct { Simplified *bool } +// NewService builds the user settings service with its repository, event bus, +// and logger. func NewService(repo store.Repository, eventBus bus.EventBus, log *logger.Logger) *Service { return &Service{ repo: repo, @@ -107,6 +110,8 @@ func NewService(repo store.Repository, eventBus bus.EventBus, log *logger.Logger } } +// settingsUserID resolves the effective user for settings operations: +// the authenticated identity when present, otherwise the default user. func (s *Service) settingsUserID(ctx context.Context) string { identity, ok := authn.IdentityFromContext(ctx) if !ok || identity.Synthetic || identity.UserID == "" { @@ -115,6 +120,8 @@ func (s *Service) settingsUserID(ctx context.Context) string { return identity.UserID } +// GetCurrentUser returns the current (or default) user, mapping a missing +// row to ErrUserNotFound. func (s *Service) GetCurrentUser(ctx context.Context) (*models.User, error) { user, err := s.repo.GetUser(ctx, s.settingsUserID(ctx)) if err != nil { @@ -123,6 +130,7 @@ func (s *Service) GetCurrentUser(ctx context.Context) (*models.User, error) { return user, nil } +// GetUserSettings returns the current user's persisted settings. func (s *Service) GetUserSettings(ctx context.Context) (*models.UserSettings, error) { settings, err := s.repo.GetUserSettings(ctx, s.settingsUserID(ctx)) if err != nil { @@ -131,6 +139,7 @@ func (s *Service) GetUserSettings(ctx context.Context) (*models.UserSettings, er return settings, nil } +// PreferredShell returns the user's configured shell. func (s *Service) PreferredShell(ctx context.Context) (string, error) { settings, err := s.repo.GetUserSettings(ctx, s.settingsUserID(ctx)) if err != nil { @@ -157,6 +166,9 @@ func (s *Service) GetDefaultUtilityAgentProfileID(ctx context.Context) (string, return settings.DefaultUtilityAgentProfileID, nil } +// UpdateUserSettings applies a partial settings patch field by field, +// validates each group, persists the result, and publishes the settings +// update event. func (s *Service) UpdateUserSettings(ctx context.Context, req *UpdateUserSettingsRequest) (*models.UserSettings, error) { settings, err := s.repo.GetUserSettings(ctx, s.settingsUserID(ctx)) if err != nil { @@ -199,6 +211,8 @@ func (s *Service) UpdateUserSettings(ctx context.Context, req *UpdateUserSetting return settings, nil } +// RecordTaskCreateLastUsed persists the last task-creation choices (a no-op +// for an empty patch) and publishes the settings update event. func (s *Service) RecordTaskCreateLastUsed(ctx context.Context, patch models.TaskCreateLastUsed) error { if taskCreateLastUsedPatchEmpty(patch) { return nil @@ -211,10 +225,13 @@ func (s *Service) RecordTaskCreateLastUsed(ctx context.Context, patch models.Tas return nil } +// updateTaskCreateLastUsed delegates the patch to the repository. func (s *Service) updateTaskCreateLastUsed(ctx context.Context, patch models.TaskCreateLastUsed) (*models.UserSettings, error) { return s.repo.UpdateTaskCreateLastUsed(ctx, s.settingsUserID(ctx), patch) } +// taskCreateLastUsedPatchEmpty reports whether every field of the patch is +// unset, i.e. nothing to record. func taskCreateLastUsedPatchEmpty(patch models.TaskCreateLastUsed) bool { return patch.RepositoryID == "" && patch.Branch == "" && @@ -254,6 +271,8 @@ func applyBasicSettings(settings *models.UserSettings, req *UpdateUserSettingsRe return nil } +// applyWorkspaceAndTaskListPreferences copies workspace, board, and task-list +// fields from the patch, validating the hidden-step map and list sort/group. func applyWorkspaceAndTaskListPreferences(settings *models.UserSettings, req *UpdateUserSettingsRequest) error { if req.WorkspaceID != nil { settings.WorkspaceID = *req.WorkspaceID @@ -339,6 +358,7 @@ func validateKanbanHiddenStepIDs(hidden map[string][]string) error { return nil } +// applyStartupPage validates and applies the startup page enum. func applyStartupPage(settings *models.UserSettings, value *string) error { if value == nil { return nil @@ -353,6 +373,9 @@ func applyStartupPage(settings *models.UserSettings, value *string) error { } } +// applyTaskActionPreferences copies the task-action preference group +// (archive confirmation, auto-start prevention, transcript display toggles, +// MCP default profile, release notification) from the patch. func applyTaskActionPreferences(settings *models.UserSettings, req *UpdateUserSettingsRequest) error { if req.ReviewAutoMarkOnScroll != nil { settings.ReviewAutoMarkOnScroll = *req.ReviewAutoMarkOnScroll @@ -360,6 +383,9 @@ func applyTaskActionPreferences(settings *models.UserSettings, req *UpdateUserSe if req.ConfirmTaskArchive != nil { settings.ConfirmTaskArchive = *req.ConfirmTaskArchive } + if req.PreventAutoStartAgentOnOpen != nil { + settings.PreventAutoStartAgentOnOpen = *req.PreventAutoStartAgentOnOpen + } if req.UnreadDivider != nil { settings.UnreadDivider = *req.UnreadDivider } @@ -393,6 +419,8 @@ func applyTaskActionPreferences(settings *models.UserSettings, req *UpdateUserSe return nil } +// applyUtilityPreferences copies the utility-agent defaults and release-notes +// version from the patch. func applyUtilityPreferences(settings *models.UserSettings, req *UpdateUserSettingsRequest) { if req.ReleaseNotesLastSeenVersion != nil { settings.ReleaseNotesLastSeenVersion = *req.ReleaseNotesLastSeenVersion @@ -408,6 +436,7 @@ func applyUtilityPreferences(settings *models.UserSettings, req *UpdateUserSetti } } +// applyKeyboardShortcuts validates and applies the keyboard shortcut map. func applyKeyboardShortcuts(settings *models.UserSettings, value *map[string]interface{}) error { if value == nil { return nil @@ -419,6 +448,7 @@ func applyKeyboardShortcuts(settings *models.UserSettings, value *map[string]int return nil } +// applySystemMetricsDisplay applies the topbar metrics display patch. func applySystemMetricsDisplay(settings *models.UserSettings, value *SystemMetricsDisplaySettingsPatch) { if value == nil { return @@ -431,6 +461,8 @@ func applySystemMetricsDisplay(settings *models.UserSettings, value *SystemMetri } } +// applyTerminalFontPreferences applies the terminal font family and validates +// the font size range. func applyTerminalFontPreferences(settings *models.UserSettings, req *UpdateUserSettingsRequest) error { if req.TerminalFontFamily != nil { settings.TerminalFontFamily = strings.TrimSpace(*req.TerminalFontFamily) @@ -446,6 +478,8 @@ func applyTerminalFontPreferences(settings *models.UserSettings, req *UpdateUser return nil } +// applyMCPTaskAgentProfileDefault validates and applies the MCP task agent +// profile default enum. func applyMCPTaskAgentProfileDefault(settings *models.UserSettings, value *string) error { if value == nil { return nil @@ -462,6 +496,8 @@ func applyMCPTaskAgentProfileDefault(settings *models.UserSettings, value *strin } } +// applyTasksListPreferences validates and applies the task list sort and +// group enums, defaulting empty values. func applyTasksListPreferences(settings *models.UserSettings, sortValue, groupValue *string) error { if sortValue != nil { v := strings.TrimSpace(*sortValue) @@ -486,6 +522,8 @@ func applyTasksListPreferences(settings *models.UserSettings, sortValue, groupVa return nil } +// applyTerminalLinkBehavior validates and applies the terminal link behavior +// enum. func applyTerminalLinkBehavior(settings *models.UserSettings, value *string) error { if value == nil { return nil @@ -498,6 +536,8 @@ func applyTerminalLinkBehavior(settings *models.UserSettings, value *string) err return nil } +// applyChangesPanelLayout validates and applies the changes panel layout +// enum (flat or tree). func applyChangesPanelLayout(settings *models.UserSettings, value *string) error { if value == nil { return nil @@ -683,6 +723,8 @@ func applySidebarViews(settings *models.UserSettings, req *UpdateUserSettingsReq return nil } +// applySidebarViewState validates and applies the active sidebar view id and +// the sidebar draft. func applySidebarViewState(settings *models.UserSettings, req *UpdateUserSettingsRequest) error { if req.SidebarActiveViewID != nil { activeViewID := strings.TrimSpace(*req.SidebarActiveViewID) @@ -700,6 +742,7 @@ func applySidebarViewState(settings *models.UserSettings, req *UpdateUserSetting return nil } +// sidebarViewIDExists reports whether a view with the given id is saved. func sidebarViewIDExists(views []models.SidebarView, id string) bool { for _, view := range views { if view.ID == id { @@ -711,6 +754,9 @@ func sidebarViewIDExists(views []models.SidebarView, id string) bool { const maxUserPreferenceBlobBytes = 64 * 1024 +// applyUserPreferenceBlobs applies each free-form preference blob (sidebar +// task prefs, Jira/GitHub/GitLab/Azure saved views and presets), validating +// size and shape via applyUserPreferenceBlob. func applyUserPreferenceBlobs(settings *models.UserSettings, req *UpdateUserSettingsRequest) error { if req.SidebarTaskPrefs != nil { settings.SidebarTaskPrefs = *req.SidebarTaskPrefs @@ -736,6 +782,9 @@ func applyUserPreferenceBlobs(settings *models.UserSettings, req *UpdateUserSett return nil } +// applyUserPreferenceBlob applies one PATCH-distinguished blob: omitted +// leaves the target untouched, explicit null clears it, and a value is +// validated before being stored. func applyUserPreferenceBlob(field string, value **json.RawMessage, target *json.RawMessage) error { if value == nil { return nil @@ -751,6 +800,8 @@ func applyUserPreferenceBlob(field string, value **json.RawMessage, target *json return nil } +// validateUserPreferenceBlob enforces the blob size cap and JSON shape +// (object, array, or null). func validateUserPreferenceBlob(field string, value json.RawMessage) error { if len(value) > maxUserPreferenceBlobBytes { return fmt.Errorf("%s: max %d bytes allowed", field, maxUserPreferenceBlobBytes) @@ -767,6 +818,8 @@ func validateUserPreferenceBlob(field string, value json.RawMessage) error { } } +// publishUserSettingsEvent broadcasts the full settings snapshot on the +// UserSettingsUpdated event bus topic so connected clients stay in sync. func (s *Service) publishUserSettingsEvent(ctx context.Context, settings *models.UserSettings) { if s.eventBus == nil || settings == nil { return @@ -788,6 +841,7 @@ func (s *Service) publishUserSettingsEvent(ctx context.Context, settings *models "chat_submit_key": settings.ChatSubmitKey, "review_auto_mark_on_scroll": settings.ReviewAutoMarkOnScroll, "confirm_task_archive": settings.ConfirmTaskArchive, + "prevent_auto_start_agent_on_open": settings.PreventAutoStartAgentOnOpen, "unread_divider": settings.UnreadDivider, "agent_generated_task_titles": settings.AgentGeneratedTaskTitles, "mcp_task_agent_profile_default": models.NormalizeMCPTaskAgentProfileDefault(settings.MCPTaskAgentProfileDefault), @@ -836,6 +890,8 @@ func (s *Service) publishUserSettingsEvent(ctx context.Context, settings *models } } +// validateKeyboardShortcuts checks the shortcut map shape: each entry must be +// an object with a non-empty key and boolean-only modifiers. func validateKeyboardShortcuts(shortcuts map[string]interface{}) error { for name, raw := range shortcuts { shortcut, ok := raw.(map[string]interface{}) @@ -861,6 +917,7 @@ func validateKeyboardShortcuts(shortcuts map[string]interface{}) error { return nil } +// validateLSPLanguages rejects languages the LSP installer does not support. func validateLSPLanguages(langs []string) error { supported := installer.SupportedLanguages() for _, lang := range langs { @@ -871,6 +928,8 @@ func validateLSPLanguages(langs []string) error { return nil } +// validateLSPAutoInstallLanguages rejects languages that are unsupported or +// cannot be auto-installed. func validateLSPAutoInstallLanguages(langs []string) error { if err := validateLSPLanguages(langs); err != nil { return err @@ -883,6 +942,9 @@ func validateLSPAutoInstallLanguages(langs []string) error { return nil } +// ClearDefaultEditorID clears the saved default editor when it matches the +// given editor id (used when an editor is uninstalled), persisting and +// publishing the change. func (s *Service) ClearDefaultEditorID(ctx context.Context, editorID string) error { if editorID == "" { return nil diff --git a/apps/backend/internal/user/service/service_test.go b/apps/backend/internal/user/service/service_test.go index cc2fca0031..ba54b97b03 100644 --- a/apps/backend/internal/user/service/service_test.go +++ b/apps/backend/internal/user/service/service_test.go @@ -185,6 +185,42 @@ func TestApplyBasicSettings_ConfirmTaskArchive(t *testing.T) { }) } +func TestApplyBasicSettings_PreventAutoStartAgentOnOpen(t *testing.T) { + t.Run("omitted value leaves the setting unchanged", func(t *testing.T) { + settings := &models.UserSettings{PreventAutoStartAgentOnOpen: true} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !settings.PreventAutoStartAgentOnOpen { + t.Fatal("expected the setting to remain enabled") + } + }) + + t.Run("explicit true enables the setting", func(t *testing.T) { + settings := &models.UserSettings{PreventAutoStartAgentOnOpen: false} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{ + PreventAutoStartAgentOnOpen: ptr(true), + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !settings.PreventAutoStartAgentOnOpen { + t.Fatal("expected the setting to be enabled") + } + }) + + t.Run("explicit false disables the setting", func(t *testing.T) { + settings := &models.UserSettings{PreventAutoStartAgentOnOpen: true} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{ + PreventAutoStartAgentOnOpen: ptr(false), + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if settings.PreventAutoStartAgentOnOpen { + t.Fatal("expected the setting to be disabled") + } + }) +} + func TestApplyBasicSettingsAgentGeneratedTaskTitles(t *testing.T) { settings := &models.UserSettings{AgentGeneratedTaskTitles: false} if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{}); err != nil { diff --git a/apps/backend/internal/user/store/sqlite.go b/apps/backend/internal/user/store/sqlite.go index 27affb4926..538480b812 100644 --- a/apps/backend/internal/user/store/sqlite.go +++ b/apps/backend/internal/user/store/sqlite.go @@ -32,10 +32,15 @@ type sqliteRepository struct { var _ Repository = (*sqliteRepository)(nil) +// newSQLiteRepositoryWithDB builds a repository over caller-owned database +// handles (the writer/reader pair is not closed by the repository). func newSQLiteRepositoryWithDB(writer, reader *sqlx.DB) (*sqliteRepository, error) { return newSQLiteRepository(writer, reader, false) } +// newSQLiteRepository builds a repository, initializing the schema and the +// default user; when ownsDB is set the writer connection is closed on schema +// failure. func newSQLiteRepository(writer, reader *sqlx.DB, ownsDB bool) (*sqliteRepository, error) { repo := &sqliteRepository{db: writer, ro: reader, ownsDB: ownsDB} if err := repo.initSchema(); err != nil { @@ -49,6 +54,8 @@ func newSQLiteRepository(writer, reader *sqlx.DB, ownsDB bool) (*sqliteRepositor return repo, nil } +// initSchema creates the users table, applies idempotent migrations, and +// seeds the default user. func (r *sqliteRepository) initSchema() error { schema := ` CREATE TABLE IF NOT EXISTS users ( @@ -86,6 +93,8 @@ func (r *sqliteRepository) runMigrations() { m.Apply("users.email_unique", "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email)") } +// ensureDefaultUser inserts the pre-auth default user row when it does not +// exist yet. func (r *sqliteRepository) ensureDefaultUser() error { ctx := context.Background() var count int @@ -105,6 +114,7 @@ func (r *sqliteRepository) ensureDefaultUser() error { return nil } +// Close releases the writer connection when the repository owns it. func (r *sqliteRepository) Close() error { if !r.ownsDB { return nil @@ -114,6 +124,7 @@ func (r *sqliteRepository) Close() error { const userColumns = "id, email, display_name, role, status, created_at, updated_at" +// GetUser returns the user row for the given id. func (r *sqliteRepository) GetUser(ctx context.Context, id string) (*models.User, error) { row := r.ro.QueryRowContext(ctx, r.ro.Rebind(` SELECT `+userColumns+` @@ -122,10 +133,12 @@ func (r *sqliteRepository) GetUser(ctx context.Context, id string) (*models.User return scanUser(row) } +// GetDefaultUser returns the pre-auth default user row. func (r *sqliteRepository) GetDefaultUser(ctx context.Context) (*models.User, error) { return r.GetUser(ctx, DefaultUserID) } +// GetUserByEmail returns the user row matching the email. func (r *sqliteRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) { row := r.ro.QueryRowContext(ctx, r.ro.Rebind(` SELECT `+userColumns+` @@ -134,6 +147,7 @@ func (r *sqliteRepository) GetUserByEmail(ctx context.Context, email string) (*m return scanUser(row) } +// ListUsers returns all users ordered by creation time. func (r *sqliteRepository) ListUsers(ctx context.Context) ([]*models.User, error) { rows, err := r.ro.QueryContext(ctx, ` SELECT `+userColumns+` @@ -154,11 +168,14 @@ func (r *sqliteRepository) ListUsers(ctx context.Context) ([]*models.User, error return users, rows.Err() } +// DeleteUser removes the user row with the given id. func (r *sqliteRepository) DeleteUser(ctx context.Context, id string) error { _, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM users WHERE id = ?`), id) return err } +// CreateUser inserts a new user row with an empty settings blob, stamping +// creation timestamps. func (r *sqliteRepository) CreateUser(ctx context.Context, user *models.User) error { now := time.Now().UTC() user.CreatedAt = now @@ -187,6 +204,8 @@ func (r *sqliteRepository) UpdateUserProfile(ctx context.Context, id, email, dis return r.getUserFromWriter(ctx, id) } +// UpdateUserRoleStatus updates a user's role and status, returning the +// refreshed row. func (r *sqliteRepository) UpdateUserRoleStatus(ctx context.Context, id, role, status string) (*models.User, error) { result, err := r.db.ExecContext(ctx, r.db.Rebind(` UPDATE users SET role = ?, status = ?, updated_at = ? @@ -211,6 +230,8 @@ func (r *sqliteRepository) getUserFromWriter(ctx context.Context, id string) (*m return scanUser(row) } +// checkUserRowsAffected fails when a user mutation affected no rows, i.e. +// the target user does not exist. func checkUserRowsAffected(result sqlResult, userID string) error { rows, err := result.RowsAffected() if err != nil { @@ -226,10 +247,12 @@ type sqlResult interface { RowsAffected() (int64, error) } +// GetUserSettings reads the user's settings through the reader connection. func (r *sqliteRepository) GetUserSettings(ctx context.Context, userID string) (*models.UserSettings, error) { return r.getUserSettings(ctx, r.ro, userID) } +// getUserSettings reads settings through an explicit connection. func (r *sqliteRepository) getUserSettings(ctx context.Context, conn *sqlx.DB, userID string) (*models.UserSettings, error) { row := conn.QueryRowContext(ctx, conn.Rebind(` SELECT settings, updated_at, settings_revision @@ -242,6 +265,9 @@ func (r *sqliteRepository) getUserSettings(ctx context.Context, conn *sqlx.DB, u return settings, nil } +// UpsertUserSettingsPreservingTaskCreateLastUsed writes the settings blob, +// merging the task_create_last_used patch into the stored JSON rather than +// replacing it, and returns the persisted settings. func (r *sqliteRepository) UpsertUserSettingsPreservingTaskCreateLastUsed( ctx context.Context, settings *models.UserSettings, @@ -288,6 +314,9 @@ func (r *sqliteRepository) UpsertUserSettingsPreservingTaskCreateLastUsed( ) } +// upsertUserSettingsPreservingTaskCreateLastUsedPostgres writes settings via +// a jsonb_set expression so task_create_last_used merges instead of +// replacing. func (r *sqliteRepository) upsertUserSettingsPreservingTaskCreateLastUsedPostgres( ctx context.Context, settings *models.UserSettings, @@ -303,6 +332,8 @@ func (r *sqliteRepository) upsertUserSettingsPreservingTaskCreateLastUsedPostgre ) } +// UpdateTaskCreateLastUsed merges the last task-creation choices into the +// stored settings JSON and bumps the revision. func (r *sqliteRepository) UpdateTaskCreateLastUsed(ctx context.Context, userID string, patch models.TaskCreateLastUsed) (*models.UserSettings, error) { if dialect.IsPostgres(r.db.DriverName()) { return r.updateTaskCreateLastUsedPostgres(ctx, userID, patch) @@ -334,6 +365,8 @@ func (r *sqliteRepository) UpdateTaskCreateLastUsed(ctx context.Context, userID ) } +// updateTaskCreateLastUsedPostgres merges the patch via a Postgres jsonb_set +// expression. func (r *sqliteRepository) updateTaskCreateLastUsedPostgres(ctx context.Context, userID string, patch models.TaskCreateLastUsed) (*models.UserSettings, error) { query, args := buildPostgresTaskCreateLastUsedUpdate(patch) if len(args) == 0 { @@ -347,6 +380,8 @@ func (r *sqliteRepository) updateTaskCreateLastUsedPostgres(ctx context.Context, ) } +// makeTaskCreateLastUsedJSONSetArgs flattens the patch into JSON1 json_set +// path/value arguments, skipping empty fields and unsafe workspace path keys. func makeTaskCreateLastUsedJSONSetArgs(patch models.TaskCreateLastUsed) []any { args := []any{} if patch.RepositoryID != "" { @@ -382,6 +417,9 @@ func makeTaskCreateLastUsedJSONSetArgs(patch models.TaskCreateLastUsed) []any { return args } +// isSafeTaskCreateWorkspacePathKey reports whether a workspace id can be +// embedded in a JSON path segment without punctuation that would change the +// path. func isSafeTaskCreateWorkspacePathKey(value string) bool { if value == "" { return false @@ -398,6 +436,8 @@ func isSafeTaskCreateWorkspacePathKey(value string) bool { return true } +// buildPostgresTaskCreateLastUsedUpdate builds the jsonb_set UPDATE statement +// and its arguments for a task_create_last_used patch. func buildPostgresTaskCreateLastUsedUpdate(patch models.TaskCreateLastUsed) (string, []any) { base := "(CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}'::jsonb ELSE settings::jsonb END)" expr := fmt.Sprintf( @@ -416,6 +456,8 @@ func buildPostgresTaskCreateLastUsedUpdate(patch models.TaskCreateLastUsed) (str return query, args } +// buildPostgresUserSettingsPreservingTaskCreateLastUsedUpdate builds the +// jsonb_set UPDATE for a full settings write that merges the patch. func buildPostgresUserSettingsPreservingTaskCreateLastUsedUpdate(patch *models.TaskCreateLastUsed) (string, []any) { base := "(CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}'::jsonb ELSE settings::jsonb END)" expr := fmt.Sprintf( @@ -435,6 +477,8 @@ func buildPostgresUserSettingsPreservingTaskCreateLastUsedUpdate(patch *models.T return query, args } +// normalizePostgresTaskCreateLastUsedExpr builds the jsonb expression that +// reads (or defaults) the task_create_last_used object and its workflow map. func normalizePostgresTaskCreateLastUsedExpr(base string) string { taskCreate := fmt.Sprintf("COALESCE(%s->'task_create_last_used', '{}'::jsonb)", base) workflowMap := fmt.Sprintf( @@ -449,6 +493,8 @@ func normalizePostgresTaskCreateLastUsedExpr(base string) string { ) } +// applyPostgresTaskCreateLastUsedPatch appends jsonb_set calls for each +// non-empty patch field and the corresponding arguments. func applyPostgresTaskCreateLastUsedPatch(expr string, patch models.TaskCreateLastUsed, args []any) (string, []any) { if patch.RepositoryID != "" { expr = fmt.Sprintf("jsonb_set(%s, '{task_create_last_used,repository_id}', to_jsonb(?::text), true)", expr) @@ -485,6 +531,8 @@ func applyPostgresTaskCreateLastUsedPatch(expr string, patch models.TaskCreateLa return expr, args } +// marshalUserSettingsPayload serializes the settings model to the stored JSON +// blob, normalizing enums and defaulting nil slices/maps. func marshalUserSettingsPayload(settings *models.UserSettings) ([]byte, error) { lspAutoStart := settings.LspAutoStartLanguages if lspAutoStart == nil { @@ -527,6 +575,7 @@ func marshalUserSettingsPayload(settings *models.UserSettings) ([]byte, error) { "chat_submit_key": settings.ChatSubmitKey, "review_auto_mark_on_scroll": settings.ReviewAutoMarkOnScroll, "confirm_task_archive": settings.ConfirmTaskArchive, + "prevent_auto_start_agent_on_open": settings.PreventAutoStartAgentOnOpen, "unread_divider": settings.UnreadDivider, "agent_generated_task_titles": settings.AgentGeneratedTaskTitles, "mcp_task_agent_profile_default": models.NormalizeMCPTaskAgentProfileDefault(settings.MCPTaskAgentProfileDefault), @@ -570,6 +619,8 @@ func marshalUserSettingsPayload(settings *models.UserSettings) ([]byte, error) { }) } +// scanUpdatedUserSettings scans a settings row after an UPDATE, mapping a +// missing row to a user-not-found error. func scanUpdatedUserSettings(scanner interface{ Scan(dest ...any) error }, userID string) (*models.UserSettings, error) { settings, err := scanUserSettings(scanner, userID) if err == sql.ErrNoRows { @@ -578,6 +629,7 @@ func scanUpdatedUserSettings(scanner interface{ Scan(dest ...any) error }, userI return settings, err } +// scanUser scans a single user row into a models.User. func scanUser(scanner interface{ Scan(dest ...any) error }) (*models.User, error) { user := &models.User{} if err := scanner.Scan(&user.ID, &user.Email, &user.DisplayName, &user.Role, &user.Status, &user.CreatedAt, &user.UpdatedAt); err != nil { @@ -638,6 +690,8 @@ func mergeVoiceModeDefaults(stored *storedVoiceMode) models.VoiceModeSettings { return out } +// defaultUserSettings returns the baseline settings for a user with no saved +// preferences. func defaultUserSettings(userID string) *models.UserSettings { return &models.UserSettings{ UserID: userID, @@ -676,6 +730,7 @@ func defaultUserSettings(userID string) *models.UserSettings { } } +// DefaultSidebarViews returns the default single "All tasks" sidebar view. func DefaultSidebarViews() []models.SidebarView { return []models.SidebarView{{ ID: DefaultSidebarViewID, @@ -687,6 +742,8 @@ func DefaultSidebarViews() []models.SidebarView { }} } +// scanUserSettings scans and decodes the settings row, starting from defaults +// and merging every field present in the stored JSON blob. func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID string) (*models.UserSettings, error) { settings := defaultUserSettings(userID) var settingsRaw string @@ -712,6 +769,7 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin ChatSubmitKey string `json:"chat_submit_key"` ReviewAutoMarkOnScroll *bool `json:"review_auto_mark_on_scroll"` ConfirmTaskArchive *bool `json:"confirm_task_archive"` + PreventAutoStartAgentOnOpen *bool `json:"prevent_auto_start_agent_on_open"` UnreadDivider *bool `json:"unread_divider"` AgentGeneratedTaskTitles *bool `json:"agent_generated_task_titles"` MCPTaskAgentProfileDefault string `json:"mcp_task_agent_profile_default"` @@ -780,6 +838,9 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin if payload.ConfirmTaskArchive != nil { settings.ConfirmTaskArchive = *payload.ConfirmTaskArchive } + if payload.PreventAutoStartAgentOnOpen != nil { + settings.PreventAutoStartAgentOnOpen = *payload.PreventAutoStartAgentOnOpen + } if payload.UnreadDivider != nil { settings.UnreadDivider = *payload.UnreadDivider } @@ -901,6 +962,8 @@ func decodeKanbanHiddenStepIDs(raw json.RawMessage) map[string][]string { return decoded } +// normalizeSidebarTaskPrefs defaults nil sidebar task pref collections so the +// stored JSON never carries null. func normalizeSidebarTaskPrefs(prefs models.SidebarTaskPrefs) models.SidebarTaskPrefs { if prefs.PinnedTaskIDs == nil { prefs.PinnedTaskIDs = []string{} @@ -914,6 +977,8 @@ func normalizeSidebarTaskPrefs(prefs models.SidebarTaskPrefs) models.SidebarTask return prefs } +// normalizeAppStatusBarOrder defaults nil status bar item lists so the stored +// JSON never carries null. func normalizeAppStatusBarOrder(order models.AppStatusBarOrder) models.AppStatusBarOrder { if order.LeftItemIDs == nil { order.LeftItemIDs = []string{} diff --git a/apps/backend/internal/user/store/sqlite_prevent_auto_start_test.go b/apps/backend/internal/user/store/sqlite_prevent_auto_start_test.go new file mode 100644 index 0000000000..6b0975a90b --- /dev/null +++ b/apps/backend/internal/user/store/sqlite_prevent_auto_start_test.go @@ -0,0 +1,83 @@ +package store + +import ( + "context" + "encoding/json" + "testing" + + "github.com/jmoiron/sqlx" + "github.com/kandev/kandev/internal/user/models" +) + +func TestScanUserSettingsPreventAutoStartAgentOnOpenDefault(t *testing.T) { + tests := []struct { + name string + raw string + want bool + }{ + {name: "empty settings default to false", raw: `{}`, want: false}, + {name: "missing setting defaults to false", raw: `{"chat_submit_key":"cmd_enter"}`, want: false}, + {name: "explicit false is preserved", raw: `{"prevent_auto_start_agent_on_open":false}`, want: false}, + {name: "true is preserved", raw: `{"prevent_auto_start_agent_on_open":true}`, want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + settings, err := scanUserSettings(settingsScanner{raw: tt.raw}, DefaultUserID) + if err != nil { + t.Fatalf("scan settings: %v", err) + } + if settings.PreventAutoStartAgentOnOpen != tt.want { + t.Fatalf("PreventAutoStartAgentOnOpen = %v, want %v", settings.PreventAutoStartAgentOnOpen, tt.want) + } + }) + } +} + +func TestMarshalUserSettingsPreventAutoStartAgentOnOpen(t *testing.T) { + raw, err := marshalUserSettingsPayload(&models.UserSettings{ + PreventAutoStartAgentOnOpen: true, + }) + if err != nil { + t.Fatalf("marshal settings: %v", err) + } + var payload map[string]any + if err := json.Unmarshal(raw, &payload); err != nil { + t.Fatalf("decode settings: %v", err) + } + if got := payload["prevent_auto_start_agent_on_open"]; got != true { + t.Fatalf("prevent_auto_start_agent_on_open = %#v, want true", got) + } +} + +func TestSQLiteRepositoryPreventAutoStartAgentOnOpenRoundTrip(t *testing.T) { + conn, err := sqlx.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + conn.SetMaxOpenConns(1) + t.Cleanup(func() { _ = conn.Close() }) + repo, err := newSQLiteRepositoryWithDB(conn, conn) + if err != nil { + t.Fatalf("new repo: %v", err) + } + + ctx := context.Background() + settings, err := repo.GetUserSettings(ctx, DefaultUserID) + if err != nil { + t.Fatalf("get defaults: %v", err) + } + if settings.PreventAutoStartAgentOnOpen { + t.Fatal("default should be false") + } + settings.PreventAutoStartAgentOnOpen = true + upsertUserSettingsForTest(t, repo, ctx, settings) + + got, err := repo.GetUserSettings(ctx, DefaultUserID) + if err != nil { + t.Fatalf("get saved settings: %v", err) + } + if !got.PreventAutoStartAgentOnOpen { + t.Fatal("PreventAutoStartAgentOnOpen did not round-trip through the SQLite blob") + } +} diff --git a/apps/web/components/github/pr-status-refresh-routes.test.tsx b/apps/web/components/github/pr-status-refresh-routes.test.tsx index e728dd8f54..b4efff9bdb 100644 --- a/apps/web/components/github/pr-status-refresh-routes.test.tsx +++ b/apps/web/components/github/pr-status-refresh-routes.test.tsx @@ -117,6 +117,7 @@ function taskState(prs: TaskPR[], activeTask = false): Partial { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, } : {}), diff --git a/apps/web/components/kanban-with-preview.tsx b/apps/web/components/kanban-with-preview.tsx index 66c1c1dac6..72ea148399 100644 --- a/apps/web/components/kanban-with-preview.tsx +++ b/apps/web/components/kanban-with-preview.tsx @@ -168,10 +168,27 @@ function useSelectedTask( kanbanTasks.find((t: KanbanState["tasks"][number]) => t.id === selectedTaskId) ?? findTaskInSnapshots(selectedTaskId, snapshots); if (!task) return null; + // Boot-hydrated snapshot tasks (backend `mapKanbanTaskState` entries) do + // not carry workflowId, and useAllWorkflowSnapshots keeps those snapshots + // as already-loaded instead of normalizing them. Derive the workflow id + // from the snapshot key so the prevent-auto-start gate resolves the + // task's OWN workflow steps — otherwise a non-active-workflow task would + // be checked against the active workflow's steps and could auto-start a + // terminal-step task despite the preference. + let workflowId = task.workflowId; + if (!workflowId) { + for (const [snapshotWorkflowId, snapshot] of Object.entries(snapshots)) { + if (snapshot.tasks.some((t) => t.id === selectedTaskId)) { + workflowId = snapshotWorkflowId; + break; + } + } + } return { id: task.id, title: task.title, workflowStepId: task.workflowStepId, + workflowId, state: task.state, description: task.description, position: task.position, diff --git a/apps/web/components/review/walkthrough-overlay.test.tsx b/apps/web/components/review/walkthrough-overlay.test.tsx index 81d9c7cf5a..481cc4f4b6 100644 --- a/apps/web/components/review/walkthrough-overlay.test.tsx +++ b/apps/web/components/review/walkthrough-overlay.test.tsx @@ -59,6 +59,7 @@ function renderOverlay({ followActiveTask = false } = {}) { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }} > diff --git a/apps/web/components/settings/general-settings.tsx b/apps/web/components/settings/general-settings.tsx index 076cf2c70c..e2c3833377 100644 --- a/apps/web/components/settings/general-settings.tsx +++ b/apps/web/components/settings/general-settings.tsx @@ -27,6 +27,7 @@ import { updateUserSettings } from "@/lib/api"; import type { Theme } from "@/lib/settings/types"; import type { UserSettingsState } from "@/lib/state/slices/settings/types"; import { ArchiveConfirmationSettings } from "@/components/settings/archive-confirmation-settings"; +import { PreventAutoStartAgentSettings } from "@/components/settings/prevent-auto-start-agent-settings"; import { LanguageSettings } from "@/components/settings/language-settings"; import { MCPTaskAgentProfileDefaultSettings } from "@/components/settings/mcp-task-agent-profile-default-settings"; import { UnreadDividerSettings } from "@/components/settings/unread-divider-settings"; @@ -284,6 +285,7 @@ export function TaskActionsSettings() { description={t("settings:configureArchiveSafeguardsAndDefaultsFor")} >
+ diff --git a/apps/web/components/settings/prevent-auto-start-agent-settings.test.tsx b/apps/web/components/settings/prevent-auto-start-agent-settings.test.tsx new file mode 100644 index 0000000000..5a6ef7bf47 --- /dev/null +++ b/apps/web/components/settings/prevent-auto-start-agent-settings.test.tsx @@ -0,0 +1,84 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { StateProvider } from "@/components/state-provider"; +import { defaultState } from "@/lib/state/default-state"; +import { SettingsSaveProvider } from "./settings-save-provider"; + +const updateUserSettings = vi.fn(); + +vi.mock("@/lib/api", () => ({ + updateUserSettings: (...args: unknown[]) => updateUserSettings(...args), +})); + +import { PreventAutoStartAgentSettings } from "./prevent-auto-start-agent-settings"; + +function renderSettings(preventAutoStartAgentOnOpen = false) { + return render( + + + + + , + ); +} + +const DATA_STATE_ATTRIBUTE = "data-state"; +const CHECKED_STATE = "checked"; +const UNCHECKED_STATE = "unchecked"; + +beforeEach(() => { + updateUserSettings.mockReset().mockResolvedValue({ settings: {} }); +}); + +afterEach(cleanup); + +describe("PreventAutoStartAgentSettings", () => { + it("keeps an explicit true value local until Save changes is pressed", async () => { + renderSettings(true); + + const toggle = screen.getByRole("switch", { name: "Prevent auto-start on open" }); + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(CHECKED_STATE); + expect(updateUserSettings).not.toHaveBeenCalled(); + + fireEvent.click(toggle); + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE); + + fireEvent.click(screen.getByRole("button", { name: "Save changes" })); + await waitFor(() => { + expect(updateUserSettings).toHaveBeenCalledWith({ + prevent_auto_start_agent_on_open: false, + }); + }); + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE); + }); + + it("persists enabling the preference", async () => { + renderSettings(false); + + const toggle = screen.getByRole("switch", { name: "Prevent auto-start on open" }); + fireEvent.click(toggle); + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(CHECKED_STATE); + + fireEvent.click(screen.getByRole("button", { name: "Save changes" })); + await waitFor(() => { + expect(updateUserSettings).toHaveBeenCalledWith({ + prevent_auto_start_agent_on_open: true, + }); + }); + }); + + it("registers its own save contributor so the archive card keeps working", async () => { + renderSettings(false); + fireEvent.click(screen.getByRole("switch", { name: "Prevent auto-start on open" })); + fireEvent.click(screen.getByRole("button", { name: "Save changes" })); + await waitFor(() => { + expect(updateUserSettings).toHaveBeenCalledWith({ + prevent_auto_start_agent_on_open: true, + }); + }); + }); +}); diff --git a/apps/web/components/settings/prevent-auto-start-agent-settings.tsx b/apps/web/components/settings/prevent-auto-start-agent-settings.tsx new file mode 100644 index 0000000000..3f28100ea4 --- /dev/null +++ b/apps/web/components/settings/prevent-auto-start-agent-settings.tsx @@ -0,0 +1,80 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { CardContent, CardHeader, CardTitle } from "@kandev/ui/card"; +import { Label } from "@kandev/ui/label"; +import { Switch } from "@kandev/ui/switch"; +import { useAppStore, useAppStoreApi } from "@/components/state-provider"; +import { updateUserSettings } from "@/lib/api"; +import { SettingsCard } from "./settings-card"; +import { GENERAL_SETTINGS_TARGETS } from "@/lib/settings-discovery/catalog/preferences"; +import { useSettingsSaveContributor } from "./settings-save-provider"; +import { useTranslation } from "react-i18next"; + +export function PreventAutoStartAgentSettings() { + const { t } = useTranslation(); + const preventAutoStartAgentOnOpen = useAppStore( + (state) => state.userSettings.preventAutoStartAgentOnOpen, + ); + const setUserSettings = useAppStore((state) => state.setUserSettings); + const storeApi = useAppStoreApi(); + const [saved, setSaved] = useState(preventAutoStartAgentOnOpen); + const [draft, setDraft] = useState(preventAutoStartAgentOnOpen); + const draftRef = useRef(draft); + draftRef.current = draft; + const isDirty = draft !== saved; + + useEffect(() => { + setSaved((previous) => { + if (draftRef.current === previous) setDraft(preventAutoStartAgentOnOpen); + return preventAutoStartAgentOnOpen; + }); + }, [preventAutoStartAgentOnOpen]); + + useSettingsSaveContributor({ + id: "general-prevent-auto-start-on-open", + revision: Number(draft), + isDirty, + save: async (revision) => { + const submitted = Boolean(revision); + await updateUserSettings({ prevent_auto_start_agent_on_open: submitted }); + setSaved(submitted); + setUserSettings({ + ...storeApi.getState().userSettings, + preventAutoStartAgentOnOpen: submitted, + }); + }, + discard: () => setDraft(saved), + }); + + return ( + + + {t("settings:preventAutoStartAgentOnOpen")} + + +
+
+ +

+ {t("settings:preventAutoStartAgentOnOpenHelp")} +

+
+ +
+
+
+ ); +} diff --git a/apps/web/components/task/chat/message-list-footer.test.tsx b/apps/web/components/task/chat/message-list-footer.test.tsx index a6d89f17a8..a48389711b 100644 --- a/apps/web/components/task/chat/message-list-footer.test.tsx +++ b/apps/web/components/task/chat/message-list-footer.test.tsx @@ -12,15 +12,29 @@ vi.mock("@/components/task/chat/message-renderer", () => ({ ), })); +let mockResumeSkippedSessionIds: Record = {}; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: ( + selector: (state: { tasks: { resumeSkippedSessionIds: Record } }) => unknown, + ) => selector({ tasks: { resumeSkippedSessionIds: mockResumeSkippedSessionIds } }), +})); + +vi.mock("@/components/task/chat/session-resume-start-button", () => ({ + SessionResumeStartButton: () =>
Start agent
, +})); + import { MessageListFooter } from "./message-list-footer"; +const AGENT_STATUS_TEST_ID = "agent-status"; +const SESSION_ID = "session-1"; +const RESUME_BUTTON_TEST_ID = "resume-start-button"; + afterEach(cleanup); -const AGENT_STATUS_TEST_ID = "agent-status"; - const actionableFailure = { id: "failure-1", - session_id: toSessionId("session-1"), + session_id: toSessionId(SESSION_ID), task_id: toTaskId("task-1"), author_type: "agent", type: "status", @@ -49,7 +63,7 @@ describe("MessageListFooter", () => { render( , @@ -60,7 +74,7 @@ describe("MessageListFooter", () => { }); it("keeps the generic status for a failed session without an actionable footer", () => { - render(); + render(); expect(screen.getByTestId(AGENT_STATUS_TEST_ID)).toBeTruthy(); }); @@ -69,7 +83,7 @@ describe("MessageListFooter", () => { render( , @@ -80,14 +94,14 @@ describe("MessageListFooter", () => { it("switches ownership when missing-branch recovery arrives after failure", () => { const { rerender } = render( - , + , ); expect(screen.getByTestId(AGENT_STATUS_TEST_ID)).toBeTruthy(); rerender( , @@ -101,7 +115,7 @@ describe("MessageListFooter", () => { render( , @@ -111,3 +125,85 @@ describe("MessageListFooter", () => { expect(screen.queryByTestId("action-message")).toBeNull(); }); }); + +const recoveryMessage = { + id: "recovery-1", + session_id: toSessionId("session-1"), + task_id: toTaskId("task-1"), + author_type: "agent", + type: "status", + created_at: "2026-07-22T00:00:00Z", + content: "Agent process exited with code 1", + metadata: { + variant: "danger", + recovery_actions: true, + actions: [ + { type: "resume_session", label: "Resume session" }, + { type: "start_fresh", label: "Start fresh session" }, + ], + }, +} satisfies Message; + +describe("MessageListFooter resume-skipped start button", () => { + const withMessages = [actionableFailure]; + + it("renders the Start agent button for a resume-skipped session with messages", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.getByTestId(RESUME_BUTTON_TEST_ID)).toBeTruthy(); + }); + + it("hides the Start agent button for a resume-skipped FAILED session (recovery owns the affordance)", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.queryByTestId(RESUME_BUTTON_TEST_ID)).toBeNull(); + }); + + it("renders the Start agent button for an empty resume-skipped session (empty description fallback)", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.getByTestId(RESUME_BUTTON_TEST_ID)).toBeTruthy(); + }); + + it("hides the Start agent button when recovery actions are already visible", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.queryByTestId(RESUME_BUTTON_TEST_ID)).toBeNull(); + }); + + it("renders the Start agent button when no recovery actions are visible", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.getByTestId(RESUME_BUTTON_TEST_ID)).toBeTruthy(); + }); + + it("hides the Start agent button for a resume-skipped RUNNING session", () => { + mockResumeSkippedSessionIds = { [SESSION_ID]: true }; + render( + , + ); + expect(screen.queryByTestId(RESUME_BUTTON_TEST_ID)).toBeNull(); + }); +}); diff --git a/apps/web/components/task/chat/message-list-footer.tsx b/apps/web/components/task/chat/message-list-footer.tsx index 68acf52e4c..243e25a74b 100644 --- a/apps/web/components/task/chat/message-list-footer.tsx +++ b/apps/web/components/task/chat/message-list-footer.tsx @@ -1,8 +1,11 @@ "use client"; +import { useMemo } from "react"; import type { Message, TaskSessionState } from "@/lib/types/http"; import { AgentStatus } from "@/components/task/chat/messages/agent-status"; import { MessageRenderer } from "@/components/task/chat/message-renderer"; +import { SessionResumeStartButton } from "@/components/task/chat/session-resume-start-button"; +import { useAppStore } from "@/components/state-provider"; type MessageListFooterProps = { sessionState?: TaskSessionState; @@ -49,6 +52,39 @@ export function MessageListFooter({ const visibleFooterActionMessages = footerActionMessages.filter( (message) => !isMissingBranchFailure(message) || message.id === currentActionableFailure?.id, ); + // The task-description start button only renders for EMPTY sessions. A + // resume-skipped session (prevent-auto-start-on-open preference, agent + // stopped with history) gets its Start agent button here instead — but only + // when no recovery actions are already visible: if the conversation shows + // "Resume session" / "Start fresh session" (an agent-kill recovery action + // message), that is the manual affordance and a second Start agent button + // would be duplicate noise. + const resumeSkipped = useAppStore((state) => + sessionId ? state.tasks.resumeSkippedSessionIds[sessionId] === true : false, + ); + const hasRecoveryActions = useMemo( + () => + messages.some( + (message) => + (message.metadata as Record | undefined)?.recovery_actions === true, + ) || + footerActionMessages.some( + (message) => + (message.metadata as Record | undefined)?.recovery_actions === true, + ), + [messages, footerActionMessages], + ); + // The footer is the single Start-agent surface for resume-skipped sessions + // (prevent-auto-start-on-open): it must render even when the session has + // no messages or the task has no description, so every gated recovered-idle + // session keeps the manual affordance. + const showResumeStartButton = + resumeSkipped && + !hasRecoveryActions && + sessionState !== "FAILED" && + sessionState !== "RUNNING" && + sessionState !== "STARTING" && + sessionId !== null; return ( <> {!recoveryOwnsFailure && ( @@ -59,6 +95,9 @@ export function MessageListFooter({ isWorking={isWorking} /> )} + {showResumeStartButton && sessionId !== null && ( + + )} {visibleFooterActionMessages.map((message) => ( ))} diff --git a/apps/web/components/task/chat/message-renderer.test.ts b/apps/web/components/task/chat/message-renderer.test.ts new file mode 100644 index 0000000000..5085d5747a --- /dev/null +++ b/apps/web/components/task/chat/message-renderer.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { shouldShowDescriptionStartButton } from "./message-renderer"; + +const TASK_ID = "t1"; +const SESSION_ID = "s1"; +const CREATED_STATE = "CREATED"; + +describe("shouldShowDescriptionStartButton", () => { + it("shows for a never-started (CREATED) session", () => { + expect( + shouldShowDescriptionStartButton({ + sessionState: CREATED_STATE, + taskState: "CREATED", + taskId: TASK_ID, + sessionId: SESSION_ID, + }), + ).toBe(true); + }); + + it("does NOT show for a resume-skipped session (the footer owns that surface)", () => { + expect( + shouldShowDescriptionStartButton({ + sessionState: "WAITING_FOR_INPUT", + taskState: "CREATED", + taskId: TASK_ID, + sessionId: SESSION_ID, + }), + ).toBe(false); + }); + + it("does NOT show for a FAILED session (recovery owns the affordance)", () => { + expect( + shouldShowDescriptionStartButton({ + sessionState: "FAILED", + taskState: "CREATED", + taskId: TASK_ID, + sessionId: SESSION_ID, + }), + ).toBe(false); + }); + + it("hides while the task is SCHEDULING", () => { + expect( + shouldShowDescriptionStartButton({ + sessionState: CREATED_STATE, + taskState: "SCHEDULING", + taskId: TASK_ID, + sessionId: SESSION_ID, + }), + ).toBe(false); + }); + + it("hides when no task/session context is bound", () => { + expect( + shouldShowDescriptionStartButton({ + sessionState: CREATED_STATE, + taskState: "CREATED", + taskId: undefined, + sessionId: undefined, + }), + ).toBe(false); + }); +}); diff --git a/apps/web/components/task/chat/message-renderer.tsx b/apps/web/components/task/chat/message-renderer.tsx index 61aecba546..262f174bbb 100644 --- a/apps/web/components/task/chat/message-renderer.tsx +++ b/apps/web/components/task/chat/message-renderer.tsx @@ -3,10 +3,15 @@ import { memo, useState, useCallback, type ReactElement } from "react"; import { IconPlayerPlay } from "@tabler/icons-react"; import { Button } from "@kandev/ui/button"; +import { sessionId as toSessionId, taskId as toTaskId } from "@/lib/types/http"; import type { Message, TaskSessionState } from "@/lib/types/http"; import type { ToolCallMetadata } from "@/components/task/chat/types"; import { launchSession } from "@/lib/services/session-launch-service"; -import { buildStartCreatedRequest } from "@/lib/services/session-launch-helpers"; +import { isLaunchStateRegression } from "@/lib/session-state"; +import { + buildResumeRequest, + buildStartCreatedRequest, +} from "@/lib/services/session-launch-helpers"; import { useAppStore } from "@/components/state-provider"; import { useTask } from "@/hooks/use-task"; import { ChatMessage } from "@/components/task/chat/messages/chat-message"; @@ -45,24 +50,81 @@ type AdapterContext = { isContainingTurnActive?: boolean; }; +/** + * Decides whether the task-description message renders the Start agent + * button. Shown only for never-started (CREATED) sessions; resume-skipped + * (prevent-auto-start-on-open) sessions get their Start agent button from + * the message-list footer instead (which also covers empty sessions and + * empty descriptions). Hidden while the task is SCHEDULING (the launch is + * in flight) and when no task/session context is bound. + */ +export function shouldShowDescriptionStartButton({ + sessionState, + taskState, + taskId, + sessionId, +}: { + sessionState: TaskSessionState | undefined; + taskState?: string; + taskId?: string; + sessionId?: string; +}): boolean { + return sessionState === "CREATED" && taskState !== "SCHEDULING" && !!taskId && !!sessionId; +} + function TaskDescriptionStartButton({ taskId, sessionId }: { taskId: string; sessionId: string }) { const { t } = useTranslation(); const [isStarting, setIsStarting] = useState(false); const prepareStatus = useAppStore( (state) => state.prepareProgress.bySessionId[sessionId]?.status ?? null, ); + const resumeSkipped = useAppStore( + (state) => state.tasks.resumeSkippedSessionIds[sessionId] === true, + ); + const setResumeSkipped = useAppStore((state) => state.setResumeSkipped); + const session = useAppStore((state) => state.taskSessions.items[sessionId] ?? null); + const setTaskSession = useAppStore((state) => state.setTaskSession); const handleStart = useCallback(async () => { setIsStarting(true); try { - const { request } = buildStartCreatedRequest(taskId, sessionId); - await launchSession(request); + // Never-started (CREATED) sessions use the start_created intent; a + // resume-skipped (recovered-idle) session resumes its existing agent. + const { request } = resumeSkipped + ? buildResumeRequest(taskId, sessionId) + : buildStartCreatedRequest(taskId, sessionId); + const response = await launchSession(request); + if (response.success && response.state) { + // Hydrate the launch state (commonly STARTING) so the button hides + // immediately and repeated start_created/resume requests cannot fire + // against an already-starting session before the WS transition lands. + // Never apply it over a newer live state: a WS RUNNING/FAILED + // transition can land before the launch response resolves, and the + // delayed STARTING must not hide a running agent or a failure's + // recovery affordances. + if (!isLaunchStateRegression(session?.state, response.state)) { + setTaskSession({ + id: toSessionId(sessionId), + task_id: toTaskId(taskId), + state: response.state as TaskSessionState, + started_at: session?.started_at ?? "", + updated_at: session?.updated_at ?? "", + }); + } + } + // Only confirmed RUNNING clears the resume-skipped marker: a resume + // response commonly reports STARTING (launch accepted, agent starting), + // and the WS RUNNING transition clears it later. Failed launches keep + // the button as a retry affordance. + if (response.state === "RUNNING") { + setResumeSkipped(sessionId, false); + } } catch (error) { console.error("Failed to start agent:", error); } finally { setIsStarting(false); } - }, [taskId, sessionId]); + }, [taskId, sessionId, resumeSkipped, setResumeSkipped, session, setTaskSession]); // Hide while environment is being prepared if (prepareStatus === "preparing") return null; @@ -132,8 +194,12 @@ function TaskDescriptionMessage({ /> ); } - const showStartButton = - sessionState === "CREATED" && task?.state !== "SCHEDULING" && !!taskId && !!sessionId; + const showStartButton = shouldShowDescriptionStartButton({ + sessionState, + taskState: task?.state, + taskId, + sessionId, + }); return ( <> state.taskSessions.items[sessionId] ?? null); + const setTaskSession = useAppStore((state) => state.setTaskSession); + const setResumeSkipped = useAppStore((state) => state.setResumeSkipped); + + const handleStart = useCallback(async () => { + if (!session) return; + setIsStarting(true); + try { + const { request } = buildResumeRequest(session.task_id, sessionId); + const response = await launchSession(request); + if (response.success && response.state) { + // Hydrate the launch state (commonly STARTING) so the button hides + // immediately and the UI reflects the in-flight resume instead of + // staying stopped and clickable for repeated resumes. Never apply it + // over a newer live state: a WS RUNNING/FAILED transition can land + // before the launch response resolves, and the delayed STARTING must + // not hide a running agent or a failure's recovery affordances. + if (!isLaunchStateRegression(session.state, response.state)) { + setTaskSession({ + id: session.id, + task_id: session.task_id, + state: response.state as TaskSessionState, + started_at: session.started_at ?? "", + updated_at: session.updated_at ?? "", + }); + } + } + // Only confirmed RUNNING clears the resume-skipped marker: a resume + // response commonly reports STARTING (launch accepted, agent starting), + // and the WS RUNNING transition clears it later. Failed launches keep + // the button as a retry affordance. + if (response.state === "RUNNING") { + setResumeSkipped(sessionId, false); + } + } catch (error) { + console.error("Failed to resume agent:", error); + } finally { + setIsStarting(false); + } + }, [session, sessionId, setTaskSession, setResumeSkipped]); + + return ( +
+ +
+ ); +} diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts index bceafecc4b..88e5fa94cf 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts +++ b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts @@ -348,6 +348,7 @@ function buildKanbanTaskUpsert( id: task.id, parentTaskId: task.parent_id ?? undefined, workspaceMode: workspaceModeFromMetadata(task.metadata), + workflowId: task.workflow_id, workflowStepId: task.workflow_step_id, title: task.title, description: task.description, diff --git a/apps/web/components/task/recent-task-switcher-model.test.ts b/apps/web/components/task/recent-task-switcher-model.test.ts index c2d4a472df..fa512f3879 100644 --- a/apps/web/components/task/recent-task-switcher-model.test.ts +++ b/apps/web/components/task/recent-task-switcher-model.test.ts @@ -81,6 +81,7 @@ function buildContext(): RecentTaskBuildContext { kanbanTasks: [ { id: CURRENT_TASK_ID, + workflowId: WF_MAIN, workflowStepId: "step-1", title: "Current live title", position: 0, @@ -100,6 +101,7 @@ function buildContext(): RecentTaskBuildContext { tasks: [ { id: PREVIOUS_TASK_ID, + workflowId: WF_REVIEW, workflowStepId: "step-2", title: "Previous live title", position: 0, diff --git a/apps/web/components/task/task-archive-confirm-dialog.test.tsx b/apps/web/components/task/task-archive-confirm-dialog.test.tsx index 204aed4ac8..30ca6cc1f9 100644 --- a/apps/web/components/task/task-archive-confirm-dialog.test.tsx +++ b/apps/web/components/task/task-archive-confirm-dialog.test.tsx @@ -39,6 +39,7 @@ function renderWithTasks(ui: ReactNode, tasks: SeedTask[], confirmTaskArchive = steps: [], tasks: tasks.map((t) => ({ id: t.id, + workflowId: "wf-1", workflowStepId: "step-1", title: t.id, position: 0, diff --git a/apps/web/components/task/task-delete-confirm-dialog.test.tsx b/apps/web/components/task/task-delete-confirm-dialog.test.tsx index 968c5b80fc..3266555e9a 100644 --- a/apps/web/components/task/task-delete-confirm-dialog.test.tsx +++ b/apps/web/components/task/task-delete-confirm-dialog.test.tsx @@ -25,6 +25,7 @@ function renderDialog(ui: ReactNode, tasks: SeedTask[] = []) { steps: [], tasks: tasks.map((t) => ({ id: t.id, + workflowId: "wf-1", workflowStepId: "step-1", title: t.id, position: 0, diff --git a/apps/web/components/task/task-page-content.tsx b/apps/web/components/task/task-page-content.tsx index 1e30442736..e1966d3291 100644 --- a/apps/web/components/task/task-page-content.tsx +++ b/apps/web/components/task/task-page-content.tsx @@ -273,7 +273,11 @@ function useTaskPageData( const { task, taskLoadError, onTaskUnarchived } = useTaskDetails(activeTaskId, initialTask); const agent = useSessionAgent(task); - const ensureSession = useEnsureTaskSession(task); + const ensureSession = useEnsureTaskSession({ + id: task?.id, + workflowStepId: task?.workflow_step_id, + workflowId: task?.workflow_id, + }); const initialSessionId = sessionId ?? agent.taskSessionId ?? null; const effectiveSessionId = validatedActiveSessionId ?? initialSessionId; diff --git a/apps/web/e2e/fixtures/test-base.ts b/apps/web/e2e/fixtures/test-base.ts index f8a56ee7bd..52fd85f3f9 100644 --- a/apps/web/e2e/fixtures/test-base.ts +++ b/apps/web/e2e/fixtures/test-base.ts @@ -215,6 +215,10 @@ export const test = backendFixture.extend< kanban_view_mode: "", // Keep startup routing deterministic for tests that open bare home. startup_page: "task_overview", + // Reset to the default (off). Prevent-auto-start tests flip this via + // saveUserSettings; without this reset it would leak into unrelated + // tests running later in the same worker. + prevent_auto_start_agent_on_open: false, // Reset to the default (off). Anchored-bar tests flip this via // saveUserSettings; without this reset it would leak into unrelated // tests running later in the same worker. diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index bc8b48916f..e9a6764f59 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -702,13 +702,20 @@ export class ApiClient { workflowId: string, name: string, position: number, - opts?: { is_start_step?: boolean }, + opts?: { + is_start_step?: boolean; + events?: { + on_enter?: Array<{ type: string; config?: Record }>; + on_turn_complete?: Array<{ type: string; config?: Record }>; + }; + }, ): Promise<{ id: string }> { return this.request("POST", `/api/v1/workflow/steps`, { workflow_id: workflowId, name, position, ...(opts?.is_start_step != null ? { is_start_step: opts.is_start_step } : {}), + ...(opts?.events != null ? { events: opts.events } : {}), }); } @@ -928,6 +935,7 @@ export class ApiClient { async saveUserSettings(settings: { enable_preview_on_click?: boolean; confirm_task_archive?: boolean; + prevent_auto_start_agent_on_open?: boolean; unread_divider?: boolean; agent_generated_task_titles?: boolean; mcp_task_agent_profile_default?: MCPTaskAgentProfileDefault; diff --git a/apps/web/e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts b/apps/web/e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts new file mode 100644 index 0000000000..f36a045044 --- /dev/null +++ b/apps/web/e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts @@ -0,0 +1,57 @@ +import { test, expect } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +// Mobile variant of the final-step gate: the gating hooks run on mobile +// through the shared responsive TaskPageContent, so the Start agent button +// must appear on a phone viewport too. Mirrors mobile-general-settings.spec.ts. + +test.describe("Mobile prevent auto-start on open", () => { + test("final-step task with no session opens with the Start agent button when the preference is on", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + await testPage.setViewportSize({ width: 390, height: 844 }); + const finalStep = await apiClient.createWorkflowStep( + seedData.workflowId, + "Prevent AutoStart Mobile Done", + 7, + { events: { on_enter: [{ type: "auto_start_agent" }] } }, + ); + let taskId: string | undefined; + try { + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: true }); + const task = await apiClient.createTask( + seedData.workspaceId, + "Prevent AutoStart Mobile Task", + { + description: "Prevent auto-start on open final step task", + workflow_id: seedData.workflowId, + workflow_step_id: finalStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }, + ); + taskId = task.id; + + await testPage.goto(`/t/${task.id}`); + + const startButton = testPage.getByTestId("task-description-start-button"); + await expect(startButton).toBeVisible({ timeout: 30_000 }); + await expect(testPage.getByText("Started agent", { exact: false })).toHaveCount(0); + + await startButton.click(); + const session = new SessionPage(testPage); + await expect(testPage.getByText("Started agent", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await session.sendMessageViaButton("/e2e:simple-message"); + await session.expectChatResponseVisible("simple mock response", 0, { timeout: 30_000 }); + } finally { + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: false }); + if (taskId) await apiClient.deleteTask(taskId); + await apiClient.deleteWorkflowStep(finalStep.id); + } + }); +}); diff --git a/apps/web/e2e/tests/settings/prevent-auto-start-on-open.spec.ts b/apps/web/e2e/tests/settings/prevent-auto-start-on-open.spec.ts new file mode 100644 index 0000000000..e31b2f73d6 --- /dev/null +++ b/apps/web/e2e/tests/settings/prevent-auto-start-on-open.spec.ts @@ -0,0 +1,175 @@ +import { test, expect, type Page } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +// --------------------------------------------------------------------------- +// Prevent agent auto-start on open (prevent_auto_start_agent_on_open). +// +// The final-step cases add a custom terminal step (on_enter auto_start_agent) +// to the SEEDED (active) workflow: the task page hydrates state.kanban.steps +// for the active workflow via SSR, so the frontend gate resolves the step +// list without board-side multi-workflow snapshots. Each test deletes its +// task and step in teardown so the seeded workflow stays pristine for the +// next test in the same worker. +// --------------------------------------------------------------------------- + +async function openTaskSession(page: Page, title: string): Promise { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { KanbanPage } = await import("../../pages/kanban-page"); + const kanban = new KanbanPage(page); + await kanban.goto(); + + const card = kanban.taskCardByTitle(title); + await expect(card).toBeVisible({ timeout: 15_000 }); + await card.click(); + await expect(page).toHaveURL(/\/t\//, { timeout: 15_000 }); + + const session = new SessionPage(page); + await session.waitForLoad(); + return session; +} + +test.describe("Prevent auto-start on open", () => { + test("final-step task with no session opens with the Start agent button when the preference is on", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + const finalStep = await apiClient.createWorkflowStep( + seedData.workflowId, + "Prevent AutoStart Done", + 7, + { events: { on_enter: [{ type: "auto_start_agent" }] } }, + ); + let taskId: string | undefined; + try { + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: true }); + const task = await apiClient.createTask( + seedData.workspaceId, + "Prevent AutoStart Final Step Task", + { + description: "Prevent auto-start on open final step task", + workflow_id: seedData.workflowId, + workflow_step_id: finalStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }, + ); + taskId = task.id; + + await testPage.goto(`/t/${task.id}`); + + // The preference keeps the agent stopped and renders the Start agent + // button (session created in the prepared/CREATED state). + const startButton = testPage.getByTestId("task-description-start-button"); + await expect(startButton).toBeVisible({ timeout: 30_000 }); + await expect(testPage.getByText("Started agent", { exact: false })).toHaveCount(0); + + // Clicking the button starts the agent, which then answers prompts. + await startButton.click(); + const session = new SessionPage(testPage); + await expect(testPage.getByText("Started agent", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await session.sendMessage("/e2e:simple-message"); + await session.expectChatResponseVisible("simple mock response", 0, { timeout: 30_000 }); + } finally { + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: false }); + if (taskId) await apiClient.deleteTask(taskId); + await apiClient.deleteWorkflowStep(finalStep.id); + } + }); + + test("final-step task auto-starts on open when the preference is off (control)", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + const finalStep = await apiClient.createWorkflowStep( + seedData.workflowId, + "Prevent AutoStart Ctrl Done", + 8, + { events: { on_enter: [{ type: "auto_start_agent" }] } }, + ); + let taskId: string | undefined; + try { + const task = await apiClient.createTask( + seedData.workspaceId, + "Prevent AutoStart Control Task", + { + description: "Prevent auto-start on open final step task", + workflow_id: seedData.workflowId, + workflow_step_id: finalStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }, + ); + taskId = task.id; + + await testPage.goto(`/t/${task.id}`); + + // Default behavior: the agent auto-starts and no Start button is shown. + const session = new SessionPage(testPage); + await session.waitForLoad(); + await expect(testPage.getByText("Started agent", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await expect(testPage.getByTestId("task-description-start-button")).toHaveCount(0); + } finally { + if (taskId) await apiClient.deleteTask(taskId); + await apiClient.deleteWorkflowStep(finalStep.id); + } + }); + + test("post-restart session does not auto-resume when the preference is on", async ({ + testPage, + apiClient, + seedData, + backend, + }) => { + test.setTimeout(180_000); + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: true }); + try { + await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Prevent AutoStart Resume Task", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + + // Let the agent finish its first turn so the session ends idle with a + // resume token (the post-restart needs_resume shape). + const session = await openTaskSession(testPage, "Prevent AutoStart Resume Task"); + await expect(session.chat.getByText("simple mock response", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await session.waitForChatIdle({ timeout: 15_000 }); + + // Restart the backend and reload — the resume-skipped gate must keep + // the agent stopped and render the Start agent button instead. + await backend.restart(); + await testPage.reload(); + await session.waitForLoad(); + + const startButton = testPage.getByTestId("session-resume-start-button"); + await expect(startButton).toBeVisible({ timeout: 60_000 }); + await expect(testPage.getByText("Resumed agent", { exact: false })).toHaveCount(0); + + // Manual start resumes the agent and it keeps working. + await startButton.click(); + await expect(testPage.getByText("Resumed agent", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await session.sendMessage("/e2e:simple-message"); + await session.expectChatResponseVisible("simple mock response", 0, { timeout: 30_000 }); + } finally { + await apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: false }); + } + }); +}); diff --git a/apps/web/hooks/domains/github/use-pr-review-repository-identity.test.tsx b/apps/web/hooks/domains/github/use-pr-review-repository-identity.test.tsx index b36a76ece7..3409ea0c3b 100644 --- a/apps/web/hooks/domains/github/use-pr-review-repository-identity.test.tsx +++ b/apps/web/hooks/domains/github/use-pr-review-repository-identity.test.tsx @@ -81,6 +81,7 @@ const initialState: Partial = { tasks: [ { id: TASK_ID, + workflowId: "wf-1", workflowStepId: "step-1", title: "Multi-PR task", position: 0, diff --git a/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts b/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts index 2747c47284..d333abc5c6 100644 --- a/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts +++ b/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts @@ -105,6 +105,13 @@ async function fetchAndWriteSnapshot( `[useAllWorkflowSnapshots] Failed to fetch snapshot for workflow "${wf.name}" (${wf.id}):`, err, ); + // A failed fetch must not leave a placeholder permanently "unknown": that + // would block the final-step ensure forever. Transition to an explicit + // known-but-empty state so the ensure proceeds ungated (safe default). + const current = store.getState().kanbanMulti.snapshots[wf.id]; + if (current?.isPlaceholder) { + store.getState().setWorkflowSnapshot(wf.id, { ...current, isPlaceholder: false }); + } } } diff --git a/apps/web/hooks/domains/kanban/use-kanban-actions.ts b/apps/web/hooks/domains/kanban/use-kanban-actions.ts index e70d2ed613..c07efa2bcf 100644 --- a/apps/web/hooks/domains/kanban/use-kanban-actions.ts +++ b/apps/web/hooks/domains/kanban/use-kanban-actions.ts @@ -54,6 +54,7 @@ function hydrateCreatedTask( ...currentKanban.tasks, { id: task.id, + workflowId: task.workflow_id, workflowStepId: task.workflow_step_id, title: task.title, description: task.description ?? undefined, diff --git a/apps/web/hooks/domains/session/use-ensure-task-session.test.ts b/apps/web/hooks/domains/session/use-ensure-task-session.test.ts index 9ffa565d37..5b534d863b 100644 --- a/apps/web/hooks/domains/session/use-ensure-task-session.test.ts +++ b/apps/web/hooks/domains/session/use-ensure-task-session.test.ts @@ -13,17 +13,44 @@ let mockSessionsResult: { loadSessions: mockLoadSessions, }; +let mockStoreState: { + userSettings: { preventAutoStartAgentOnOpen: boolean }; + kanban: { + workflowId: string | null; + steps: Array<{ id: string; position: number }>; + isLoading: boolean; + }; + kanbanMulti: { + snapshots: Record< + string, + { steps: Array<{ id: string; position: number }>; isPlaceholder?: boolean } + >; + }; +} = { + userSettings: { preventAutoStartAgentOnOpen: false }, + kanban: { workflowId: "wf-active", steps: [], isLoading: false }, + kanbanMulti: { snapshots: {} }, +}; + vi.mock("@/lib/services/session-launch-service", () => ({ - ensureTaskSession: (taskId: string) => mockEnsureTaskSession(taskId), + ensureTaskSession: (taskId: string, opts?: { autoStart?: boolean }) => + mockEnsureTaskSession(taskId, opts), })); vi.mock("@/hooks/use-task-sessions", () => ({ useTaskSessions: () => mockSessionsResult, })); -import { useEnsureTaskSession } from "./use-ensure-task-session"; +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: typeof mockStoreState) => unknown) => selector(mockStoreState), +})); + +import { useEnsureTaskSession, isFinalWorkflowStep } from "./use-ensure-task-session"; const TASK = { id: "task-1" }; +const OTHER_DONE_STEP = "other-done"; +const OTHER_STEP = "other-step"; +const OTHER_WORKFLOW = "wf-other"; function flushMicrotasks() { return act(() => Promise.resolve()); @@ -33,6 +60,11 @@ function resetEnsureTaskSessionMocks() { vi.clearAllMocks(); mockLoadSessions.mockResolvedValue(undefined); mockSessionsResult = { sessions: [], isLoaded: true, loadSessions: mockLoadSessions }; + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: false }, + kanban: { workflowId: "wf-active", steps: [], isLoading: false }, + kanbanMulti: { snapshots: {} }, + }; mockEnsureTaskSession.mockResolvedValue({ success: true, task_id: "task-1", @@ -50,7 +82,7 @@ describe("useEnsureTaskSession", () => { const { result } = renderHook(() => useEnsureTaskSession(TASK)); expect(mockEnsureTaskSession).toHaveBeenCalledTimes(1); - expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1"); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", undefined); expect(result.current.status).toBe("preparing"); await flushMicrotasks(); expect(result.current.status).toBe("idle"); @@ -155,6 +187,243 @@ describe("useEnsureTaskSession — task changes", () => { expect(mockEnsureTaskSession).toHaveBeenCalledTimes(1); rerender({ task: { id: "task-2" } }); expect(mockEnsureTaskSession).toHaveBeenCalledTimes(2); - expect(mockEnsureTaskSession).toHaveBeenLastCalledWith("task-2"); + expect(mockEnsureTaskSession).toHaveBeenLastCalledWith("task-2", undefined); + }); +}); + +describe("isFinalWorkflowStep", () => { + const steps = [ + { id: "a", position: 0 }, + { id: "b", position: 1 }, + { id: "c", position: 2 }, + ]; + + it("returns true for the max-position step", () => { + expect(isFinalWorkflowStep("c", steps)).toBe(true); + }); + + it("returns false for non-terminal steps", () => { + expect(isFinalWorkflowStep("a", steps)).toBe(false); + expect(isFinalWorkflowStep("b", steps)).toBe(false); + }); + + it("breaks position ties deterministically by max id", () => { + const tied = [ + { id: "early", position: 2 }, + { id: "late", position: 2 }, + ]; + expect(isFinalWorkflowStep("late", tied)).toBe(true); + expect(isFinalWorkflowStep("early", tied)).toBe(false); + }); + + it("treats missing step id or empty steps as not final", () => { + expect(isFinalWorkflowStep(undefined, steps)).toBe(false); + expect(isFinalWorkflowStep("c", [])).toBe(false); + expect(isFinalWorkflowStep("missing", steps)).toBe(false); + }); +}); + +// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability +describe("useEnsureTaskSession prevent-auto-start gate", () => { + it("requests autoStart:false for a final-step task when the preference is on", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + steps: [ + { id: "step-1", position: 0 }, + { id: "step-done", position: 1 }, + ], + isLoading: false, + }, + kanbanMulti: { snapshots: {} }, + }; + const { result } = renderHook(() => + useEnsureTaskSession({ id: "task-1", workflowStepId: "step-done", workflowId: "wf-active" }), + ); + await flushMicrotasks(); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", { autoStart: false }); + expect(result.current.status).toBe("idle"); + }); + + it("keeps the default ensure call for a non-final step even when the preference is on", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + steps: [ + { id: "step-1", position: 0 }, + { id: "step-done", position: 1 }, + ], + isLoading: false, + }, + kanbanMulti: { snapshots: {} }, + }; + renderHook(() => + useEnsureTaskSession({ id: "task-1", workflowStepId: "step-1", workflowId: "wf-active" }), + ); + await flushMicrotasks(); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", undefined); + }); + + it("does NOT gate a task whose workflow id is missing even when its step id matches the active workflow's terminal step", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + steps: [ + { id: "step-1", position: 0 }, + { id: "step-done", position: 1 }, + ], + isLoading: false, + }, + kanbanMulti: { snapshots: {} }, + }; + // No workflowId on the task: resolving against the active workflow's + // steps would gate a task whose own workflow is unknown, suppressing the + // auto-start the user expects. Missing workflow id → no gate. + renderHook(() => useEnsureTaskSession({ id: "task-1", workflowStepId: "step-done" })); + await flushMicrotasks(); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", undefined); + }); + + it("resolves the step list from the multi-workflow snapshot for a cross-workflow task", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + steps: [{ id: "active-step", position: 0 }], + isLoading: false, + }, + kanbanMulti: { + snapshots: { + [OTHER_WORKFLOW]: { + steps: [ + { id: OTHER_STEP, position: 0 }, + { id: OTHER_DONE_STEP, position: 1 }, + ], + }, + }, + }, + }; + renderHook(() => + useEnsureTaskSession({ + id: "task-2", + workflowStepId: OTHER_DONE_STEP, + workflowId: OTHER_WORKFLOW, + }), + ); + await flushMicrotasks(); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-2", { autoStart: false }); + }); + + it("does not gate when the preference is off", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: false }, + kanban: { + workflowId: "wf-active", + steps: [ + { id: "step-1", position: 0 }, + { id: "step-done", position: 1 }, + ], + isLoading: false, + }, + kanbanMulti: { snapshots: {} }, + }; + renderHook(() => + useEnsureTaskSession({ id: "task-1", workflowStepId: "step-done", workflowId: "wf-active" }), + ); + await flushMicrotasks(); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", undefined); + }); +}); + +describe("useEnsureTaskSession late step hydration", () => { + beforeEach(resetEnsureTaskSessionMocks); + + it("waits for the workflow steps before ensuring, then applies the gate", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + // Steps not yet hydrated — isLoading still true. + steps: [], + isLoading: true, + }, + kanbanMulti: { snapshots: {} }, + }; + const { rerender } = renderHook(() => + useEnsureTaskSession({ id: "task-1", workflowStepId: "step-done", workflowId: "wf-active" }), + ); + await flushMicrotasks(); + // No ensure while the step list is unresolved. + expect(mockEnsureTaskSession).not.toHaveBeenCalled(); + + // Steps hydrate: the final step appears and loading completes. + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { + workflowId: "wf-active", + steps: [ + { id: "step-1", position: 0 }, + { id: "step-done", position: 1 }, + ], + isLoading: false, + }, + kanbanMulti: { snapshots: {} }, + }; + rerender(); + await flushMicrotasks(); + + // Exactly one ensure, gated: never an ungated call. + expect(mockEnsureTaskSession).toHaveBeenCalledTimes(1); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-1", { autoStart: false }); + }); +}); + +describe("useEnsureTaskSession placeholder snapshot", () => { + beforeEach(resetEnsureTaskSessionMocks); + + it("waits for the real snapshot when only a placeholder exists", async () => { + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { workflowId: "wf-active", steps: [], isLoading: false }, + kanbanMulti: { + snapshots: { + [OTHER_WORKFLOW]: { steps: [], isPlaceholder: true }, + }, + }, + }; + const { rerender } = renderHook(() => + useEnsureTaskSession({ + id: "task-2", + workflowStepId: OTHER_DONE_STEP, + workflowId: OTHER_WORKFLOW, + }), + ); + await flushMicrotasks(); + // A placeholder snapshot must not satisfy stepsKnown — no ensure yet. + expect(mockEnsureTaskSession).not.toHaveBeenCalled(); + + // The real workflow snapshot arrives with the terminal step. + mockStoreState = { + userSettings: { preventAutoStartAgentOnOpen: true }, + kanban: { workflowId: "wf-active", steps: [], isLoading: false }, + kanbanMulti: { + snapshots: { + [OTHER_WORKFLOW]: { + steps: [ + { id: OTHER_STEP, position: 0 }, + { id: OTHER_DONE_STEP, position: 1 }, + ], + }, + }, + }, + }; + rerender(); + await flushMicrotasks(); + + expect(mockEnsureTaskSession).toHaveBeenCalledTimes(1); + expect(mockEnsureTaskSession).toHaveBeenCalledWith("task-2", { autoStart: false }); }); }); diff --git a/apps/web/hooks/domains/session/use-ensure-task-session.ts b/apps/web/hooks/domains/session/use-ensure-task-session.ts index 121fefc9e3..6bf0ab1a4e 100644 --- a/apps/web/hooks/domains/session/use-ensure-task-session.ts +++ b/apps/web/hooks/domains/session/use-ensure-task-session.ts @@ -1,12 +1,45 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ensureTaskSession } from "@/lib/services/session-launch-service"; import { useTaskSessions } from "@/hooks/use-task-sessions"; +import { useAppStore } from "@/components/state-provider"; /** Minimal task shape consumed by useEnsureTaskSession. */ export type EnsureTaskInput = { id?: string | null; + /** Snake_case workflow_step_id from the HTTP Task type. */ + workflowStepId?: string | null; + /** Snake_case workflow_id from the HTTP Task type. */ + workflowId?: string | null; } | null; +export type KanbanStepLike = { + id: string; + position: number; +}; + +/** + * Reports whether the step is the terminal step of its workflow. Terminal is + * the maximum under the `(position, id)` ordering (ties broken by max id): + * step positions are caller-supplied and not uniqueness-validated, so equal + * positions are representable and must not make both steps terminal. + * Missing step id or an empty step list → not final (no gate). + */ +export function isFinalWorkflowStep( + workflowStepId: string | null | undefined, + steps: KanbanStepLike[] | undefined, +): boolean { + if (!workflowStepId || !steps || steps.length === 0) return false; + const current = steps.find((s) => s.id === workflowStepId); + if (!current) return false; + const terminal = steps.reduce((best, step) => { + if (!best) return step; + if (step.position > best.position) return step; + if (step.position === best.position && step.id > best.id) return step; + return best; + }, null); + return terminal?.id === current.id; +} + export type EnsureTaskSessionStatus = "idle" | "preparing" | "error"; export type UseEnsureTaskSessionResult = { @@ -28,6 +61,78 @@ export type UseEnsureTaskSessionResult = { * - No-op when `enabled === false` or `task.id` is missing. * - Idempotent per task id within a mount; switching tasks resets the latch. */ +/** + * Resolves the task's workflow step list and final-step decision for the + * prevent-auto-start gate. Workflow-aware: the active workflow's steps + * (state.kanban.steps) when the task is in it, otherwise the multi-workflow + * snapshot's steps. `stepsKnown` is false only while the ACTIVE workflow's + * steps are still hydrating (loading, empty) — callers must wait before + * ensuring, or a final-step task would auto-start. Non-active workflows + * without a snapshot never resolve here (documented safe default: no gate). + */ +function resolveWorkflowSteps( + snapshot: { steps: KanbanStepLike[]; isPlaceholder?: boolean } | undefined, + taskWorkflowId: string | null, + kanbanWorkflowId: string | null, + kanbanSteps: KanbanStepLike[], +): KanbanStepLike[] { + // The ACTIVE workflow's steps always come from state.kanban.steps: WS + // step events (workflow.step.created/updated) only mutate that list, so a + // multi-workflow snapshot for the active workflow can be stale and miss a + // freshly-added terminal step, which would bypass the final-step gate. + if (taskWorkflowId === null || taskWorkflowId === kanbanWorkflowId) return kanbanSteps; + if (snapshot !== undefined) return snapshot.steps; + return []; +} + +function resolveStepsKnown( + snapshot: { steps: KanbanStepLike[]; isPlaceholder?: boolean } | undefined, + taskWorkflowId: string | null, + kanbanWorkflowId: string | null, + kanbanSteps: KanbanStepLike[], + kanbanLoading: boolean, +): boolean { + if (taskWorkflowId === null || taskWorkflowId === kanbanWorkflowId) { + return kanbanSteps.length > 0 || !kanbanLoading; + } + if (snapshot !== undefined) { + // A placeholder snapshot (created by a task event before the real + // workflow snapshot arrives) carries empty steps — it must NOT satisfy + // stepsKnown, or the ungated ensure would latch before the real steps + // hydrate. + return snapshot.isPlaceholder !== true; + } + // Non-active workflow with no snapshot: safe default (no gate), never wait. + return true; +} + +export function resolveFinalStepInfo( + task: EnsureTaskInput, + kanbanWorkflowId: string | null, + kanbanSteps: KanbanStepLike[], + kanbanLoading: boolean, + snapshots: Record, +): { isFinalStep: boolean; stepsKnown: boolean } { + const workflowStepId = task?.workflowStepId ?? null; + const taskWorkflowId = task?.workflowId ?? null; + // A task whose own workflow is unknown must never resolve against another + // workflow's steps: if workflowStepId merely matches a terminal step of the + // ACTIVE workflow, gating would suppress auto-start for a task whose own + // workflow we cannot see. No workflow id → no gate. + if (!workflowStepId || !taskWorkflowId) return { isFinalStep: false, stepsKnown: true }; + const snapshot = taskWorkflowId ? snapshots[taskWorkflowId] : undefined; + const steps = resolveWorkflowSteps(snapshot, taskWorkflowId, kanbanWorkflowId, kanbanSteps); + const isFinalStep = isFinalWorkflowStep(workflowStepId, steps); + const stepsKnown = resolveStepsKnown( + snapshot, + taskWorkflowId, + kanbanWorkflowId, + kanbanSteps, + kanbanLoading, + ); + return { isFinalStep, stepsKnown }; +} + export function useEnsureTaskSession( task: EnsureTaskInput, opts?: { enabled?: boolean }, @@ -40,6 +145,24 @@ export function useEnsureTaskSession( const [error, setError] = useState(null); const [retryToken, setRetryToken] = useState(0); + // Prevent-auto-start preference + workflow-aware step resolution. The + // terminal-step gate applies to the task's OWN workflow: the active + // workflow's steps (state.kanban.steps) when the task is in it, otherwise + // the multi-workflow snapshot's steps for that workflow. + const preventAutoStart = useAppStore((state) => state.userSettings.preventAutoStartAgentOnOpen); + const kanbanWorkflowId = useAppStore((state) => state.kanban.workflowId); + const kanbanSteps = useAppStore((state) => state.kanban.steps); + const kanbanLoading = useAppStore((state) => state.kanban.isLoading === true); + const snapshots = useAppStore((state) => state.kanbanMulti.snapshots); + + const { isFinalStep, stepsKnown } = useMemo( + () => + preventAutoStart + ? resolveFinalStepInfo(task, kanbanWorkflowId, kanbanSteps, kanbanLoading, snapshots) + : { isFinalStep: false, stepsKnown: true }, + [preventAutoStart, task, kanbanWorkflowId, kanbanSteps, kanbanLoading, snapshots], + ); + // Latch keyed by `${taskId}:${retryToken}` so a re-mount on the same task // doesn't refire, but switching tasks or calling retry() does. const launchedKeyRef = useRef(null); @@ -59,7 +182,11 @@ export function useEnsureTaskSession( useEffect(() => { if (!enabled || !taskId || !isLoaded) return; if (sessions.length > 0) return; - const key = `${taskId}:${retryToken}`; + // Wait for the workflow steps to resolve before deciding the gate. This + // branch does NOT latch, so a later steps hydration re-runs the effect + // with the correct isFinalStep value (fixes late-hydration auto-start). + if (preventAutoStart && !stepsKnown) return; + const key = `${taskId}:${retryToken}:${isFinalStep ? "gated" : "plain"}`; if (launchedKeyRef.current === key) return; launchedKeyRef.current = key; @@ -67,7 +194,10 @@ export function useEnsureTaskSession( let cancelled = false; setStatus("preparing"); setError(null); - ensureTaskSession(taskId) + const ensurePromise = isFinalStep + ? ensureTaskSession(taskId, { autoStart: false }) + : ensureTaskSession(taskId); + ensurePromise .then(async () => { if (cancelled || launchedKeyRef.current !== key) return; // Force-reload: backend may have returned an existing_* source our initial list missed. @@ -85,7 +215,17 @@ export function useEnsureTaskSession( return () => { cancelled = true; }; - }, [enabled, taskId, isLoaded, loadSessions, sessions.length, retryToken]); + }, [ + enabled, + taskId, + isLoaded, + loadSessions, + sessions.length, + retryToken, + preventAutoStart, + stepsKnown, + isFinalStep, + ]); /* eslint-enable react-hooks/set-state-in-effect */ const retry = useCallback(() => { diff --git a/apps/web/hooks/domains/session/use-session-resumption.test.ts b/apps/web/hooks/domains/session/use-session-resumption.test.ts index 6c0ffea059..02d02b0169 100644 --- a/apps/web/hooks/domains/session/use-session-resumption.test.ts +++ b/apps/web/hooks/domains/session/use-session-resumption.test.ts @@ -1,11 +1,14 @@ -import { renderHook, waitFor } from "@testing-library/react"; +import { act, renderHook, waitFor } from "@testing-library/react"; import { describe, it, expect, vi, beforeEach } from "vitest"; const mockRequest = vi.fn(); const mockSetTaskSession = vi.fn(); const mockSetSessionAgentctlStatus = vi.fn(); +const mockSetResumeSkipped = vi.fn(); let mockConnectionStatus = "connected"; -let mockSessionItems: Record = {}; +let mockPreventAutoStart = false; +let mockSessionItems: Record = + {}; vi.mock("@/lib/ws/connection", () => ({ getWebSocketClient: () => ({ request: mockRequest }), @@ -18,9 +21,23 @@ vi.mock("@/components/state-provider", () => ({ taskSessions: { items: mockSessionItems }, setTaskSession: mockSetTaskSession, setSessionAgentctlStatus: mockSetSessionAgentctlStatus, + setResumeSkipped: mockSetResumeSkipped, + userSettings: { preventAutoStartAgentOnOpen: mockPreventAutoStart }, + tasks: { resumeSkippedSessionIds: {} }, }), + useAppStoreApi: () => ({ + getState: () => ({ taskSessions: { items: mockSessionItems } }), + }), })); +const SESSION_ID = "s1"; +const TASK_ID = "t1"; +const FAILED_STATE = "FAILED"; +const LAUNCH_ACTION = "session.launch"; +const STATUS_ACTION = "task.session.status"; +const STARTED_AT = "2026-01-01T00:00:00.000Z"; +const LATER_AT = "2026-01-02T00:00:00.000Z"; + import { resumeWithSilentFallback, useSessionResumption, @@ -69,6 +86,7 @@ describe("resumeWithSilentFallback", () => { beforeEach(() => { vi.clearAllMocks(); mockConnectionStatus = "connected"; + mockPreventAutoStart = false; mockSessionItems = {}; // tryLaunch logs caught errors via console.error; silence in tests so the // expected error paths don't pollute the test output. @@ -78,20 +96,20 @@ describe("resumeWithSilentFallback", () => { it("uses resume on first try when it succeeds, never calling restore_workspace", async () => { mockRequest.mockResolvedValueOnce({ success: true, - task_id: "t1", - session_id: "s1", + task_id: TASK_ID, + session_id: SESSION_ID, state: "STARTING", worktree_path: "/wt/foo", worktree_branch: "feature/foo", }); const { setters, calls } = createSetters(); - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(mockRequest).toHaveBeenCalledTimes(1); expect(mockRequest).toHaveBeenCalledWith( - "session.launch", - expect.objectContaining({ intent: "resume", session_id: "s1" }), + LAUNCH_ACTION, + expect.objectContaining({ intent: "resume", session_id: SESSION_ID }), expect.any(Number), ); expect(calls.resumptionStates).toContain("resumed"); @@ -102,28 +120,28 @@ describe("resumeWithSilentFallback", () => { it("falls back to restore_workspace silently when resume returns success=false", async () => { // 1st call: resume fails. 2nd call: restore_workspace succeeds. mockRequest - .mockResolvedValueOnce({ success: false, task_id: "t1", state: "FAILED" }) + .mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE }) .mockResolvedValueOnce({ success: true, - task_id: "t1", - session_id: "s1", - state: "FAILED", + task_id: TASK_ID, + session_id: SESSION_ID, + state: FAILED_STATE, worktree_path: "/wt/foo", }); const { setters, calls } = createSetters(); - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(mockRequest).toHaveBeenCalledTimes(2); expect(mockRequest).toHaveBeenNthCalledWith( 1, - "session.launch", + LAUNCH_ACTION, expect.objectContaining({ intent: "resume" }), expect.any(Number), ); expect(mockRequest).toHaveBeenNthCalledWith( 2, - "session.launch", + LAUNCH_ACTION, expect.objectContaining({ intent: "restore_workspace" }), expect.any(Number), ); @@ -133,12 +151,15 @@ describe("resumeWithSilentFallback", () => { }); it("falls back to restore_workspace silently when resume throws", async () => { - mockRequest - .mockRejectedValueOnce(new Error("ws timeout")) - .mockResolvedValueOnce({ success: true, task_id: "t1", session_id: "s1", state: "FAILED" }); + mockRequest.mockRejectedValueOnce(new Error("ws timeout")).mockResolvedValueOnce({ + success: true, + task_id: TASK_ID, + session_id: SESSION_ID, + state: FAILED_STATE, + }); const { setters, calls } = createSetters(); - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(mockRequest).toHaveBeenCalledTimes(2); expect(calls.resumptionStates.at(-1)).toBe("resumed"); @@ -147,11 +168,11 @@ describe("resumeWithSilentFallback", () => { it("surfaces an error only when BOTH resume and restore_workspace fail", async () => { mockRequest - .mockResolvedValueOnce({ success: false, task_id: "t1", state: "FAILED" }) - .mockResolvedValueOnce({ success: false, task_id: "t1", state: "FAILED" }); + .mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE }) + .mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE }); const { setters, calls } = createSetters(); - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(mockRequest).toHaveBeenCalledTimes(2); expect(calls.resumptionStates.at(-1)).toBe("error"); @@ -166,7 +187,7 @@ describe("resumeWithSilentFallback", () => { .mockRejectedValueOnce(new Error("still closed")); const { setters, calls } = createSetters(); - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(mockRequest).toHaveBeenCalledTimes(2); expect(calls.resumptionStates.at(-1)).toBe("error"); @@ -177,35 +198,35 @@ describe("resumeWithSilentFallback", () => { it("seeds agentctl ready when restore_workspace fallback succeeds", async () => { mockRequest - .mockResolvedValueOnce({ success: false, task_id: "t1", state: "FAILED" }) + .mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE }) .mockResolvedValueOnce({ success: true, - task_id: "t1", - session_id: "s1", - state: "FAILED", + task_id: TASK_ID, + session_id: SESSION_ID, + state: FAILED_STATE, }); const { setters } = createSetters(); const setAgentctlReady = vi.fn(); setters.setAgentctlReady = setAgentctlReady; - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(setAgentctlReady).toHaveBeenCalledTimes(1); - expect(setAgentctlReady).toHaveBeenCalledWith("s1"); + expect(setAgentctlReady).toHaveBeenCalledWith(SESSION_ID); }); it("does not seed agentctl ready when resume succeeds (new execution will emit its own events)", async () => { mockRequest.mockResolvedValueOnce({ success: true, - task_id: "t1", - session_id: "s1", + task_id: TASK_ID, + session_id: SESSION_ID, state: "STARTING", }); const { setters } = createSetters(); const setAgentctlReady = vi.fn(); setters.setAgentctlReady = setAgentctlReady; - await resumeWithSilentFallback("t1", "s1", null, setters); + await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters); expect(setAgentctlReady).not.toHaveBeenCalled(); }); @@ -215,24 +236,25 @@ describe("useSessionResumption", () => { beforeEach(() => { vi.clearAllMocks(); mockConnectionStatus = "connected"; + mockPreventAutoStart = false; mockSessionItems = { s1: { - started_at: "2026-01-01T00:00:00.000Z", + started_at: STARTED_AT, }, }; }); it("does not mint client timestamps when status has no updated_at", async () => { mockRequest.mockResolvedValueOnce({ - session_id: "s1", - task_id: "t1", + session_id: SESSION_ID, + task_id: TASK_ID, state: "WAITING_FOR_INPUT", is_agent_running: false, is_resumable: false, needs_resume: false, }); - renderHook(() => useSessionResumption("t1", "s1")); + renderHook(() => useSessionResumption(TASK_ID, SESSION_ID)); await waitFor(() => expect(mockSetTaskSession).toHaveBeenCalled()); expect(mockSetTaskSession).toHaveBeenCalledWith(expect.objectContaining({ updated_at: "" })); @@ -241,8 +263,8 @@ describe("useSessionResumption", () => { it("refreshes the status and embedded editor capability after a successful resume", async () => { mockRequest .mockResolvedValueOnce({ - session_id: "s1", - task_id: "t1", + session_id: SESSION_ID, + task_id: TASK_ID, state: "WAITING_FOR_INPUT", is_agent_running: false, is_resumable: true, @@ -251,13 +273,13 @@ describe("useSessionResumption", () => { }) .mockResolvedValueOnce({ success: true, - task_id: "t1", - session_id: "s1", + task_id: TASK_ID, + session_id: SESSION_ID, state: "STARTING", }) .mockResolvedValueOnce({ - session_id: "s1", - task_id: "t1", + session_id: SESSION_ID, + task_id: TASK_ID, state: "STARTING", is_agent_running: true, is_resumable: false, @@ -265,14 +287,325 @@ describe("useSessionResumption", () => { capabilities: { embedded_vscode: true }, }); - const { result } = renderHook(() => useSessionResumption("t1", "s1")); + const { result } = renderHook(() => useSessionResumption(TASK_ID, SESSION_ID)); await waitFor(() => { expect(result.current.sessionStatus?.capabilities?.embedded_vscode).toBe(true); }); - expect(mockRequest).toHaveBeenLastCalledWith("task.session.status", { - task_id: "t1", - session_id: "s1", + expect(mockRequest).toHaveBeenLastCalledWith(STATUS_ACTION, { + task_id: TASK_ID, + session_id: SESSION_ID, }); }); }); + +describe("useSessionResumption prevent-auto-start gate", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockConnectionStatus = "connected"; + mockPreventAutoStart = true; + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: STARTED_AT, + state: "WAITING_FOR_INPUT", + }, + }; + }); + + it("skips the auto-resume, records the skip, and stays idle when the preference is on", async () => { + mockRequest.mockResolvedValueOnce({ + session_id: SESSION_ID, + task_id: TASK_ID, + state: "WAITING_FOR_INPUT", + is_agent_running: false, + is_resumable: true, + needs_resume: true, + updated_at: STARTED_AT, + }); + + const { result } = renderHook(() => useSessionResumption(TASK_ID, SESSION_ID)); + + await waitFor(() => { + expect(mockSetResumeSkipped).toHaveBeenCalledWith(SESSION_ID, true); + }); + // No resume/restore launch attempt happened. + const launchCalls = mockRequest.mock.calls.filter(([action]) => action === LAUNCH_ACTION); + expect(launchCalls).toHaveLength(0); + expect(result.current.resumptionState).toBe("idle"); + }); + + it("auto-resumes when the preference is off (unchanged behavior)", async () => { + mockPreventAutoStart = false; + mockRequest + .mockResolvedValueOnce({ + session_id: SESSION_ID, + task_id: TASK_ID, + state: "WAITING_FOR_INPUT", + is_agent_running: false, + is_resumable: true, + needs_resume: true, + updated_at: STARTED_AT, + }) + .mockResolvedValueOnce({ + success: true, + task_id: TASK_ID, + session_id: SESSION_ID, + state: "STARTING", + }); + + renderHook(() => useSessionResumption(TASK_ID, SESSION_ID)); + + await waitFor(() => { + expect(mockRequest).toHaveBeenCalledWith( + LAUNCH_ACTION, + expect.objectContaining({ session_id: SESSION_ID, intent: "resume" }), + expect.any(Number), + ); + }); + expect(mockSetResumeSkipped).not.toHaveBeenCalled(); + }); + + it("does not record the skip when the live session is already RUNNING (stale status race)", async () => { + // A status response taken before the agent started can arrive while the + // live row is RUNNING. The skip must not be recorded, or a Start button + // would appear beside a running agent. + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: LATER_AT, + state: "RUNNING", + }, + }; + mockRequest.mockResolvedValueOnce({ + session_id: SESSION_ID, + task_id: TASK_ID, + state: "IDLE", + is_agent_running: false, + is_resumable: true, + needs_resume: true, + updated_at: STARTED_AT, // older than the live RUNNING row + }); + + renderHook(() => useSessionResumption(TASK_ID, SESSION_ID)); + + await waitFor(() => { + expect(mockRequest).toHaveBeenCalledWith(STATUS_ACTION, { + task_id: TASK_ID, + session_id: SESSION_ID, + }); + }); + // The skip branch must consult the live row (RUNNING) and refuse. + expect(mockSetResumeSkipped).not.toHaveBeenCalled(); + expect(mockSetTaskSession).not.toHaveBeenCalled(); + }); +}); + +// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability +describe("useSessionResumption monotonic terminal hydration", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockConnectionStatus = "connected"; + mockPreventAutoStart = false; + }); + + it("rejects an older terminal status over a live terminal state", async () => { + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: LATER_AT, + state: "FAILED", + }, + }; + mockRequest.mockResolvedValueOnce({ + session_id: "s1", + task_id: "t1", + state: "COMPLETED", + is_agent_running: false, + is_resumable: false, + needs_resume: false, + updated_at: STARTED_AT, // older than the live FAILED + }); + + renderHook(() => useSessionResumption("t1", "s1")); + + await waitFor(() => { + expect(mockRequest).toHaveBeenCalledWith(STATUS_ACTION, { + task_id: "t1", + session_id: "s1", + }); + }); + // The stale COMPLETED must not overwrite the newer live FAILED. + expect(mockSetTaskSession).not.toHaveBeenCalledWith( + expect.objectContaining({ state: "COMPLETED" }), + ); + }); + + it("rejects an older non-terminal status over a live terminal state", async () => { + mockSessionItems = { + s1: { + started_at: "2026-01-01T00:00:00.000Z", + updated_at: LATER_AT, + state: "FAILED", + }, + }; + mockRequest.mockResolvedValueOnce({ + session_id: "s1", + task_id: "t1", + state: "STARTING", + is_agent_running: false, + is_resumable: false, + needs_resume: false, + updated_at: STARTED_AT, // older than the live FAILED + }); + + renderHook(() => useSessionResumption("t1", "s1")); + + await waitFor(() => { + expect(mockRequest).toHaveBeenCalledWith(STATUS_ACTION, { + task_id: "t1", + session_id: "s1", + }); + }); + // The stale STARTING must not overwrite the newer live FAILED. + expect(mockSetTaskSession).not.toHaveBeenCalledWith( + expect.objectContaining({ state: "STARTING" }), + ); + }); + + it("accepts a newer terminal status over a live terminal state", async () => { + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: STARTED_AT, + state: "FAILED", + }, + }; + mockRequest.mockResolvedValueOnce({ + session_id: "s1", + task_id: "t1", + state: "COMPLETED", + is_agent_running: false, + is_resumable: false, + needs_resume: false, + updated_at: LATER_AT, // newer + }); + + renderHook(() => useSessionResumption("t1", "s1")); + + await waitFor(() => { + expect(mockSetTaskSession).toHaveBeenCalledWith( + expect.objectContaining({ state: "COMPLETED" }), + ); + }); + }); + + it("rejects an older status over a live WAITING_FOR_INPUT state", async () => { + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: LATER_AT, + state: "WAITING_FOR_INPUT", + }, + }; + mockRequest.mockResolvedValueOnce({ + session_id: "s1", + task_id: "t1", + state: "IDLE", + is_agent_running: false, + is_resumable: true, + needs_resume: true, + updated_at: STARTED_AT, // older than the live WAITING_FOR_INPUT row + }); + + renderHook(() => useSessionResumption("t1", "s1")); + + await waitFor(() => { + expect(mockRequest).toHaveBeenCalledWith(STATUS_ACTION, { + task_id: "t1", + session_id: "s1", + }); + }); + // WAITING_FOR_INPUT means the agent is alive; a stale older response must + // not downgrade it to a stopped-looking state. + expect(mockSetTaskSession).not.toHaveBeenCalledWith(expect.objectContaining({ state: "IDLE" })); + }); +}); + +describe("useSessionResumption resume-skipped clearing on running status", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockConnectionStatus = "connected"; + mockPreventAutoStart = true; + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: STARTED_AT, + state: "WAITING_FOR_INPUT", + }, + }; + }); + + it("clears the resume-skipped marker when the status confirms the agent is running", async () => { + mockRequest.mockResolvedValueOnce({ + session_id: "s1", + task_id: "t1", + state: "RUNNING", + is_agent_running: true, + is_resumable: false, + needs_resume: false, + updated_at: LATER_AT, + }); + + renderHook(() => useSessionResumption("t1", "s1")); + + await waitFor(() => { + expect(mockSetResumeSkipped).toHaveBeenCalledWith("s1", false); + }); + }); +}); + +describe("useSessionResumption stale-callback guard after navigation", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockConnectionStatus = "connected"; + mockPreventAutoStart = true; + mockSessionItems = { + s1: { + started_at: STARTED_AT, + updated_at: STARTED_AT, + state: "WAITING_FOR_INPUT", + }, + }; + }); + + it("does not record a skip or write state for the previous session when a status response lands after navigation", async () => { + const { promise, resolve: resolveStatus } = Promise.withResolvers(); + mockRequest.mockReturnValueOnce(promise); + + const { rerender } = renderHook( + ({ sid }: { sid: string }) => useSessionResumption(TASK_ID, sid), + { initialProps: { sid: SESSION_ID } }, + ); + + // Navigate to another session before the first status response resolves. + rerender({ sid: "s2" }); + + await act(async () => { + resolveStatus({ + session_id: SESSION_ID, + task_id: TASK_ID, + state: "IDLE", + is_agent_running: false, + is_resumable: true, + needs_resume: true, + updated_at: STARTED_AT, + }); + }); + + // The stale response for the switched-away session must neither record a + // resume-skipped marker nor write its session row. + expect(mockSetResumeSkipped).not.toHaveBeenCalled(); + expect(mockSetTaskSession).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/hooks/domains/session/use-session-resumption.ts b/apps/web/hooks/domains/session/use-session-resumption.ts index e023b574eb..1b9e939cd8 100644 --- a/apps/web/hooks/domains/session/use-session-resumption.ts +++ b/apps/web/hooks/domains/session/use-session-resumption.ts @@ -5,7 +5,7 @@ import { buildResumeRequest, buildRestoreWorkspaceRequest, } from "@/lib/services/session-launch-helpers"; -import { useAppStore } from "@/components/state-provider"; +import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { sessionId as toSessionId, taskId as toTaskId, @@ -59,7 +59,7 @@ export type ResumeStateSetter = { setResumptionState: (s: ResumptionState) => void; setError: (e: string | null) => void; setWorktreePath: (p: string | null) => void; - setWorktreeBranch: (b: string | null) => void; + setWorktreeBranch: (p: string | null) => void; setTaskSession: (s: { id: SessionId; task_id: TaskId; @@ -68,9 +68,13 @@ export type ResumeStateSetter = { updated_at: string; }) => void; setAgentctlReady?: (sessionId: string) => void; + /** Records/clears the resume-skipped marker (prevent-auto-start-on-open). */ + setResumeSkipped?: (sessionId: string, skipped: boolean) => void; + /** Reads the session row live from the store (monotonic hydration guard). */ + getLiveSession?: (sessionId: string) => SessionLike | null; }; -type SessionLike = { started_at?: string; updated_at?: string } | null; +type SessionLike = { started_at?: string; updated_at?: string; state?: string } | null; /** Apply a successful resume response to local state. */ function applyResumeResponse( @@ -229,9 +233,48 @@ type CheckAndResumeParams = { session: SessionLike; setSessionStatus: (s: SessionStatus) => void; setters: ResumeStateSetter; + /** True when the prevent-auto-start-on-open preference gates open-time resumes. */ + preventAutoStart: boolean; }; -/** Apply session status fields to local state. */ +const TERMINAL_STATES = new Set(["FAILED", "CANCELLED", "COMPLETED"]); + +type LiveSessionLike = (SessionLike & { state?: string }) | null; + +/** + * Monotonic status-hydration guard: a `task.session.status` response must not + * downgrade a live STARTING/RUNNING/WAITING_FOR_INPUT session state (a stale + * response can race a newer `session.state_changed` WS event and leave the UI + * showing a stopped session while the agent runs — WAITING_FOR_INPUT means the + * agent is alive and awaiting the next prompt, so an older response claiming + * otherwise must not overwrite it), and must not overwrite a live TERMINAL + * state (FAILED/CANCELLED/COMPLETED — which determines the recovery + * affordances the UI shows) with an older or timestamp-less response. In both + * cases the incoming status is accepted only when its timestamp is newer than + * the live session's. + */ +function shouldApplyStatusState(status: SessionStatus, live: LiveSessionLike): boolean { + if (!status.state) return false; + const liveState = live?.state; + const liveIsProtected = + liveState === "STARTING" || + liveState === "RUNNING" || + liveState === "WAITING_FOR_INPUT" || + TERMINAL_STATES.has(liveState as TaskSessionState); + if (!liveIsProtected) return true; + const liveUpdated = live?.updated_at ? Date.parse(live.updated_at) : Number.NaN; + const incomingUpdated = status.updated_at ? Date.parse(status.updated_at) : Number.NaN; + return ( + Number.isFinite(liveUpdated) && + Number.isFinite(incomingUpdated) && + incomingUpdated > liveUpdated + ); +} + +/** + * Apply session status fields to local state (guarded by + * `shouldApplyStatusState` against stale downgrades). + */ function applyStatusToState( status: SessionStatus, taskId: string, @@ -241,15 +284,18 @@ function applyStatusToState( ): void { setters.setWorktreePath(status.worktree_path ?? null); setters.setWorktreeBranch(status.worktree_branch ?? null); - if (status.state) { - setters.setTaskSession({ - id: toSessionId(sessionId), - task_id: toTaskId(taskId), - state: status.state as TaskSessionState, - started_at: session?.started_at ?? "", - updated_at: status.updated_at ?? session?.updated_at ?? "", - }); + if (!status.state) return; + const live = setters.getLiveSession?.(sessionId) ?? session; + if (!shouldApplyStatusState(status, live)) { + return; // stale or non-terminal status must not downgrade a running session } + setters.setTaskSession({ + id: toSessionId(sessionId), + task_id: toTaskId(taskId), + state: status.state as TaskSessionState, + started_at: session?.started_at ?? "", + updated_at: status.updated_at ?? session?.updated_at ?? "", + }); } type RefreshSessionStatusParams = { @@ -276,6 +322,12 @@ async function refreshSessionStatus({ }); setSessionStatus(status); applyStatusToState(status, taskId, sessionId, session, setters); + // A status response confirming the agent is running must clear any + // stale resume-skipped marker (a delayed response can otherwise leave + // a Start button beside a running agent). + if (status.is_agent_running || status.state === "RUNNING") { + setters.setResumeSkipped?.(sessionId, false); + } if (status.is_agent_running && setters.setAgentctlReady) { setters.setAgentctlReady(sessionId); } @@ -284,12 +336,35 @@ async function refreshSessionStatus({ } } +type ResumeAction = "running" | "skip" | "resume" | "restore" | "idle"; + +function decideResumeAction(status: SessionStatus, preventAutoStart: boolean): ResumeAction { + if (status.is_agent_running) return "running"; + if (preventAutoStart && status.needs_resume && status.is_resumable) return "skip"; + if (status.needs_resume && status.is_resumable) return "resume"; + if (status.needs_workspace_restore) return "restore"; + return "idle"; +} + +/** + * Record the resume-skipped marker only while the live session row is not + * STARTING/RUNNING (checked here with typed live-store access so a stale + * status can never leave a Start button beside a running agent). + */ +function recordResumeSkipIfStopped(setters: ResumeStateSetter, sessionId: string): void { + const liveState = setters.getLiveSession?.(sessionId)?.state; + if (liveState !== "STARTING" && liveState !== "RUNNING") { + setters.setResumeSkipped?.(sessionId, true); + } +} + async function checkAndResume({ taskId, sessionId, session, setSessionStatus, setters, + preventAutoStart, }: CheckAndResumeParams): Promise { const client = getWebSocketClient(); if (!client) return; @@ -313,20 +388,36 @@ async function checkAndResume({ setters.setAgentctlReady(sessionId); } let resumed = false; - if (status.is_agent_running) { - setters.setResumptionState("running"); - } else if (status.needs_resume && status.is_resumable) { - resumed = await resumeWithSilentFallback(taskId, sessionId, session, setters); - } else if (status.needs_workspace_restore) { - resumed = await resumeViaLaunch( - taskId, - sessionId, - session, - setters, - buildRestoreWorkspaceRequest, - ); - } else { - setters.setResumptionState("idle"); + switch (decideResumeAction(status, preventAutoStart)) { + case "running": + setters.setResumptionState("running"); + // A status response confirming the agent is running clears any stale + // resume-skipped marker (the WS RUNNING transition may have been + // missed, or the marker predates this page load). + setters.setResumeSkipped?.(sessionId, false); + break; + case "skip": + // The preference gates the open-time auto-resume: leave the session + // stopped and record the skip so the Start agent button renders. + // The record is guarded against a live STARTING/RUNNING row (a stale + // status can race a running WS transition). + recordResumeSkipIfStopped(setters, sessionId); + setters.setResumptionState("idle"); + break; + case "resume": + resumed = await resumeWithSilentFallback(taskId, sessionId, session, setters); + break; + case "restore": + resumed = await resumeViaLaunch( + taskId, + sessionId, + session, + setters, + buildRestoreWorkspaceRequest, + ); + break; + default: + setters.setResumptionState("idle"); } if (resumed) { await refreshSessionStatus({ client, taskId, sessionId, session, setSessionStatus, setters }); @@ -356,14 +447,24 @@ type SessionResetAndCheckResult = { sessionStatus: SessionStatus | null; }; +type ResetAndCheckParams = { + taskId: string | null; + sessionId: string | null; + connectionStatus: string; + session: SessionLike; + setters: ResumeStateSetter; + preventAutoStart: boolean; +}; + /** Extracted effects: reset state on session/task change, auto-check/resume, and remote retry. */ -function useSessionResetAndCheck( - taskId: string | null, - sessionId: string | null, - connectionStatus: string, - session: { started_at?: string; updated_at?: string } | null, - setters: ResumeStateSetter, -): SessionResetAndCheckResult { +function useSessionResetAndCheck({ + taskId, + sessionId, + connectionStatus, + session, + setters, + preventAutoStart, +}: ResetAndCheckParams): SessionResetAndCheckResult { const [sessionStatusState, setSessionStatus] = useState<{ id: string | null; status: SessionStatus | null; @@ -396,12 +497,13 @@ function useSessionResetAndCheck( taskId, sessionId, session, + preventAutoStart, setSessionStatus: (s) => { if (activeSessionRef.current === sessionId) setSessionStatus({ id: sessionId, status: s }); }, setters: guardedSetters, }); - }, [taskId, sessionId, connectionStatus, session]); // eslint-disable-line react-hooks/exhaustive-deps + }, [taskId, sessionId, connectionStatus, session, preventAutoStart]); // eslint-disable-line react-hooks/exhaustive-deps // Freshly created remote sessions may return status before runtime metadata is available. // Retry a few times so topbar/tooltips can show remote details without manual refresh. @@ -453,6 +555,19 @@ function buildGuardedSetters( setWorktreeBranch: (b) => { if (guard()) setters.setWorktreeBranch(b); }, + // The remaining setters write store state keyed by session id, but a + // stale async callback completing after navigation can still touch the + // previous session's row (e.g. re-mark it resume-skipped or overwrite its + // status). Guard them all so a switched-away session is never mutated. + setTaskSession: (s) => { + if (guard()) setters.setTaskSession(s); + }, + setAgentctlReady: (sid) => { + if (guard()) setters.setAgentctlReady?.(sid); + }, + setResumeSkipped: (sid, skipped) => { + if (guard()) setters.setResumeSkipped?.(sid, skipped); + }, }; } @@ -465,11 +580,16 @@ export function useSessionResumption( const [worktreePath, setWorktreePath] = useState(null); const [worktreeBranch, setWorktreeBranch] = useState(null); const connectionStatus = useAppStore((state) => state.connection.status); + const preventAutoStartAgentOnOpen = useAppStore( + (state) => state.userSettings.preventAutoStartAgentOnOpen, + ); const session = useAppStore((state) => sessionId ? (state.taskSessions.items[sessionId] ?? null) : null, ); const setTaskSession = useAppStore((state) => state.setTaskSession); const setSessionAgentctlStatus = useAppStore((state) => state.setSessionAgentctlStatus); + const setResumeSkipped = useAppStore((state) => state.setResumeSkipped); + const storeApi = useAppStoreApi(); const setters: ResumeStateSetter = { setResumptionState, @@ -478,15 +598,18 @@ export function useSessionResumption( setWorktreeBranch, setTaskSession, setAgentctlReady: (sid: string) => setSessionAgentctlStatus(sid, { status: "ready" }), + setResumeSkipped, + getLiveSession: (sid: string) => storeApi.getState().taskSessions.items[sid] ?? null, }; - const { sessionStatus } = useSessionResetAndCheck( + const { sessionStatus } = useSessionResetAndCheck({ taskId, sessionId, connectionStatus, session, setters, - ); + preventAutoStart: preventAutoStartAgentOnOpen, + }); // Manual resume function const resumeSession = useCallback(async (): Promise => { @@ -507,6 +630,14 @@ export function useSessionResumption( updated_at: session?.updated_at ?? "", }); } + // A successful resume commonly returns state STARTING (launch + // accepted, not agent running). Only confirmed RUNNING clears the + // resume-skipped marker; a STARTING response keeps it so the Start + // button stays until the WS RUNNING transition (or a later status) + // confirms the agent. Failed resumes keep it as a retry affordance. + if (response.state === "RUNNING") { + setResumeSkipped(sessionId, false); + } if (response.worktree_path) setWorktreePath(response.worktree_path); if (response.worktree_branch) setWorktreeBranch(response.worktree_branch); return true; @@ -519,7 +650,15 @@ export function useSessionResumption( setError(err instanceof Error ? err.message : "Unknown error"); return false; } - }, [taskId, sessionId, session, setTaskSession, setWorktreePath, setWorktreeBranch]); + }, [ + taskId, + sessionId, + session, + setTaskSession, + setWorktreePath, + setWorktreeBranch, + setResumeSkipped, + ]); return { resumptionState, diff --git a/apps/web/hooks/domains/workspace/use-external-vcs-file-link.gitlab-host.test.tsx b/apps/web/hooks/domains/workspace/use-external-vcs-file-link.gitlab-host.test.tsx index 4dd0266e19..1e1b45884e 100644 --- a/apps/web/hooks/domains/workspace/use-external-vcs-file-link.gitlab-host.test.tsx +++ b/apps/web/hooks/domains/workspace/use-external-vcs-file-link.gitlab-host.test.tsx @@ -84,6 +84,7 @@ function wrapper(repository: Repository, mr: TaskMR) { tasks: [ { id: TASK_ID, + workflowId: "wf-1", workflowStepId: "step-1", title: "External links", position: 0, diff --git a/apps/web/hooks/domains/workspace/use-external-vcs-file-link.test.tsx b/apps/web/hooks/domains/workspace/use-external-vcs-file-link.test.tsx index 7623c8c665..f8fad7c68d 100644 --- a/apps/web/hooks/domains/workspace/use-external-vcs-file-link.test.tsx +++ b/apps/web/hooks/domains/workspace/use-external-vcs-file-link.test.tsx @@ -211,6 +211,7 @@ function wrapper(options: InitialOptions = {}) { tasks: [ { id: TASK_ID, + workflowId: "wf-1", workflowStepId: "step-1", title: "External links", position: 0, diff --git a/apps/web/hooks/use-ensure-user-settings.test.ts b/apps/web/hooks/use-ensure-user-settings.test.ts index ed7b857221..2185d0488d 100644 --- a/apps/web/hooks/use-ensure-user-settings.test.ts +++ b/apps/web/hooks/use-ensure-user-settings.test.ts @@ -62,6 +62,7 @@ function makeUnloadedSettings(): UserSettingsState { chatSubmitKey: "cmd_enter", reviewAutoMarkOnScroll: true, confirmTaskArchive: true, + preventAutoStartAgentOnOpen: false, unreadDivider: true, agentGeneratedTaskTitles: false, mcpTaskAgentProfileDefault: "current_task", diff --git a/apps/web/hooks/use-task-in-flight.test.tsx b/apps/web/hooks/use-task-in-flight.test.tsx index e04e42fef6..d898c658df 100644 --- a/apps/web/hooks/use-task-in-flight.test.tsx +++ b/apps/web/hooks/use-task-in-flight.test.tsx @@ -11,6 +11,7 @@ type Task = KanbanState["tasks"][number]; function task(id: string, foregroundActivity?: ForegroundActivity | null): Task { return { id, + workflowId: "wf-1", workflowStepId: "step-1", title: id, position: 0, diff --git a/apps/web/lib/kanban/find-task.test.ts b/apps/web/lib/kanban/find-task.test.ts index 8c44f1d732..23f4d65f47 100644 --- a/apps/web/lib/kanban/find-task.test.ts +++ b/apps/web/lib/kanban/find-task.test.ts @@ -5,7 +5,7 @@ import type { KanbanState } from "@/lib/state/slices"; type Task = KanbanState["tasks"][number]; function task(id: string): Task { - return { id, workflowStepId: "s", title: id, position: 0 }; + return { id, workflowId: "wf-1", workflowStepId: "s", title: id, position: 0 }; } describe("findTaskInSnapshots", () => { diff --git a/apps/web/lib/services/session-launch-service.test.ts b/apps/web/lib/services/session-launch-service.test.ts new file mode 100644 index 0000000000..ebefc0cb13 --- /dev/null +++ b/apps/web/lib/services/session-launch-service.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const request = vi.fn(); + +vi.mock("@/lib/ws/connection", () => ({ + getWebSocketClient: () => ({ request }), +})); + +import { ensureTaskSession } from "./session-launch-service"; + +describe("ensureTaskSession", () => { + beforeEach(() => { + request.mockReset(); + request.mockResolvedValue({ success: true, task_id: "t1", state: "CREATED" }); + }); + + it("sends the task id without auto_start when the option is absent", async () => { + await ensureTaskSession("t1"); + expect(request).toHaveBeenCalledWith("session.ensure", { task_id: "t1" }, 15_000); + }); + + it("includes auto_start: false when explicitly requested", async () => { + await ensureTaskSession("t1", { autoStart: false }); + expect(request).toHaveBeenCalledWith( + "session.ensure", + { task_id: "t1", auto_start: false }, + 15_000, + ); + }); + + it("includes auto_start: true when explicitly requested", async () => { + await ensureTaskSession("t1", { autoStart: true }); + expect(request).toHaveBeenCalledWith( + "session.ensure", + { task_id: "t1", auto_start: true }, + 15_000, + ); + }); +}); diff --git a/apps/web/lib/services/session-launch-service.ts b/apps/web/lib/services/session-launch-service.ts index e6d599923a..588c78794b 100644 --- a/apps/web/lib/services/session-launch-service.ts +++ b/apps/web/lib/services/session-launch-service.ts @@ -75,13 +75,17 @@ export type EnsureSessionResponse = { */ export async function ensureTaskSession( taskId: string, - opts?: { ensureExecution?: boolean; timeout?: number }, + opts?: { ensureExecution?: boolean; autoStart?: boolean; timeout?: number }, ): Promise { const client = getWebSocketClient(); if (!client) throw new Error("WebSocket client not available"); return client.request( "session.ensure", - { task_id: taskId, ensure_execution: opts?.ensureExecution }, + { + task_id: taskId, + ensure_execution: opts?.ensureExecution, + ...(opts?.autoStart !== undefined ? { auto_start: opts.autoStart } : {}), + }, opts?.timeout ?? 15_000, ); } diff --git a/apps/web/lib/session-state.test.ts b/apps/web/lib/session-state.test.ts new file mode 100644 index 0000000000..c2e3c74290 --- /dev/null +++ b/apps/web/lib/session-state.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest"; +import { isLaunchStateRegression } from "./session-state"; + +describe("isLaunchStateRegression", () => { + it("applies the launch response over a never-started (CREATED) session", () => { + expect(isLaunchStateRegression("CREATED", "STARTING")).toBe(false); + expect(isLaunchStateRegression("CREATED", "RUNNING")).toBe(false); + }); + + it("applies the launch response over an idle (resume-skipped) session", () => { + expect(isLaunchStateRegression("IDLE", "STARTING")).toBe(false); + expect(isLaunchStateRegression("IDLE", "RUNNING")).toBe(false); + }); + + it("does not regress a live RUNNING state with a delayed STARTING response", () => { + expect(isLaunchStateRegression("RUNNING", "STARTING")).toBe(true); + }); + + it("does not regress a live WAITING_FOR_INPUT state with a delayed STARTING response", () => { + expect(isLaunchStateRegression("WAITING_FOR_INPUT", "STARTING")).toBe(true); + }); + + it("does not regress a live FAILED state with a delayed STARTING response", () => { + expect(isLaunchStateRegression("FAILED", "STARTING")).toBe(true); + expect(isLaunchStateRegression("CANCELLED", "STARTING")).toBe(true); + expect(isLaunchStateRegression("COMPLETED", "STARTING")).toBe(true); + }); + + it("accepts a STARTING response while the live state is already STARTING", () => { + expect(isLaunchStateRegression("STARTING", "STARTING")).toBe(false); + }); + + it("applies a RUNNING launch response over a live STARTING state", () => { + expect(isLaunchStateRegression("STARTING", "RUNNING")).toBe(false); + }); + + it("never regresses when there is no live state", () => { + expect(isLaunchStateRegression(undefined, "STARTING")).toBe(false); + expect(isLaunchStateRegression("", "STARTING")).toBe(false); + }); + + it("treats unknown states as non-regressing", () => { + expect(isLaunchStateRegression("SOMETHING_NEW", "STARTING")).toBe(false); + expect(isLaunchStateRegression("CREATED", "SOMETHING_NEW")).toBe(false); + }); +}); diff --git a/apps/web/lib/session-state.ts b/apps/web/lib/session-state.ts new file mode 100644 index 0000000000..53d974df5a --- /dev/null +++ b/apps/web/lib/session-state.ts @@ -0,0 +1,38 @@ +import type { TaskSessionState } from "@/lib/types/http"; + +/** + * Lifecycle rank for launch-response regression checks. Ordered from + * "agent not running" (CREATED/IDLE) through STARTING to live states + * (RUNNING/WAITING_FOR_INPUT) and terminal states. A launch response + * (typically STARTING) must never overwrite a live state that is FURTHER + * along the lifecycle: a WebSocket RUNNING/FAILED transition can land before + * `session.launch` resolves, and unconditionally writing the older response + * state would hide a running agent or a failure's recovery affordances. + */ +const LAUNCH_STATE_ORDER: Record = { + CREATED: 0, + IDLE: 0, + STARTING: 1, + RUNNING: 2, + WAITING_FOR_INPUT: 2, + COMPLETED: 3, + FAILED: 3, + CANCELLED: 3, +}; + +/** + * True when applying `incomingState` over `liveState` would regress the + * session (incoming is earlier in the lifecycle than what is live). Unknown + * states never count as a regression, so a live row with an unfamiliar state + * still accepts the launch response (the button-hiding hydration wins). + */ +export function isLaunchStateRegression( + liveState: string | undefined, + incomingState: string, +): boolean { + if (!liveState) return false; + const live = LAUNCH_STATE_ORDER[liveState as TaskSessionState]; + const incoming = LAUNCH_STATE_ORDER[incomingState as TaskSessionState]; + if (live === undefined || incoming === undefined) return false; + return incoming < live; +} diff --git a/apps/web/lib/settings-discovery/catalog/preferences.ts b/apps/web/lib/settings-discovery/catalog/preferences.ts index 07e4ecff32..3111901b16 100644 --- a/apps/web/lib/settings-discovery/catalog/preferences.ts +++ b/apps/web/lib/settings-discovery/catalog/preferences.ts @@ -35,6 +35,7 @@ export const GENERAL_SETTINGS_TARGETS = { agentTaskProfile: "setting-agent-task-profile", agentGeneratedTitles: "setting-agent-generated-task-titles", archiveConfirmation: "setting-archive-confirmation", + preventAutoStartOnOpen: "setting-prevent-auto-start-on-open", unreadMessages: "setting-unread-messages", transcriptNavigation: "setting-transcript-navigation", messageQueue: "setting-message-queue", @@ -324,6 +325,16 @@ export const PREFERENCES_DISCOVERY_DEFINITIONS: SettingsDiscoveryDefinition[] = targetId: GENERAL_SETTINGS_TARGETS.agentGeneratedTitles, order: 62, }, + { + id: "task-actions-prevent-auto-start-on-open", + kind: "control", + labelKey: "settings:preventAutoStartAgentOnOpen", + parentId: TASK_BEHAVIOR_ID, + groupId: "preferences", + href: TASK_BEHAVIOR_SETTINGS_HREF, + targetId: GENERAL_SETTINGS_TARGETS.preventAutoStartOnOpen, + order: 63, + }, { id: "task-actions-archive-confirmation", kind: "control", @@ -333,7 +344,7 @@ export const PREFERENCES_DISCOVERY_DEFINITIONS: SettingsDiscoveryDefinition[] = groupId: "preferences", href: TASK_BEHAVIOR_SETTINGS_HREF, targetId: GENERAL_SETTINGS_TARGETS.archiveConfirmation, - order: 63, + order: 64, }, { id: "task-actions-unread-messages", @@ -343,7 +354,7 @@ export const PREFERENCES_DISCOVERY_DEFINITIONS: SettingsDiscoveryDefinition[] = groupId: "preferences", href: TASK_BEHAVIOR_SETTINGS_HREF, targetId: GENERAL_SETTINGS_TARGETS.unreadMessages, - order: 64, + order: 65, }, { id: "task-actions-transcript-navigation", diff --git a/apps/web/lib/ssr/mapper.ts b/apps/web/lib/ssr/mapper.ts index 895eb20520..9a5bf3fc52 100644 --- a/apps/web/lib/ssr/mapper.ts +++ b/apps/web/lib/ssr/mapper.ts @@ -31,6 +31,7 @@ export function snapshotToState(snapshot: WorkflowSnapshot): Partial { const primary = primaryTaskRepository(task.repositories); return { id: task.id, + workflowId: snapshot.workflow.id, workflowStepId, title: task.title, description: task.description ?? undefined, @@ -100,6 +101,7 @@ export function taskToState( activeSessionId: resolvedSessionId, pinnedSessionId: null, lastSessionByTaskId: resolvedSessionId ? { [task.id]: resolvedSessionId } : {}, + resumeSkippedSessionIds: {}, }, messages: resolvedSessionId && messages diff --git a/apps/web/lib/ssr/user-settings.test.ts b/apps/web/lib/ssr/user-settings.test.ts index d3defb7d7b..33cb006e54 100644 --- a/apps/web/lib/ssr/user-settings.test.ts +++ b/apps/web/lib/ssr/user-settings.test.ts @@ -603,3 +603,33 @@ describe("mapUserSettingsResponse voice mode", () => { }); }); }); + +describe("prevent auto-start on open preference", () => { + it("defaults the missing preference to false", () => { + expect(buildCoreFields({}).preventAutoStartAgentOnOpen).toBe(false); + expect(mapUserSettingsResponse(null).preventAutoStartAgentOnOpen).toBe(false); + }); + + it("preserves an explicit enabled preference", () => { + expect( + buildCoreFields({ prevent_auto_start_agent_on_open: true }).preventAutoStartAgentOnOpen, + ).toBe(true); + expect( + mapUserSettingsResponse({ + settings: { + user_id: DEFAULT_USER_ID, + workspace_id: toWorkspaceId(""), + repository_ids: [], + prevent_auto_start_agent_on_open: true, + updated_at: UPDATED_AT, + }, + }).preventAutoStartAgentOnOpen, + ).toBe(true); + }); + + it("preserves an explicit disabled preference", () => { + expect( + buildCoreFields({ prevent_auto_start_agent_on_open: false }).preventAutoStartAgentOnOpen, + ).toBe(false); + }); +}); diff --git a/apps/web/lib/ssr/user-settings.ts b/apps/web/lib/ssr/user-settings.ts index bf9a7a6bd5..ea85fba636 100644 --- a/apps/web/lib/ssr/user-settings.ts +++ b/apps/web/lib/ssr/user-settings.ts @@ -41,6 +41,7 @@ export function createDefaultUserSettings(): UserSettingsState { chatSubmitKey: "cmd_enter", reviewAutoMarkOnScroll: true, confirmTaskArchive: true, + preventAutoStartAgentOnOpen: false, unreadDivider: false, agentGeneratedTaskTitles: true, mcpTaskAgentProfileDefault: "current_task", @@ -249,6 +250,8 @@ function buildBehaviorFields(s: UserSettingsData, current: UserSettingsState) { chatSubmitKey: s.chat_submit_key ?? current.chatSubmitKey, reviewAutoMarkOnScroll: s.review_auto_mark_on_scroll ?? current.reviewAutoMarkOnScroll, confirmTaskArchive: s.confirm_task_archive ?? current.confirmTaskArchive, + preventAutoStartAgentOnOpen: + s.prevent_auto_start_agent_on_open ?? current.preventAutoStartAgentOnOpen, unreadDivider: s.unread_divider ?? current.unreadDivider, agentGeneratedTaskTitles: s.agent_generated_task_titles ?? current.agentGeneratedTaskTitles, mcpTaskAgentProfileDefault: mapDefined( @@ -257,6 +260,12 @@ function buildBehaviorFields(s: UserSettingsData, current: UserSettingsState) { parseMCPTaskAgentProfileDefault, ), startupPage: mapDefined(s.startup_page, current.startupPage, parseStartupPage), + keyboardShortcuts: s.keyboard_shortcuts ?? current.keyboardShortcuts, + }; +} + +function buildAppearanceFields(s: UserSettingsData, current: UserSettingsState) { + return { showAnchoredPromptBar: s.show_anchored_prompt_bar ?? current.showAnchoredPromptBar, showScrollToLastPrompt: s.show_scroll_to_last_prompt ?? current.showScrollToLastPrompt, showScrollToStart: s.show_scroll_to_start ?? current.showScrollToStart, @@ -270,7 +279,6 @@ function buildBehaviorFields(s: UserSettingsData, current: UserSettingsState) { s.release_notes_last_seen_version, current.releaseNotesLastSeenVersion, ), - keyboardShortcuts: s.keyboard_shortcuts ?? current.keyboardShortcuts, }; } @@ -282,6 +290,7 @@ export function buildCoreFields( revision: s.revision ?? current.revision, ...buildIdentityFields(s, current), ...buildBehaviorFields(s, current), + ...buildAppearanceFields(s, current), savedLayouts: s.saved_layouts ?? current.savedLayouts, sidebarViews: mapDefined(s.sidebar_views, current.sidebarViews, (views) => views.map(fromApiSidebarView), diff --git a/apps/web/lib/state/slices/kanban/kanban-slice.test.ts b/apps/web/lib/state/slices/kanban/kanban-slice.test.ts index 5da5fddf9b..944c843954 100644 --- a/apps/web/lib/state/slices/kanban/kanban-slice.test.ts +++ b/apps/web/lib/state/slices/kanban/kanban-slice.test.ts @@ -81,6 +81,7 @@ describe("kanban slice workspace transition", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: "step-a", title: "Workspace A task", position: 0, @@ -108,6 +109,7 @@ describe("kanban slice workspace transition", () => { activeSessionId: PINNED_SESSION_ID, pinnedSessionId: PINNED_SESSION_ID, lastSessionByTaskId: { [TASK_ID]: PINNED_SESSION_ID }, + resumeSkippedSessionIds: {}, }, }); @@ -131,7 +133,13 @@ describe("kanban slice workspace transition", () => { describe("kanban slice archived sidebar projection", () => { it("stores archived tasks separately from active kanban state and deduplicates IDs", () => { const store = makeStore(); - const task = { id: TASK_ID, workflowStepId: "step-a", title: "Archived", position: 0 }; + const task = { + id: TASK_ID, + workflowId: WORKFLOW_ID, + workflowStepId: "step-a", + title: "Archived", + position: 0, + }; store.getState().setSidebarArchivedTasks(ARCHIVED_WORKSPACE_ID, [task]); store @@ -149,7 +157,13 @@ describe("kanban slice archived sidebar projection", () => { it("creates a workspace bucket when upserting its first archived task", () => { const store = makeStore(); - const task = { id: TASK_ID, workflowStepId: "step-a", title: "Archived", position: 0 }; + const task = { + id: TASK_ID, + workflowId: WORKFLOW_ID, + workflowStepId: "step-a", + title: "Archived", + position: 0, + }; store.getState().upsertSidebarArchivedTask("workspace-new", task); @@ -172,7 +186,13 @@ describe("kanban slice archived sidebar projection", () => { tasks: KanbanSlice["sidebarArchivedTasks"]["itemsByWorkspaceId"][string], expectedRevision?: number, ) => boolean; - const task = { id: TASK_ID, workflowStepId: "step-a", title: "Loaded", position: 0 }; + const task = { + id: TASK_ID, + workflowId: WORKFLOW_ID, + workflowStepId: "step-a", + title: "Loaded", + position: 0, + }; setArchivedTasks(ARCHIVED_WORKSPACE_ID, [task]); const beforeArchive = revision(); @@ -200,3 +220,27 @@ describe("kanban slice archived sidebar projection", () => { ); }); }); + +describe("kanban slice resume-skipped marker", () => { + it("records the skip for any session and clears it on request", () => { + const store = makeStore(); + store.getState().setResumeSkipped("session-idle", true); + expect(store.getState().tasks.resumeSkippedSessionIds["session-idle"]).toBe(true); + + store.getState().setResumeSkipped("session-idle", false); + expect(store.getState().tasks.resumeSkippedSessionIds["session-idle"]).toBeUndefined(); + }); + + it("records the skip as a plain keyed write (the STARTING/RUNNING guard lives at the hook call site)", () => { + // The slice is deliberately a dumb write: the guard that refuses to mark + // a starting/running session resume-skipped reads the live session row + // with typed store access in use-session-resumption's skip branch. A + // direct slice call records unconditionally. + const store = makeStore(); + store.getState().setResumeSkipped("session-running", true); + expect(store.getState().tasks.resumeSkippedSessionIds["session-running"]).toBe(true); + + store.getState().setResumeSkipped("session-running", false); + expect(store.getState().tasks.resumeSkippedSessionIds["session-running"]).toBeUndefined(); + }); +}); diff --git a/apps/web/lib/state/slices/kanban/kanban-slice.ts b/apps/web/lib/state/slices/kanban/kanban-slice.ts index 6c354728d4..43856e859c 100644 --- a/apps/web/lib/state/slices/kanban/kanban-slice.ts +++ b/apps/web/lib/state/slices/kanban/kanban-slice.ts @@ -18,6 +18,7 @@ export const defaultKanbanState: KanbanSliceState = { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }; @@ -91,6 +92,61 @@ function createSidebarArchivedTaskActions(set: KanbanSliceSet): SidebarArchivedT }; } +type TaskActions = Pick< + KanbanSliceActions, + | "setActiveTask" + | "setActiveSession" + | "setActiveSessionAuto" + | "clearActiveSession" + | "setResumeSkipped" +>; + +function createTaskActions(set: KanbanSliceSet): TaskActions { + return { + setActiveTask: (taskId) => + set((draft) => { + draft.tasks.activeTaskId = taskId; + draft.tasks.activeSessionId = null; + // New task → drop any pin; the pin only applies within a single task. + draft.tasks.pinnedSessionId = null; + }), + setActiveSession: (taskId, sessionId) => + set((draft) => { + draft.tasks.activeTaskId = taskId; + draft.tasks.activeSessionId = sessionId; + // User-initiated selection: pin so WS auto-replace handoff respects it. + draft.tasks.pinnedSessionId = sessionId; + draft.tasks.lastSessionByTaskId[taskId] = sessionId; + }), + setActiveSessionAuto: (taskId, sessionId) => + set((draft) => { + if (draft.tasks.activeTaskId !== taskId) { + draft.tasks.pinnedSessionId = null; + } + draft.tasks.activeTaskId = taskId; + draft.tasks.activeSessionId = sessionId; + draft.tasks.lastSessionByTaskId[taskId] = sessionId; + }), + clearActiveSession: () => + set((draft) => { + draft.tasks.activeSessionId = null; + draft.tasks.pinnedSessionId = null; + }), + setResumeSkipped: (sessionId, skipped) => + set((draft) => { + if (skipped) { + // Recording is guarded at the call site (use-session-resumption's + // skip branch reads the live session row with typed store access), + // so a stale status can never mark a starting/running session as + // resume-skipped. The slice stays a plain keyed write. + draft.tasks.resumeSkippedSessionIds[sessionId] = true; + } else { + delete draft.tasks.resumeSkippedSessionIds[sessionId]; + } + }), + }; +} + export const createKanbanSlice: StateCreator< KanbanSlice, [["zustand/immer", never]], @@ -99,6 +155,7 @@ export const createKanbanSlice: StateCreator< > = (set) => ({ ...defaultKanbanState, ...createSidebarArchivedTaskActions(set), + ...createTaskActions(set), resetKanbanWorkspaceContext: () => set((draft) => { const nextGeneration = draft.workspaceContextGeneration + 1; @@ -126,35 +183,6 @@ export const createKanbanSlice: StateCreator< } draft.workflows.items = reordered; }), - setActiveTask: (taskId) => - set((draft) => { - draft.tasks.activeTaskId = taskId; - draft.tasks.activeSessionId = null; - // New task → drop any pin; the pin only applies within a single task. - draft.tasks.pinnedSessionId = null; - }), - setActiveSession: (taskId, sessionId) => - set((draft) => { - draft.tasks.activeTaskId = taskId; - draft.tasks.activeSessionId = sessionId; - // User-initiated selection: pin so WS auto-replace handoff respects it. - draft.tasks.pinnedSessionId = sessionId; - draft.tasks.lastSessionByTaskId[taskId] = sessionId; - }), - setActiveSessionAuto: (taskId, sessionId) => - set((draft) => { - if (draft.tasks.activeTaskId !== taskId) { - draft.tasks.pinnedSessionId = null; - } - draft.tasks.activeTaskId = taskId; - draft.tasks.activeSessionId = sessionId; - draft.tasks.lastSessionByTaskId[taskId] = sessionId; - }), - clearActiveSession: () => - set((draft) => { - draft.tasks.activeSessionId = null; - draft.tasks.pinnedSessionId = null; - }), setWorkflowSnapshot: (workflowId, data) => set((draft) => { draft.kanbanMulti.snapshots[workflowId] = data; diff --git a/apps/web/lib/state/slices/kanban/types.ts b/apps/web/lib/state/slices/kanban/types.ts index a6ab3a2e38..c3b2775c68 100644 --- a/apps/web/lib/state/slices/kanban/types.ts +++ b/apps/web/lib/state/slices/kanban/types.ts @@ -46,7 +46,11 @@ export type KanbanState = { tasks: Array<{ id: string; workspaceId?: string; - workflowId?: string; + // Required for workflow-backed kanban tasks: every producer (kanban.update + // WS handler, snapshotToState, toKanbanTask) must populate it, or the + // prevent-auto-start gate would resolve a task's step list against the + // wrong workflow. Ephemeral tasks are filtered out before this point. + workflowId: string; workflowStepId: string; title: string; description?: string; @@ -165,6 +169,12 @@ export type TaskState = { // map survives task switches so navigating back to a task can restore the // user's last-selected session instead of always jumping to primary. lastSessionByTaskId: Record; + // resumeSkippedSessionIds records sessions whose open-time auto-resume was + // skipped because the prevent-auto-start-on-open preference is enabled. A + // Record (not a Set): the slice is Immer-managed and SSR-hydrated, so a + // native Set would break mutation and serialization. The Start agent button + // renders for these sessions until the agent confirms RUNNING. + resumeSkippedSessionIds: Record; }; export type KanbanSliceState = { @@ -188,6 +198,11 @@ export type KanbanSliceActions = { // it explicitly after checking no non-terminal manual pin should be preserved. setActiveSessionAuto: (taskId: string, sessionId: string) => void; clearActiveSession: () => void; + // setResumeSkipped records/clears the resume-skipped marker for a session. + // Recording is guarded at the call site (the session-resumption hook reads + // the live session row with typed store access), so a stale status response + // can never leave a Start button while the agent is actually running. + setResumeSkipped: (sessionId: string, skipped: boolean) => void; setWorkflowSnapshot: (workflowId: string, data: WorkflowSnapshotData) => void; setKanbanMultiLoading: (loading: boolean) => void; clearKanbanMulti: () => void; diff --git a/apps/web/lib/state/slices/settings/types.ts b/apps/web/lib/state/slices/settings/types.ts index ed85662942..47178ae8e6 100644 --- a/apps/web/lib/state/slices/settings/types.ts +++ b/apps/web/lib/state/slices/settings/types.ts @@ -268,6 +268,7 @@ export type UserSettingsState = { chatSubmitKey: "enter" | "cmd_enter"; reviewAutoMarkOnScroll: boolean; confirmTaskArchive: boolean; + preventAutoStartAgentOnOpen: boolean; unreadDivider: boolean; agentGeneratedTaskTitles: boolean; mcpTaskAgentProfileDefault: MCPTaskAgentProfileDefault; diff --git a/apps/web/lib/types/http-user-settings.ts b/apps/web/lib/types/http-user-settings.ts index 987866fb92..fc2ea1d6a7 100644 --- a/apps/web/lib/types/http-user-settings.ts +++ b/apps/web/lib/types/http-user-settings.ts @@ -71,6 +71,7 @@ export type UserSettings = { show_todo_list_panel_only_when_not_empty?: boolean; review_auto_mark_on_scroll?: boolean; confirm_task_archive?: boolean; + prevent_auto_start_agent_on_open?: boolean; unread_divider?: boolean; agent_generated_task_titles?: boolean; mcp_task_agent_profile_default?: MCPTaskAgentProfileDefault; @@ -135,6 +136,7 @@ export type UserSettingsUpdatePayload = { show_todo_list_panel_only_when_not_empty?: boolean; review_auto_mark_on_scroll?: boolean; confirm_task_archive?: boolean; + prevent_auto_start_agent_on_open?: boolean; unread_divider?: boolean; agent_generated_task_titles?: boolean; mcp_task_agent_profile_default?: MCPTaskAgentProfileDefault; diff --git a/apps/web/lib/ws/handlers/agent-session-kanban.test.ts b/apps/web/lib/ws/handlers/agent-session-kanban.test.ts index ef03021eaa..9528ee62fe 100644 --- a/apps/web/lib/ws/handlers/agent-session-kanban.test.ts +++ b/apps/web/lib/ws/handlers/agent-session-kanban.test.ts @@ -20,11 +20,13 @@ function makeStore( activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: {} }, taskSessionsByTask: { itemsByTaskId: {} }, upsertTaskSessionFromEvent: vi.fn(), setActiveSessionAuto: vi.fn(), + setResumeSkipped: vi.fn(), setSessionAgentctlStatus: vi.fn(), setSessionFailureNotification: vi.fn(), setContextWindow: vi.fn(), @@ -56,6 +58,7 @@ function makeMessage(payload: TaskSessionStateChangedPayload) { function makeKanbanTask(primarySessionId: string) { return { id: "t-1", + workflowId: "wf-1", workflowStepId: "step-1", title: TASK_TITLE, position: 0, @@ -183,6 +186,7 @@ describe("session.state_changed -> non-primary kanban card state", () => { tasks: [ { id: "t-1", + workflowId: "wf-1", workflowStepId: "step-1", title: TASK_TITLE, position: 0, @@ -201,6 +205,7 @@ describe("session.state_changed -> non-primary kanban card state", () => { tasks: [ { id: "t-1", + workflowId: "wf-1", workflowStepId: "step-1", title: TASK_TITLE, position: 0, @@ -260,6 +265,7 @@ describe("session.state_changed -> kanban sync guards", () => { const kanbanTasks = [ { id: "t-1", + workflowId: "wf-1", workflowStepId: "step-1", title: TASK_TITLE, position: 0, diff --git a/apps/web/lib/ws/handlers/agent-session-pure.test.ts b/apps/web/lib/ws/handlers/agent-session-pure.test.ts index f08c31c7c1..d0f25560fd 100644 --- a/apps/web/lib/ws/handlers/agent-session-pure.test.ts +++ b/apps/web/lib/ws/handlers/agent-session-pure.test.ts @@ -16,6 +16,7 @@ function makeAppState(partial: Partial): AppState { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: {} }, taskSessionsByTask: { itemsByTaskId: {} }, @@ -76,6 +77,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }); expect(shouldAdoptNewSession(state, "t-1", "STARTING")).toBe(true); @@ -88,6 +90,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: "s-other", pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { "s-other": { id: "s-other", task_id: "t-2", state: "RUNNING" } }, @@ -103,6 +106,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: "s-old", pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "COMPLETED" } }, @@ -118,6 +122,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: "s-old", pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "IDLE" } }, @@ -133,6 +138,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: "s-old", pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, @@ -148,6 +154,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }); expect(shouldAdoptNewSession(state, "t-2", "STARTING")).toBe(false); @@ -160,6 +167,7 @@ describe("shouldAdoptNewSession", () => { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }); expect(shouldAdoptNewSession(state, "t-1", "COMPLETED")).toBe(false); @@ -209,6 +217,7 @@ describe("shouldPreservePinnedSessionForTask", () => { activeSessionId: "s-pinned", pinnedSessionId: "s-pinned", lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { "s-pinned": { id: "s-pinned", task_id: "t-1", state: "IDLE" } }, @@ -225,6 +234,7 @@ describe("shouldPreservePinnedSessionForTask", () => { activeSessionId: "s-drifted", pinnedSessionId: "s-pinned", lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessionsByTask: { itemsByTaskId: { "t-1": [] }, @@ -243,6 +253,7 @@ describe("shouldPreservePinnedSessionForTask", () => { activeSessionId: "s-drifted", pinnedSessionId: "s-pinned", lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessionsByTask: { itemsByTaskId: { "t-1": [] }, @@ -261,6 +272,7 @@ describe("shouldPreservePinnedSessionForTask", () => { activeSessionId: "s-drifted", pinnedSessionId: "s-pinned", lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { diff --git a/apps/web/lib/ws/handlers/agent-session.test.ts b/apps/web/lib/ws/handlers/agent-session.test.ts index 75768d2ee0..96cae430ff 100644 --- a/apps/web/lib/ws/handlers/agent-session.test.ts +++ b/apps/web/lib/ws/handlers/agent-session.test.ts @@ -19,6 +19,7 @@ function makeStore(overrides: Record = {}) { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: {} }, taskSessionsByTask: { itemsByTaskId: {} }, @@ -28,6 +29,7 @@ function makeStore(overrides: Record = {}) { setActiveSession: vi.fn(), setActiveSessionAuto: vi.fn(), setSessionAgentctlStatus: vi.fn(), + setResumeSkipped: vi.fn(), setSessionFailureNotification: vi.fn(), setContextWindow: vi.fn(), clearContextWindow: vi.fn(), @@ -1480,3 +1482,29 @@ describe("session activity explicit-null contract", () => { expect(store.getState().taskSessions.items["s-2"].foreground_activity).toBe("background"); }); }); + +describe("session.state_changed resume-skipped clearing", () => { + let store: ReturnType; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let handler: (msg: any) => void; + + beforeEach(() => { + vi.clearAllMocks(); + store = makeStore({ + taskSessions: { + items: { "s-1": { id: "s-1", task_id: "t-1", state: "WAITING_FOR_INPUT" } }, + }, + }); + handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!; + }); + + it("clears the resume-skipped marker on a RUNNING transition", () => { + handler(makeMessage({ task_id: "t-1", session_id: "s-1", new_state: "RUNNING" })); + expect(store.getState().setResumeSkipped).toHaveBeenCalledWith("s-1", false); + }); + + it("does NOT clear the marker on a STARTING transition (failed resumes keep the retry button)", () => { + handler(makeMessage({ task_id: "t-1", session_id: "s-1", new_state: "STARTING" })); + expect(store.getState().setResumeSkipped).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/lib/ws/handlers/agent-session.ts b/apps/web/lib/ws/handlers/agent-session.ts index b96be1d921..cc6358e2d8 100644 --- a/apps/web/lib/ws/handlers/agent-session.ts +++ b/apps/web/lib/ws/handlers/agent-session.ts @@ -729,6 +729,14 @@ export function registerTaskSessionHandlers(store: StoreApi): WsHandle extractContextWindow(store, sessionId, payload); maybePromoteAgentctlReady(store, sessionId, newState, message.timestamp); + // A confirmed RUNNING transition clears the resume-skipped marker + // (prevent-auto-start-on-open). STARTING deliberately does NOT clear + // it: a failed manual resume emits STARTING before the launch fails, + // and clearing there would drop the Start agent retry affordance. + if (newState === "RUNNING") { + store.getState().setResumeSkipped(sessionId, false); + } + maybeAdoptSessionOnTransition( store, taskId, diff --git a/apps/web/lib/ws/handlers/kanban.test.ts b/apps/web/lib/ws/handlers/kanban.test.ts index a9cea9e830..24dc5224f8 100644 --- a/apps/web/lib/ws/handlers/kanban.test.ts +++ b/apps/web/lib/ws/handlers/kanban.test.ts @@ -78,6 +78,7 @@ describe("kanban.update handler — primarySessionId preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -113,6 +114,7 @@ describe("kanban.update handler — primarySessionId preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -151,7 +153,7 @@ describe("kanban.update handler — primarySessionId preservation", () => { expect(task?.primarySessionId).toBeUndefined(); }); }); - +// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability describe("kanban.update handler — foregroundActivity preservation", () => { it("preserves foregroundActivity from existing tasks", () => { const store = makeStore({ @@ -161,6 +163,7 @@ describe("kanban.update handler — foregroundActivity preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -178,6 +181,7 @@ describe("kanban.update handler — foregroundActivity preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -213,6 +217,7 @@ describe("kanban.update handler — foregroundActivity preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -230,6 +235,7 @@ describe("kanban.update handler — foregroundActivity preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -257,7 +263,9 @@ describe("kanban.update handler — foregroundActivity preservation", () => { expect(snapshotTask?.foregroundActivity).toBeNull(); }); }); +// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability +// eslint-disable-next-line max-lines-per-function -- fixture-heavy test callback describe("kanban.update handler — taskPendingAction preservation", () => { it("preserves taskPendingAction from existing tasks", () => { const store = makeStore({ @@ -267,6 +275,7 @@ describe("kanban.update handler — taskPendingAction preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -284,6 +293,7 @@ describe("kanban.update handler — taskPendingAction preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -319,6 +329,7 @@ describe("kanban.update handler — taskPendingAction preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -336,6 +347,7 @@ describe("kanban.update handler — taskPendingAction preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -373,6 +385,7 @@ describe("kanban.update handler — repository preservation", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -436,6 +449,7 @@ describe("kanban.update handler — repository switch", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -454,6 +468,7 @@ describe("kanban.update handler — repository switch", () => { tasks: [ { id: TASK_ID, + workflowId: WORKFLOW_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0, @@ -499,6 +514,7 @@ describe("kanban.update handler — explicit-null primary preservation", () => { tasks: [ { id: "t1", + workflowId: "wf1", workflowStepId: "s1", title: "T1", position: 0, @@ -516,6 +532,7 @@ describe("kanban.update handler — explicit-null primary preservation", () => { tasks: [ { id: "t1", + workflowId: "wf1", workflowStepId: "s1", title: "T1", position: 0, @@ -552,6 +569,7 @@ describe("kanban.update handler — multi-snapshot primary lookup", () => { tasks: [ { id: "t1", + workflowId: "wf1", workflowStepId: "s1", title: "T1", position: 0, diff --git a/apps/web/lib/ws/handlers/kanban.ts b/apps/web/lib/ws/handlers/kanban.ts index cf11bc2fcd..aaae86d547 100644 --- a/apps/web/lib/ws/handlers/kanban.ts +++ b/apps/web/lib/ws/handlers/kanban.ts @@ -69,6 +69,7 @@ export function registerKanbanHandlers(store: StoreApi): WsHandlers { }); return { id: task.id, + workflowId, workflowStepId: task.workflowStepId, title: task.title, description: task.description, @@ -131,7 +132,10 @@ export function registerKanbanHandlers(store: StoreApi): WsHandlers { ...next.kanbanMulti, snapshots: { ...next.kanbanMulti.snapshots, - [workflowId]: { ...snapshot, steps, tasks: multiTasks }, + // A full kanban.update carries the authoritative step list; + // clear any placeholder marker so final-step gating can + // resolve against the real steps. + [workflowId]: { ...snapshot, steps, tasks: multiTasks, isPlaceholder: false }, }, }, }; diff --git a/apps/web/lib/ws/handlers/system-events.test.ts b/apps/web/lib/ws/handlers/system-events.test.ts index 24140992e7..3106b4ac16 100644 --- a/apps/web/lib/ws/handlers/system-events.test.ts +++ b/apps/web/lib/ws/handlers/system-events.test.ts @@ -21,6 +21,7 @@ describe("registerSystemEventsHandlers", () => { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, }); const handlers = registerSystemEventsHandlers(store); diff --git a/apps/web/lib/ws/handlers/task-lifecycle-diagnostics.test.ts b/apps/web/lib/ws/handlers/task-lifecycle-diagnostics.test.ts index dd4f79f4c4..67ede109a7 100644 --- a/apps/web/lib/ws/handlers/task-lifecycle-diagnostics.test.ts +++ b/apps/web/lib/ws/handlers/task-lifecycle-diagnostics.test.ts @@ -82,6 +82,7 @@ function makeStateChangedMessage(payload: Record) { const existingTask = { id: "t1", + workflowId: "wf1", workflowStepId: "step1", title: "Old", position: 0, diff --git a/apps/web/lib/ws/handlers/tasks.deleted.test.ts b/apps/web/lib/ws/handlers/tasks.deleted.test.ts index 28cbd0b450..c90d764681 100644 --- a/apps/web/lib/ws/handlers/tasks.deleted.test.ts +++ b/apps/web/lib/ws/handlers/tasks.deleted.test.ts @@ -49,6 +49,7 @@ describe("task.deleted cleanup", () => { activeSessionId: SESS_PINNED, pinnedSessionId: SESS_PINNED, lastSessionByTaskId: { t1: SESS_PINNED, t2: SESS_OTHER }, + resumeSkippedSessionIds: {}, }, environmentIdBySessionId: {}, }); @@ -110,6 +111,7 @@ describe("task.deleted live notification + redirect", () => { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, environmentIdBySessionId: {}, } as unknown as Partial); diff --git a/apps/web/lib/ws/handlers/tasks.test-helpers.ts b/apps/web/lib/ws/handlers/tasks.test-helpers.ts index f22e906de6..98d29d277d 100644 --- a/apps/web/lib/ws/handlers/tasks.test-helpers.ts +++ b/apps/web/lib/ws/handlers/tasks.test-helpers.ts @@ -19,6 +19,7 @@ export function makeStore(initial: Partial = {}) { activeSessionId: null, pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessionsByTask: { itemsByTaskId: {}, loadedByTaskId: {}, loadingByTaskId: {} }, environmentIdBySessionId: {}, @@ -26,6 +27,7 @@ export function makeStore(initial: Partial = {}) { state = { ...state, tasks: { + ...state.tasks, activeTaskId: taskId, activeSessionId: sessionId, pinnedSessionId: sessionId, diff --git a/apps/web/lib/ws/handlers/tasks.test.ts b/apps/web/lib/ws/handlers/tasks.test.ts index 60619b9137..a098b20727 100644 --- a/apps/web/lib/ws/handlers/tasks.test.ts +++ b/apps/web/lib/ws/handlers/tasks.test.ts @@ -30,6 +30,7 @@ function makeStore(initial: Partial = {}) { state = { ...state, tasks: { + ...state.tasks, activeTaskId: taskId, activeSessionId: sessionId, pinnedSessionId: sessionId, @@ -123,6 +124,7 @@ function makeFollowStore(opts: { activeSessionId: opts.activeSessionId, pinnedSessionId: opts.pinnedSessionId, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, setActiveSessionAuto: opts.setActiveSessionAuto, }); @@ -178,6 +180,7 @@ describe("task.updated primary-session focus follow", () => { activeSessionId: "sess-old", pinnedSessionId: null, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, setActiveSessionAuto, }); @@ -281,6 +284,7 @@ describe("task.updated primary-session focus follow (pinning)", () => { activeSessionId: SESS_DRIFTED, pinnedSessionId: SESS_PINNED, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { @@ -318,6 +322,7 @@ describe("task.updated primary-session focus follow (stale pin cleanup)", () => activeSessionId: SESS_DRIFTED, pinnedSessionId: SESS_PINNED, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { @@ -347,6 +352,7 @@ describe("task.updated primary-session focus follow (stale pin cleanup)", () => activeSessionId: SESS_DRIFTED, pinnedSessionId: SESS_PINNED, lastSessionByTaskId: {}, + resumeSkippedSessionIds: {}, }, taskSessions: { items: { diff --git a/apps/web/src/locales/en/settings.json b/apps/web/src/locales/en/settings.json index de65ad107b..ae40f96d7d 100644 --- a/apps/web/src/locales/en/settings.json +++ b/apps/web/src/locales/en/settings.json @@ -36,6 +36,8 @@ "appriseServiceUrls": "Service URL(s)", "appriseUrlRequired": "At least one Apprise service URL is required.", "archiveConfirmation": "Archive Confirmation", + "preventAutoStartAgentOnOpen": "Prevent auto-start on open", + "preventAutoStartAgentOnOpenHelp": "Don't start the agent automatically when opening a task after a restart or from the final workflow step. The Start agent button is shown instead.", "arrangeSplit": "Arrange split", "autoApprove": "Auto-approve", "autoInstallIfNotFound": "Auto-install if not found", diff --git a/apps/web/src/locales/pseudo/settings.json b/apps/web/src/locales/pseudo/settings.json index 6681f19888..8693182ac6 100644 --- a/apps/web/src/locales/pseudo/settings.json +++ b/apps/web/src/locales/pseudo/settings.json @@ -36,6 +36,8 @@ "appriseServiceUrls": "Śēŕvĩćē ŨŔĹ(ś)", "appriseUrlRequired": "Àţ ĺēàśţ ōńē Àƥƥŕĩśē śēŕvĩćē ŨŔĹ ĩś ŕēqũĩŕēď.", "archiveConfirmation": "Àŕćĥĩvē Ćōńƒĩŕḿàţĩōń", + "preventAutoStartAgentOnOpen": "Ƥŕēvēńţ àũţō-śţàŕţ ōń ōƥēń", + "preventAutoStartAgentOnOpenHelp": "Ďōń'ţ śţàŕţ ţĥē àĝēńţ àũţōḿàţĩćàĺĺŷ ŵĥēń ōƥēńĩńĝ à ţàśķ àƒţēŕ à ŕēśţàŕţ ōŕ ƒŕōḿ ţĥē ƒĩńàĺ ŵōŕķƒĺōŵ śţēƥ. Ţĥē Śţàŕţ àĝēńţ ƀũţţōń ĩś śĥōŵń ĩńśţēàď.", "arrangeSplit": "Àŕŕàńĝē śƥĺĩţ", "autoApprove": "Àũţō-àƥƥŕōvē", "autoInstallIfNotFound": "Àũţō-ĩńśţàĺĺ ĩƒ ńōţ ƒōũńď", diff --git a/apps/web/src/locales/pt-pt/settings.json b/apps/web/src/locales/pt-pt/settings.json index 365f05415d..a83220e8a5 100644 --- a/apps/web/src/locales/pt-pt/settings.json +++ b/apps/web/src/locales/pt-pt/settings.json @@ -35,6 +35,8 @@ "appriseServiceUrls": "URL(s) do serviço", "appriseUrlRequired": "É obrigatório pelo menos um URL de serviço Apprise.", "archiveConfirmation": "Confirmação de arquivo", + "preventAutoStartAgentOnOpen": "Impedir arranque automático ao abrir", + "preventAutoStartAgentOnOpenHelp": "Não inicia o agente automaticamente ao abrir uma tarefa após um reinício ou a partir do passo final do fluxo de trabalho. O botão Iniciar o agente é mostrado em vez disso.", "arrangeSplit": "Organizar a divisão", "autoApprove": "Aprovação automática", "autoFallback": "Fazer fallback automaticamente para o modelo seguinte", diff --git a/apps/web/src/locales/zh-cn/settings.json b/apps/web/src/locales/zh-cn/settings.json index 217549194c..42de6395f1 100644 --- a/apps/web/src/locales/zh-cn/settings.json +++ b/apps/web/src/locales/zh-cn/settings.json @@ -36,6 +36,8 @@ "appriseServiceUrls": "服务 URL", "appriseUrlRequired": "至少需要一个 Apprise 服务 URL。", "archiveConfirmation": "归档确认", + "preventAutoStartAgentOnOpen": "打开时阻止自动启动", + "preventAutoStartAgentOnOpenHelp": "重启后或从工作流最后一步打开任务时,不会自动启动代理,而是显示启动代理按钮。", "arrangeSplit": "调整拆分布局", "autoApprove": "自动批准", "autoInstallIfNotFound": "未找到时自动安装", diff --git a/docs/WEBSOCKET_API.md b/docs/WEBSOCKET_API.md index 22bf6ac84f..c1a37c456b 100644 --- a/docs/WEBSOCKET_API.md +++ b/docs/WEBSOCKET_API.md @@ -1780,6 +1780,77 @@ The orchestrator coordinates task execution, managing the workflow between tasks --- +## Session Actions + +Session lifecycle is managed idempotently: clients ask the backend to ensure a +session exists for a task, and the backend resolves the agent profile and +decides whether to prepare or start the agent. + +### `session.ensure` + +**Purpose:** Ensure a task has at least one session, creating one if needed. +Idempotent: returns the task's existing primary (or newest) session when one +already exists. The backend resolves the agent profile from task metadata, +workflow step, workflow, or workspace default, and chooses `prepare` vs +`start` based on the workflow step's `auto_start_agent` action unless the +client overrides it with `auto_start`. + +**Flow Position:** Called when opening a task so the chat has a session to +attach to. + +**Request:** +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "type": "request", + "action": "session.ensure", + "payload": { + "task_id": "task-uuid", + "auto_start": false + } +} +``` + +| Payload Field | Type | Required | Description | +|--------------|------|----------|-------------| +| `task_id` | string | ✅ | Task to ensure a session for | +| `auto_start` | boolean | ❌ | Optional override of the workflow step's auto-start decision. `false` prepares the session (`created_prepare`) without launching the agent; `true` forces a start (`created_start`). Omitting it defers to the workflow step's `auto_start_agent` action. | + +**Response:** +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "type": "response", + "action": "session.ensure", + "payload": { + "success": true, + "task_id": "task-uuid", + "session_id": "session-uuid", + "state": "CREATED", + "agent_profile_id": "profile-uuid", + "source": "created_prepare", + "newly_created": true + } +} +``` + +| Response Field | Type | Description | +|---------------|------|-------------| +| `success` | boolean | Whether the ensure succeeded | +| `task_id` | string | The task the session belongs to | +| `session_id` | string | The ensured session | +| `state` | string | Session state (`CREATED` for a prepared session, `STARTING`/`RUNNING` when the agent is launching) | +| `agent_profile_id` | string | Resolved agent profile | +| `source` | string | Where the session came from: `existing_primary`, `existing_newest`, `created_prepare`, or `created_start` | +| `newly_created` | boolean | Whether the session was created by this call | +| `workspace_path` | string | Worktree path (present when a workspace was prepared) | + +**Effect:** With `auto_start: false` the agent stays stopped and the client +shows a manual "Start agent" affordance; with `auto_start: true` (or the +workflow step's `auto_start_agent` action) the agent launches immediately. + +--- + ## Permission Actions Agents may request user permission for certain operations. The permission flow uses notifications and responses. diff --git a/docs/plans/prevent-agent-autostart-on-open/plan.md b/docs/plans/prevent-agent-autostart-on-open/plan.md new file mode 100644 index 0000000000..9471d461b1 --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/plan.md @@ -0,0 +1,280 @@ +--- +spec: docs/specs/prevent-agent-autostart-on-open/spec.md +created: 2026-08-11 +status: complete +--- + +# Implementation Plan: Prevent Agent Auto-Start On Open + +## Overview + +Add a per-user setting, `prevent_auto_start_agent_on_open`, that stops the web +UI from automatically starting or resuming an agent when a task is *opened* in +two situations: the post-restart recovered-idle shape (session exists, agent +process not running) and tasks sitting in the final step of their workflow. +When the setting is on, those tasks open with the agent stopped and the +existing manual start affordance (the "Start agent" button for never-started +sessions) is shown instead. + +The change spans: backend settings plumbing (models/DTO/service/controller/boot +payload), a small opt-in `auto_start` override on the `session.ensure` WS +contract, frontend settings plumbing (types/SSR/store/API client), the settings +UI card, and the two open-time gates (`useEnsureTaskSession` for the final-step +no-session case, `useSessionResumption` for the resume case). Order follows the +dependency chain: backend contracts first, settings plumbing, UI, then the +gating hooks, then E2E. + +--- + +## Backend + +### 1. User settings field + +- `apps/backend/internal/user/models/models.go` — add + `PreventAutoStartAgentOnOpen bool` with json tag + `prevent_auto_start_agent_on_open` to `UserSettings` (after + `ConfirmTaskArchive`). No DB migration: settings are a JSON blob. +- `apps/backend/internal/user/dto/dto.go` — add the field to `UserSettingsDTO` + (`FromUserSettings` at `:238`) and `*bool` to `UpdateUserSettingsRequest` + (after `ConfirmTaskArchive` at `:105`). +- `apps/backend/internal/user/service/service.go` — add `PreventAutoStartAgentOnOpen *bool` + to the service-level `UpdateUserSettingsRequest` (`:52`); apply it in + `applyTaskActionPreferences` (`:346` block); emit it in + `publishUserSettingsEvent` (`:773` map). +- `apps/backend/internal/user/controller/controller.go` — map + `req.PreventAutoStartAgentOnOpen` in `UpdateUserSettings` (`:61` block). +- `apps/backend/internal/user/store/sqlite.go` — persist the field in the + settings JSON blob: add `"prevent_auto_start_agent_on_open"` to the + `marshalUserSettingsPayload` map (`:519-573`) and a + `PreventAutoStartAgentOnOpen *bool` field to the `scanUserSettings` payload + struct (`:707-760`) with the pointer-guarded assignment. Default is `false` + (the zero value in `defaultUserSettings` at `:651`). +- `apps/backend/internal/backendapp/boot_state_routes.go` — add + `"preventAutoStartAgentOnOpen": settings.PreventAutoStartAgentOnOpen` to the + boot-payload map (`:459` block). + +### 2. `session.ensure` `auto_start` override + +- `apps/backend/internal/orchestrator/session_ensure.go` — add + `AutoStart *bool` to `EnsureSessionOptions`; in `EnsureSession`, when + `o.AutoStart != nil`, override the step-derived decision: + `autoStart := stepAllowsAutoStart(step); if o.AutoStart != nil { autoStart = *o.AutoStart }`. +- `apps/backend/internal/orchestrator/session_launch.go` — add a prepare-only + marker (e.g. `NoAgentLaunch bool`) to `LaunchSessionRequest`; `EnsureSession` + sets it when `AutoStart == &false`, and `shouldUpgradePassthroughPrepare` + (`:172-174`) returns false when it is set. Passthrough profiles are otherwise + eagerly upgraded into `launchStart`, which would start the agent despite the + override. +- `apps/backend/internal/orchestrator/handlers/handlers.go` — add + `AutoStart *bool \`json:"auto_start,omitempty"\`` to `wsEnsureSessionRequest` + and pass it through as `EnsureSessionOptions{AutoStart: req.AutoStart}`. +- Behavior: `auto_start: false` → `IntentPrepare` / `created_prepare` even when + the step has `auto_start_agent`, and never upgrades to a launch (including + passthrough profiles); absent/`true` → unchanged. + +--- + +## Frontend + +### 1. Settings plumbing + +- `apps/web/lib/types/http-user-settings.ts` — add + `prevent_auto_start_agent_on_open?: boolean` to `UserSettings` and + `UserSettingsUpdatePayload`. +- `apps/web/lib/ssr/user-settings.ts` — add `preventAutoStartAgentOnOpen: false` + to `createDefaultUserSettings`; hydrate in `buildBehaviorFields` + (`s.prevent_auto_start_agent_on_open ?? current.preventAutoStartAgentOnOpen`). +- `apps/web/lib/state/slices/settings/types.ts` — add + `preventAutoStartAgentOnOpen: boolean` to `UserSettingsState`. +- `apps/web/lib/services/session-launch-service.ts` — extend + `ensureTaskSession` opts with `autoStart?: boolean`; include + `auto_start: opts?.autoStart` in the `session.ensure` payload. + +### 2. Settings UI + +- `apps/web/components/settings/prevent-auto-start-agent-settings.tsx` (new) — + clone the `archive-confirmation-settings.tsx` pattern (SettingsCard + Switch + + `useSettingsSaveContributor`), persisting `prevent_auto_start_agent_on_open`. +- `apps/web/components/settings/general-settings.tsx` — render the new card in + `TaskActionsSettings` (first slot of the task-actions section). +- `apps/web/lib/settings-discovery/catalog/preferences.ts` — new target + `preventAutoStartOnOpen: "setting-prevent-auto-start-on-open"` on + `GENERAL_SETTINGS_TARGETS` plus a control definition under the task-actions + page. (The PageShell restructure #2322 moved the catalog here from + `catalog/general.ts`.) +- i18n — add `preventAutoStartAgentOnOpen` and `preventAutoStartAgentOnOpenHelp` + to `apps/web/src/locales/{en,pseudo,pt-pt,zh-cn}/settings.json` (help text + must use plain punctuation, no em dash). + +### 3. Open-time gates + +- `apps/web/hooks/domains/session/use-ensure-task-session.ts` — + - Extend `EnsureTaskInput` with `workflowStepId?: string | null` and + `workflowId?: string | null`. + - Read `state.userSettings.preventAutoStartAgentOnOpen` and resolve the + task's workflow step list workflow-aware: `state.kanban.steps` when the + task's workflow is the active one (`state.kanban.workflowId`), otherwise + `state.kanbanMulti.snapshots[workflowId]?.steps`. Missing workflow id or + step list → treated as "not final" (no gate). + - When the setting is on and the task's step is the terminal step of that + workflow, call `ensureTaskSession(taskId, { autoStart: false })`; + otherwise `ensureTaskSession(taskId)` as today. + - New pure helper (exported for unit tests), + `isFinalWorkflowStep(workflowStepId, steps)`. Terminal = max + `(position, id)` (ties broken by max id): step positions are + caller-supplied and not uniqueness-validated, so equal positions are + representable and must not make both steps terminal. +- `apps/web/hooks/domains/session/use-session-resumption.ts` — + - Read `state.userSettings.preventAutoStartAgentOnOpen` in + `useSessionResumption` and thread a `preventAutoStart` boolean into + `useSessionResetAndCheck` → `checkAndResume`. + - In `checkAndResume`, when `preventAutoStart` is true, skip the + `status.needs_resume && status.is_resumable` branch (do not call + `resumeWithSilentFallback`); set `resumptionState` to `"idle"` and record + the skip in the store (a `resumeSkippedSessionIds: Record` + map on the kanban tasks slice via a new `setResumeSkipped(sessionId, boolean)` + action — NOT a native `Set`, which would break the Immer-managed, + SSR-hydrated slice). The flag is keyed by session id, so it cannot leak + across sessions. + - Skip-flag semantics are confirmed-running-only and derived from live state, + not timing: + - RECORD only when `needs_resume && is_resumable && !is_agent_running` + AND the live store state is not STARTING/RUNNING. `checkAndResume` must + re-read the live session state immediately before recording + (`applyStatusToState` at `use-session-resumption.ts:244-251` merges the + status state into the store via `setTaskSession` + (`session-slice.ts:136-150` spreads incoming over existing)). + - Status hydration uses TIMESTAMP PRECEDENCE: preserve a live + STARTING/RUNNING state when the incoming status timestamp is absent or + not newer than the live session's `updated_at`; accept an incoming + terminal status (FAILED/CANCELLED/COMPLETED) only when its timestamp is + newer. Blanket protection would reject legitimate newer terminal + responses and leave the UI stuck with no recovery actions. + - CLEAR only on confirmed RUNNING: the WS `session.state_changed` handler + (`lib/ws/handlers/agent-session.ts:692-750`) deletes the flag on the + RUNNING transition only (NOT on STARTING — a failed manual resume emits + STARTING before the launch fails); the manual paths (`resumeSession()` at + `:491-522`, the Start button click at `message-renderer.tsx:55-64`) + clear it only when the launch response reports `state === "RUNNING"` + (successful resumes commonly return `state: "STARTING"` — launch + accepted, not agent running; `executor_resume.go:585`, + `session_launch.go:358-365`); rejections and `{ success: false }` keep + the flag. + - `setResumeSkipped(sessionId, true)` stays conditional in the slice + action (refuses when the current state is STARTING/RUNNING) as a second + line of defense. + - The manual `resumeSession()` action is NOT gated. +- Start agent button for the recovered-idle case — + `apps/web/components/task/chat/message-renderer.tsx`: + `TaskDescriptionStartButton` currently renders only for + `sessionState === "CREATED"`. Extend the visibility condition so it also + renders when the store marks the session as resume-skipped, BUT only for + non-FAILED sessions: `TaskDescriptionMessage` returns early for FAILED + sessions at `:119-134` (agent-styled message, no button slot), and FAILED + sessions keep their existing recovery actions (`recovery-resume-button` / + `recovery-fresh-button` in `action-message.tsx`). Dispatch the matching + intent: `buildStartCreatedRequest` for CREATED sessions, the resume request + builder for the skipped-resume case. +- Callers: + - `components/task/task-page-content.tsx` passes the normalized input + `{ id: task?.id, workflowStepId: task?.workflow_step_id, workflowId: task?.workflow_id }` + (the effective task is the HTTP `Task`, whose fields are snake_case). + - `components/kanban-with-preview.tsx` — `useSelectedTask` must include + `workflowId` in its returned subset (it currently drops it at `:171-180`), + so cross-workflow preview tasks resolve their own workflow's steps. + +--- + +## Tests + +| Behavior (spec scenario) | File | How | +|---|---|---| +| PATCH accepts and persists the setting; GET/boot payload returns it | `apps/backend/internal/user/dto/dto_test.go`, `internal/user/service/service_test.go` (or existing settings-update test) | unit: round-trip `UpdateUserSettingsRequest` → model → DTO; assert blob round-trip | +| Settings blob survives reload (true/false/omitted-legacy) | `apps/backend/internal/user/store/sqlite_test.go` | repo test: `SaveUserSettings` then `GetUserSettings` preserves the value; legacy JSON without the key loads the default `false` | +| `session.ensure` with `auto_start: false` prepares instead of starts | `apps/backend/internal/orchestrator/session_ensure_test.go` (or `session_ensure_office_test.go` pattern) | integration: seed task + step with `auto_start_agent`; call `EnsureSession` with `AutoStart: &false`; assert `Source == "created_prepare"`, `State == "CREATED"`; control case without override still `created_start` | +| passthrough profile never starts on `auto_start: false` | `apps/backend/internal/orchestrator/session_launch_test.go` | integration: mock agent manager reports `CLIPassthrough`; `EnsureSession` with `AutoStart: &false` stays prepared (`CREATED`, no `startTask`); without the override the passthrough upgrade still launches | +| WS handler passes `auto_start` through | `apps/backend/internal/orchestrator/handlers/handlers_test.go` | unit: parse `{task_id, auto_start:false}` → handler calls service with the option | +| SSR defaults and hydration | `apps/web/lib/ssr/user-settings.test.ts` | unit: default `false`; hydrate from `prevent_auto_start_agent_on_open` | +| ensure payload carries `auto_start` | extend `apps/web/hooks/domains/session/use-ensure-task-session.test.ts` (mocks `ensureTaskSession`) | unit: final-step + setting-on → called with `{ autoStart: false }`; non-final → without | +| final-step helper | new test beside the helper | unit: max `(position, id)` tie-break, equal positions resolve to one terminal step, missing step/steps → false | +| caller normalization (snake → camel input) | `apps/web/components/task/task-page-content` test or hook caller test | unit: task page passes `workflowStepId` from `workflow_step_id` | +| cross-workflow preview resolves the right steps | `apps/web/hooks/domains/session/use-ensure-task-session.test.ts` + preview test | unit: task from `kanbanMulti.snapshots[w]` uses snapshot steps, not the active workflow's | +| resume gate skips auto-resume and records the skip | `apps/web/hooks/domains/session/use-session-resumption.test.ts` | unit: `checkAndResume` with `needs_resume && is_resumable` and preventAutoStart → no launch, state idle, skip recorded in store; manual `resumeSession` still launches AND clears the flag only on success | +| failed launch keeps the retry button | `apps/web/hooks/domains/session/use-session-resumption.test.ts` + message-renderer test | unit: resume/start rejects or returns `{ success: false }` → skip flag retained, Start button still rendered (including after a WS STARTING event that precedes the failure) | +| delayed-status race: running WS event before stale status | `apps/web/lib/state/slices/kanban` slice test + `use-session-resumption.test.ts` | unit: WS `state_changed` → STARTING then a stale status response attempts to apply + record a skip → live state is NOT downgraded (timestamp precedence) and the flag is NOT set | +| stale vs newer terminal status precedence | `apps/web/hooks/domains/session/use-session-resumption.test.ts` | unit: an incoming FAILED/CANCELLED/COMPLETED status with a timestamp older than the live session is rejected; the same terminal status with a newer timestamp is accepted (recovery actions appear) | +| launch response clears only when RUNNING | `apps/web/hooks/domains/session/use-session-resumption.test.ts` + message-renderer test | unit: resume returns `{ success: true, state: "STARTING" }` → flag kept (WS RUNNING clears later); `{ success: true, state: "RUNNING" }` → flag cleared; rejections / `{ success: false }` → flag kept | +| WS clear only on RUNNING | `apps/web/lib/ws/handlers/agent-session.test.ts` (or slice test) | unit: `session.state_changed` to RUNNING deletes `resumeSkippedSessionIds[sessionId]`; STARTING does NOT delete it; hydration keeps the record shape intact | +| Start button renders for resume-skipped sessions (non-FAILED) | `apps/web/components/task/chat/message-renderer` test (or component test) | unit: `sessionState === "CREATED"` OR store resume-skipped flag (non-FAILED state) → button visible; FAILED + resume-skipped → no new button (recovery actions remain); button dispatches resume for the skipped case and clears the flag on success | +| settings card renders and saves | `apps/web/components/settings/prevent-auto-start-agent-settings.test.tsx` (mirror `archive-confirmation-settings.test.tsx`) | component: switch toggles, save calls `updateUserSettings({ prevent_auto_start_agent_on_open })` | +| i18n ratchet + em-dash check | — | `cd apps/web && pnpm run i18n:check && pnpm run i18n:ratchet` | + +## E2E Tests + +- **Scenario:** GIVEN setting ON and a task in the final workflow step with no + session, WHEN the task page is opened, THEN the Start agent button + (`[data-testid="task-description-start-button"]`) is visible and the agent + never starts on its own. +- **File:** `apps/web/e2e/tests/settings/prevent-auto-start-on-open.spec.ts` +- **What to verify:** + - Set the setting via `apiClient.saveUserSettings({ prevent_auto_start_agent_on_open: true })`. + - Create a custom workflow whose final step has + `on_enter: [{ type: "auto_start_agent" }]` — extend + `e2e/helpers/api-client.ts` `createWorkflowStep` with an `events` opt + (the backend `POST /api/v1/workflow/steps` already accepts `events`, + `internal/workflow/controller/controller.go` `CreateStepRequest`). + - Final-step case: create a task in that final step, open `/t/:id`, assert + the Start agent button appears and the agent stays stopped until clicked. + - Setting-off control: create a SEPARATE fresh task in the same final step + (never opened before, no session) — `useEnsureTaskSession` no-ops when a + session already exists, so reusing the setting-on task cannot exercise the + control. + - Recovered-idle case: seed a task+session, let the first turn finish, then + `backend.restart()` + `testPage.reload()` (the restart pattern from + `e2e/tests/session/session-resume.spec.ts`), assert no automatic resume + (the agent does not reach a running state on its own and the Start agent + button is visible), then click the button and assert the agent resumes. + - Control: with the setting off, the same final-step task auto-starts on + open (no start button; agent reaches a running/ready state). + - Isolation: `e2e/fixtures/test-base.ts` per-test settings reset (`:190-225`) + gains `prevent_auto_start_agent_on_open: false` so a test enabling the + setting cannot leak into later tests in the same worker. + - Mobile: add `e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts` + (same fixtures, phone viewport via `testPage.setViewportSize`, following + `mobile-general-settings.spec.ts`) asserting the Start agent button on the + final-step case. The gating hooks run on mobile through the shared + responsive `TaskPageContent` (`useResponsiveBreakpoint` at + `task-page-content.tsx:325`). + +## Verification Results + +All six tasks implemented with TDD and verified: + +- Backend: `go test ./internal/user/... ./internal/orchestrator/... ./internal/backendapp/... -race` — clean. golangci-lint on the PR diff — clean (after splitting the store test file and rebasing onto the then-current origin/main). +- Frontend: `pnpm run typecheck` — clean. Vitest suites (lib/ws/handlers, lib/state/slices/kanban, hooks/domains/session, lib/ssr, settings card, message-list-footer) — 753 tests passing. `pnpm run i18n:check` + `pnpm run i18n:ratchet` — clean. +- E2E (mock agent): `KANDEV_E2E_MOCK=true pnpm e2e:raw --project=chromium settings/prevent-auto-start-on-open.spec.ts` — 3/3 passing; `--project=mobile-chrome settings/mobile-prevent-auto-start-on-open.spec.ts` — 1/1 passing. +- Pre-commit hooks (harness, architecture, gofmt, golangci, prettier, web lint, i18n guard, commitlint) — passed on every commit; no bypasses. + +## Implementation Waves And Parallel Candidates + +``` +Wave 1 (sequential): +- [x] [task-01-backend-settings-field](task-01-backend-settings-field.md) +- [x] [task-02-backend-ensure-override](task-02-backend-ensure-override.md) +- [x] [task-03-frontend-settings-plumbing](task-03-frontend-settings-plumbing.md) +- [x] [task-04-settings-ui-card](task-04-settings-ui-card.md) +- [x] [task-05-open-time-gates](task-05-open-time-gates.md) + +Wave 2: +- [x] [task-06-e2e](task-06-e2e.md) +``` + +All tasks are sequential: 01→02 share the backend settings surface, 03 depends +on 01's contract, 04 depends on 03's store field, 05 depends on 03's API +client change, and 06 depends on 05's behavior. No parallel-safe candidates. + +## Open Questions + +- Office advanced-mode `ensureExecution` resume stays a no-op (the WS handler + drops `ensure_execution` today); the spec parks it out of scope until that + flow is wired. diff --git a/docs/plans/prevent-agent-autostart-on-open/task-01-backend-settings-field.md b/docs/plans/prevent-agent-autostart-on-open/task-01-backend-settings-field.md new file mode 100644 index 0000000000..488a01d336 --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-01-backend-settings-field.md @@ -0,0 +1,65 @@ +--- +id: "01-backend-settings-field" +title: "Backend user-settings field" +status: done +wave: 1 +parallelism: sequential +depends_on: [] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 01: Backend user-settings field + +## Acceptance + +- `UserSettings` gains `PreventAutoStartAgentOnOpen bool` with json tag + `prevent_auto_start_agent_on_open`; the value round-trips through + `FromUserSettings`, `UpdateUserSettingsRequest`, the service apply path, + `publishUserSettingsEvent`, and the SQLite settings blob + (`marshalUserSettingsPayload` / `scanUserSettings`). +- `PATCH /api/v1/user/settings` with `{"prevent_auto_start_agent_on_open": true}` + persists the value across a settings reload; omitting the key leaves it + unchanged (pointer semantics). +- The SSR boot payload exposes it as `preventAutoStartAgentOnOpen`. +- No DB migration: the settings blob already accepts new JSON fields. + +## Verification + +```bash +(cd apps/backend && go test ./internal/user/... ./internal/backendapp/... -race) +``` + +```bash +(cd apps/backend && make lint) +``` + +## Files Likely Touched +- `apps/backend/internal/user/models/models.go` (`UserSettings` struct) +- `apps/backend/internal/user/dto/dto.go` (`UserSettingsDTO` + `FromUserSettings` at `:238`, `UpdateUserSettingsRequest` at `:105`) +- `apps/backend/internal/user/dto/dto_test.go` +- `apps/backend/internal/user/service/service.go` (service `UpdateUserSettingsRequest` at `:52`, `applyTaskActionPreferences` at `:346`, `publishUserSettingsEvent` at `:773`) +- `apps/backend/internal/user/controller/controller.go` (`UpdateUserSettings` mapping at `:61`) +- `apps/backend/internal/user/store/sqlite.go` (`marshalUserSettingsPayload` at `:519`, `scanUserSettings` payload struct at `:707`) +- `apps/backend/internal/user/store/sqlite_test.go` +- `apps/backend/internal/backendapp/boot_state_routes.go` (boot-payload map at `:459`) + +## Dependencies + +None. + +## Inputs + +- Spec "Data model" and "API surface" sections. +- Existing pattern: `ConfirmTaskArchive` plumbing across the same files, + including the SQLite blob serialization in + `internal/user/store/sqlite.go` (`marshalUserSettingsPayload` writes + `confirm_task_archive`; `scanUserSettings` reads it via a `*bool` payload + field with a nil-guarded assignment). + +## Output Contract + +The field exists end to end on the backend: model → DTO → service apply → +controller → store blob → boot payload, with pointer-based PATCH semantics. +Tests pin the round-trip, the omitted-key behavior, and the store reload +(legacy JSON without the key loads the default `false`). diff --git a/docs/plans/prevent-agent-autostart-on-open/task-02-backend-ensure-override.md b/docs/plans/prevent-agent-autostart-on-open/task-02-backend-ensure-override.md new file mode 100644 index 0000000000..b9212074d7 --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-02-backend-ensure-override.md @@ -0,0 +1,74 @@ +--- +id: "02-backend-ensure-override" +title: "Backend session.ensure auto_start override" +status: done +wave: 1 +parallelism: sequential +depends_on: [] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 02: Backend `session.ensure` `auto_start` override + +## Acceptance + +- `EnsureSessionOptions` gains `AutoStart *bool`; `EnsureSession` honors it: + when `AutoStart` is `&false`, the session is created with + `IntentPrepare` / source `created_prepare` even when the resolved workflow + step has `auto_start_agent` in its on-enter actions. When `AutoStart` is nil + or `&true`, the step-derived decision is unchanged. +- The prepare-only request is NEVER upgraded to an agent launch: + `LaunchSessionRequest` gains a prepare-only marker (e.g. `NoAgentLaunch + bool`), `EnsureSession` sets it when `AutoStart == &false`, and + `shouldUpgradePassthroughPrepare` (`session_launch.go:172-174`) returns + false when it is set. Without this, passthrough profiles are eagerly + upgraded into `launchStart` and the agent starts anyway, violating the + contract. +- The WS `session.ensure` handler parses an optional `auto_start` field and + passes it through as the option. +- No behavior change for existing callers that never send `auto_start`. + +## Verification + +```bash +(cd apps/backend && go test ./internal/orchestrator/ -race -run 'TestEnsureSession|TestWsEnsureSession') +``` + +```bash +(cd apps/backend && go test ./internal/orchestrator/... ./internal/gateway/... -race) +``` + +## Files Likely Touched + +- `apps/backend/internal/orchestrator/session_ensure.go` (`EnsureSessionOptions` at `:26`, decision at `:87-94`) +- `apps/backend/internal/orchestrator/session_launch.go` (`LaunchSessionRequest` struct, `shouldUpgradePassthroughPrepare` at `:172-174`) +- `apps/backend/internal/orchestrator/handlers/handlers.go` (`wsEnsureSessionRequest` at `:100`, handler at `:104`) +- `apps/backend/internal/orchestrator/session_ensure_test.go` (or a new focused test file) +- `apps/backend/internal/orchestrator/session_launch_test.go` (passthrough upgrade regression) +- `apps/backend/internal/orchestrator/handlers/handlers_test.go` + +## Dependencies + +None (backend-only; the frontend sends the field from task 03). + +## Inputs + +- Spec "API surface → WebSocket `session.ensure`". +- `stepAllowsAutoStart` (`session_ensure.go:268`) and the existing + `session_ensure_test.go` / `session_ensure_office_test.go` seeding patterns + (a step whose on-enter has `auto_start_agent` → control case starts; + override case prepares). +- `launchPrepare` / `shouldUpgradePassthroughPrepare` (`session_launch.go:148-174`): + prepare requests for passthrough profiles are eagerly upgraded to + `launchStart` unless `AutoStart` or `DeferredStart` is set; the new + prepare-only marker must suppress that upgrade. + +## Output Contract + +`EnsureSession` accepts an explicit start-vs-prepare override; the WS contract +gains the optional `auto_start` field without breaking existing clients. +`auto_start: false` never starts an agent, including for passthrough profiles +(the `shouldUpgradePassthroughPrepare` upgrade is suppressed). Tests pin: +override-false prepares, override-absent starts, handler passthrough, and a +passthrough-profile regression (override-false still prepares). diff --git a/docs/plans/prevent-agent-autostart-on-open/task-03-frontend-settings-plumbing.md b/docs/plans/prevent-agent-autostart-on-open/task-03-frontend-settings-plumbing.md new file mode 100644 index 0000000000..95f204e221 --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-03-frontend-settings-plumbing.md @@ -0,0 +1,60 @@ +--- +id: "03-frontend-settings-plumbing" +title: "Frontend settings plumbing" +status: done +wave: 1 +parallelism: sequential +depends_on: ["01-backend-settings-field"] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 03: Frontend settings plumbing + +## Acceptance + +- `UserSettings` / `UserSettingsUpdatePayload` carry + `prevent_auto_start_agent_on_open?: boolean`; `UserSettingsState` carries + `preventAutoStartAgentOnOpen: boolean` defaulting to `false`. +- SSR hydration maps the snake_case API field into the store field, keeping the + default when the field is absent. +- `ensureTaskSession` accepts `{ autoStart?: boolean }` and includes + `auto_start` in the `session.ensure` WS payload only when explicitly set + (absent otherwise, so existing behavior is untouched). + +## Verification + +```bash +(cd apps/web && pnpm run typecheck) +``` + +```bash +(cd apps/web && pnpm vitest run lib/ssr/user-settings.test.ts lib/services/session-launch-service.test.ts hooks/domains/session/use-ensure-task-session.test.ts) +``` + +## Files Likely Touched + +- `apps/web/lib/types/http-user-settings.ts` (`UserSettings`, `UserSettingsUpdatePayload`) +- `apps/web/lib/ssr/user-settings.ts` (`createDefaultUserSettings` at `:26`, `buildBehaviorFields` at `:243`) +- `apps/web/lib/ssr/user-settings.test.ts` +- `apps/web/lib/state/slices/settings/types.ts` (`UserSettingsState` at `:207`) +- `apps/web/lib/services/session-launch-service.ts` (`ensureTaskSession` at `:76`) +- `apps/web/hooks/domains/session/use-ensure-task-session.test.ts` (mock signature keeps matching) + +## Dependencies + +Task 01 (backend contract the payload maps to). + +## Inputs + +- Spec "Data model" and "API surface". +- Existing patterns: `confirm_task_archive` / `confirmTaskArchive` across the + same frontend files; `ensure_execution` payload precedent in + `session-launch-service.ts`. + +## Output Contract + +The setting is readable from `state.userSettings.preventAutoStartAgentOnOpen` +after boot hydration and writable via `updateUserSettings`. `ensureTaskSession` +can request prepare-only on the wire. Tests pin defaults, hydration, and the +`auto_start` payload. diff --git a/docs/plans/prevent-agent-autostart-on-open/task-04-settings-ui-card.md b/docs/plans/prevent-agent-autostart-on-open/task-04-settings-ui-card.md new file mode 100644 index 0000000000..612f7e2bcc --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-04-settings-ui-card.md @@ -0,0 +1,65 @@ +--- +id: "04-settings-ui-card" +title: "Settings UI card" +status: done +wave: 1 +parallelism: sequential +depends_on: ["03-frontend-settings-plumbing"] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 04: Settings UI card + +## Acceptance + +- Settings → Task Actions shows a new switch card "Prevent auto-start on open" + with helper text describing the two gated cases (post-restart open, final + workflow step). All copy goes through `t()`; no em dash (U+2014). +- The switch follows the `ArchiveConfirmationSettings` pattern: draft state, + `data-settings-dirty`, `useSettingsSaveContributor`, save via + `updateUserSettings({ prevent_auto_start_agent_on_open })`, store updated + through `setUserSettings`. The contributor id MUST be unique (e.g. + `general-prevent-auto-start-on-open`): the save registry is a `Map` keyed by + contributor id (`settings-save-provider.tsx:224-248`), and the archive card + already owns `general-task-actions` (`archive-confirmation-settings.tsx:33`), + so a literal clone would silently replace the archive contributor. +- The card registers a settings-discovery target and definition. +- i18n check and ratchet pass. + +## Verification + +```bash +(cd apps/web && pnpm run typecheck && pnpm run i18n:check && pnpm run i18n:ratchet) +``` + +```bash +(cd apps/web && pnpm vitest run components/settings/prevent-auto-start-agent-settings.test.tsx components/settings/archive-confirmation-settings.test.tsx) +``` + +## Files Likely Touched + +- `apps/web/components/settings/prevent-auto-start-agent-settings.tsx` (new; clone `archive-confirmation-settings.tsx`) +- `apps/web/components/settings/prevent-auto-start-agent-settings.test.tsx` (new; mirror `archive-confirmation-settings.test.tsx`) +- `apps/web/components/settings/general-settings.tsx` (`TaskActionsSettings`) +- `apps/web/lib/settings-discovery/catalog/preferences.ts` (target + control definition; mirror `archiveConfirmation` at `:35`/`:311`; `GENERAL_SETTINGS_TARGETS` lives here after the PageShell restructure #2322) +- `apps/web/src/locales/en/settings.json`, `apps/web/src/locales/pseudo/settings.json`, `apps/web/src/locales/pt-pt/settings.json`, `apps/web/src/locales/zh-cn/settings.json` + +## Dependencies + +Task 03 (store field + `updateUserSettings` payload). + +## Inputs + +- Spec "What" bullet on the settings surface. +- `components/settings/archive-confirmation-settings.tsx` as the pattern + reference; `GENERAL_SETTINGS_TARGETS` structure. + +## Output Contract + +The setting is user-visible and persisted from the Task Actions settings page. +Component test pins toggle → save payload; i18n ratchets stay green. + +Proposed copy (translated via the four locale files): +- Title: "Prevent auto-start on open" +- Help: "Don't start the agent automatically when opening a task after a restart or from the final workflow step. The Start agent button is shown instead." diff --git a/docs/plans/prevent-agent-autostart-on-open/task-05-open-time-gates.md b/docs/plans/prevent-agent-autostart-on-open/task-05-open-time-gates.md new file mode 100644 index 0000000000..cf9b7aa51b --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-05-open-time-gates.md @@ -0,0 +1,144 @@ +--- +id: "05-open-time-gates" +title: "Open-time gates in ensure and resume hooks" +status: done +wave: 1 +parallelism: sequential +depends_on: ["03-frontend-settings-plumbing"] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 05: Open-time gates in ensure and resume hooks + +## Acceptance + +- `useEnsureTaskSession` accepts `{ id, workflowStepId, workflowId }` and reads + `state.userSettings.preventAutoStartAgentOnOpen`. When the setting is on and + the task's step is the terminal step of the task's OWN workflow, it calls + `ensureTaskSession(taskId, { autoStart: false })`; all other cases call + `ensureTaskSession(taskId)` exactly as today. +- The terminal-step predicate is deterministic even with equal positions: + `isFinalWorkflowStep(workflowStepId, steps)` returns true only when the + step's `(position, id)` is the maximum of all steps under that ordering + (max `position`, ties broken by max `id`). Workflow-step positions are + caller-supplied and not uniqueness-validated + (`internal/workflow/controller/controller.go` `CreateStepRequest`, + `internal/workflow/service/service.go:335-344`), so a tie is representable + and MUST NOT make both steps terminal. Add an equal-position unit test. +- The step list is resolved workflow-aware: the active workflow's steps + (`state.kanban.steps` when `task.workflowId` matches + `state.kanban.workflowId`) or the multi-workflow snapshot's steps + (`state.kanbanMulti.snapshots[task.workflowId]?.steps`). Missing workflow id + or step list → treated as "not final" (no gate). +- Callers pass normalized input: `task-page-content.tsx` maps the HTTP task's + snake_case fields (`workflow_step_id`, `workflow_id`); `kanban-with-preview.tsx` + `useSelectedTask` includes `workflowId` in its returned subset so + cross-workflow preview tasks resolve their own steps. +- `useSessionResumption`'s automatic check no longer auto-resumes when the + setting is on: with `status.needs_resume && status.is_resumable` it skips + `resumeWithSilentFallback`, settles on `"idle"`, and records the skip in the + store as `resumeSkippedSessionIds: Record` on the kanban tasks + slice via a new `setResumeSkipped(sessionId, boolean)` action. Do NOT use a + native `Set`: the kanban slice is Immer-managed (`zustand/immer`, no + `enableMapSet` configured) and SSR-hydrated, so a `Set` breaks mutation and + serialization. The manual `resumeSession()` action and the + `is_agent_running` / `needs_workspace_restore` branches are unchanged. +- Skip-flag semantics are monotonic and derived from live state, not timing: + - RECORD the skip only when `status.needs_resume && status.is_resumable && + !status.is_agent_running` AND the live store state for the session is not + STARTING or RUNNING. `checkAndResume` MUST re-read the live session state + immediately before recording (not rely on the status response alone): + `applyStatusToState` merges the status state into the store and can + downgrade a newer STARTING/RUNNING state to the stale status state before + the guard runs. + - Status hydration uses timestamp precedence, not blanket protection: + preserve a live STARTING/RUNNING session state when the incoming + `task.session.status` timestamp is absent or NOT newer than the live + session's `updated_at`; ACCEPT an incoming terminal status (FAILED, + CANCELLED, COMPLETED) when its timestamp IS newer. Blanket protection + would reject a legitimate newer terminal response and leave the UI stuck + in STARTING/RUNNING with no recovery actions + (`applyStatusToState` at `use-session-resumption.ts:244-251` merges via + `setTaskSession`; `session-slice.ts:136-150` spreads incoming over + existing). Add tests for both a stale terminal response (rejected) and a + newer terminal response (accepted). + - CLEAR the flag only on CONFIRMED RUNNING: the WS `session.state_changed` + handler (`lib/ws/handlers/agent-session.ts:692-750`) deletes it on the + RUNNING transition only (NOT on STARTING — a failed manual resume emits + STARTING before the launch fails, and clearing there would drop the retry + affordance). The manual paths (`resumeSession()` at + `use-session-resumption.ts:491-522`, the Start button click at + `message-renderer.tsx:55-64`) clear it only when the launch response + reports `state === "RUNNING"` — a successful resume commonly returns + `state: "STARTING"` (launch accepted, not agent running: + `executor_resume.go:585` builds the execution as `SessionStateStarting`, + `executionToLaunchResponse` at `session_launch.go:358-365` copies it), so + success alone is NOT confirmation; the WS RUNNING transition (or a later + status response reporting RUNNING) does the clearing. Rejections and + `{ success: false }` keep the flag. + - `setResumeSkipped(sessionId, true)` remains conditional in the slice + action (refuses when the current state is STARTING/RUNNING) as a second + line of defense. +- The Start agent button (`TaskDescriptionStartButton` in + `message-renderer.tsx`) renders for `sessionState === "CREATED"` AND for + resume-skipped (recovered-idle) sessions whose state is NOT FAILED; for the + recovered-idle case it dispatches the resume request builder instead of + `buildStartCreatedRequest`. FAILED sessions are excluded: the renderer + returns early at `:119-134` for FAILED, and they keep their existing + recovery actions (`recovery-resume-button` / `recovery-fresh-button`). + +## Verification + +```bash +(cd apps/web && pnpm run typecheck) +``` + +```bash +(cd apps/web && pnpm vitest run hooks/domains/session/use-ensure-task-session.test.ts hooks/domains/session/use-session-resumption.test.ts components/task/chat/message-renderer.test.tsx) +``` + +## Files Likely Touched + +- `apps/web/hooks/domains/session/use-ensure-task-session.ts` (+ its test; add a `isFinalWorkflowStep(workflowStepId, steps)` helper, exported for tests) +- `apps/web/hooks/domains/session/use-session-resumption.ts` (+ its test; thread `preventAutoStart` into `checkAndResume` via `useSessionResetAndCheck`) +- `apps/web/lib/state/slices/kanban/types.ts` + `kanban-slice.ts` (the slice owning `tasks.activeSessionId`): add `resumeSkippedSessionIds: Record` state + a `setResumeSkipped` action (property assignment / `delete`) +- `apps/web/components/task/chat/message-renderer.tsx` (+ test): Start button visibility for resume-skipped non-FAILED sessions, resume intent dispatch, and flag clearing on click +- `apps/web/lib/ws/handlers/agent-session.ts` (+ test): clear the skip flag ONLY on a `session.state_changed` transition to RUNNING; never clear it on STARTING +- `apps/web/hooks/domains/session/use-session-resumption.ts`: monotonic status application + re-read-before-record + clear-on-success (covered by its test) +- `apps/web/components/task/task-page-content.tsx`: pass `{ id, workflowStepId: task?.workflow_step_id, workflowId: task?.workflow_id }` +- `apps/web/components/kanban-with-preview.tsx` (+ test): `useSelectedTask` returns `workflowId` + +## Dependencies + +Task 03 (store field + `ensureTaskSession` `autoStart` opt), Task 04 (Start +button copy covers both cases). + +## Inputs + +- Spec scenarios 1, 2, 3, 5, 7, 8 and the "State machine" table. +- `useEnsureTaskSession` current flow: fires once per `(taskId, retryToken)` when + the task has no sessions; the latch must keep working with the widened input. +- `checkAndResume` branch order at `use-session-resumption.ts:284-336`; + `state.kanban.steps` position semantics (sorted, `position` ascending) and + `state.kanbanMulti.snapshots` (keyed by workflow id, each with its own + `steps`); `TaskDescriptionStartButton` condition at + `message-renderer.tsx:135-149` (currently `sessionState === "CREATED"` only). + +## Output Contract + +Opening a task honors the setting on both kanban surfaces: +final-step + no-session → prepare-only ensure (CREATED session, Start agent +button rendered); post-restart idle session (non-FAILED) → no auto-resume, +skip recorded, Start agent button rendered with a resume action; resumable +FAILED sessions → no auto-resume, existing recovery actions retained. The skip +flag is confirmed-running-only: it is recorded only when the agent is +verifiably stopped (live state re-checked; status hydration preserves live +STARTING/RUNNING unless a NEWER terminal status arrives) and cleared only on +confirmed RUNNING (WS RUNNING transition or a launch response with +`state === "RUNNING"`); failed launches and `STARTING` responses keep the +retry button. Unit tests pin each branch, including the non-gated controls, +the snake→camel caller normalization, the cross-workflow preview resolution, +the equal-position tie-break, the delayed-status race (WS STARTING then stale +status), the stale-vs-newer terminal status precedence, and the failed-launch +retention. diff --git a/docs/plans/prevent-agent-autostart-on-open/task-06-e2e.md b/docs/plans/prevent-agent-autostart-on-open/task-06-e2e.md new file mode 100644 index 0000000000..2184755ccf --- /dev/null +++ b/docs/plans/prevent-agent-autostart-on-open/task-06-e2e.md @@ -0,0 +1,91 @@ +--- +id: "06-e2e" +title: "E2E: prevent auto-start on open" +status: done +wave: 2 +parallelism: sequential +depends_on: ["05-open-time-gates"] +plan: "plan.md" +spec: "../../specs/prevent-agent-autostart-on-open/spec.md" +--- + +# Task 06: E2E — prevent auto-start on open + +## Acceptance + +- **Final-step case:** with the setting on, opening a task whose current + workflow step is the final step (and has `auto_start_agent` in its on-enter + actions) shows the Start agent button + (`[data-testid="task-description-start-button"]`) and does not start an + agent on its own. Clicking the button starts the agent. +- **Recovered-idle case:** with the setting on, after a backend restart a + task whose session needs resume does not auto-resume; the Start agent button + is visible and the agent stays stopped until clicked, then resumes. +- **Setting-off control:** with the setting off, a SEPARATE fresh task in the + same final step (never opened before, no session) auto-starts on open (no + start button; agent reaches a running/ready state). The control must not + reuse the setting-on task: `useEnsureTaskSession` no-ops once a session + exists, so a reused task cannot exercise fresh auto-start. +- **Isolation:** `e2e/fixtures/test-base.ts` per-test settings reset + (`:190-225`) gains `prevent_auto_start_agent_on_open: false` — PATCH omits + the field as "unchanged", so without the reset a test enabling the setting + leaks into later tests in the same worker. +- **Mobile:** `e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts` + (same fixtures, phone viewport, `mobile-general-settings.spec.ts` pattern) + asserts the Start agent button for the final-step case. The gating hooks run + on mobile through the shared responsive `TaskPageContent` + (`useResponsiveBreakpoint` at `task-page-content.tsx:325`). + +## Verification + +```bash +cd apps && pnpm install --frozen-lockfile +``` + +```bash +(cd apps/web && KANDEV_E2E_MOCK=true pnpm e2e:raw -- --project=chromium settings/prevent-auto-start-on-open.spec.ts settings/mobile-prevent-auto-start-on-open.spec.ts) +``` + +## Files Likely Touched + +- `apps/web/e2e/tests/settings/prevent-auto-start-on-open.spec.ts` (new) +- `apps/web/e2e/tests/settings/mobile-prevent-auto-start-on-open.spec.ts` (new, phone viewport) +- `apps/web/e2e/fixtures/test-base.ts` (per-test settings reset at `:190-225`) +- `apps/web/e2e/helpers/api-client.ts`: + - `saveUserSettings` (`:926`) gains `prevent_auto_start_agent_on_open?: boolean` + (there is no `updateUserSettings` helper — the settings PATCH helper is + named `saveUserSettings`). + - `createWorkflowStep` (`:701`) gains an `events` opt, e.g. + `events?: { on_enter?: Array<{ type: string; config?: Record }> }`, + passed through as `events` — the backend `POST /api/v1/workflow/steps` + already accepts `events` (`internal/workflow/controller/controller.go` + `CreateStepRequest`). + +## Dependencies + +Task 05 (the gating behavior under test), Task 03 (the setting is settable via +`saveUserSettings`). + +## Inputs + +- Spec scenarios 2, 4, 5. +- Existing patterns: + - `apps/web/e2e/tests/settings/startup-page.spec.ts` (settings UI flow). + - `apps/web/e2e/tests/session/session-resume.spec.ts` `:44-85` — the + backend-restart pattern: `backend.restart()` then `testPage.reload()` + (this is the correct restart fixture; `session-recovery.spec.ts` covers + agent-crash recovery buttons, not backend restarts). + - `api-client.ts` `createWorkflow` / `createWorkflowStep` / `createTask` + with `workflow_id` + `workflow_step_id`. +- Note: built-in final steps (office-default, kanban) do NOT carry + `auto_start_agent`; the fixture must create a custom workflow through the + API whose last step has `on_enter: [{ type: "auto_start_agent" }]`. + +## Output Contract + +The spec's two user-visible gates are pinned end to end with the mock agent: +final-step no-auto-start and post-restart no-auto-resume, each with the Start +agent button visible and a working click-through. Control case (setting off) +asserts the current auto-start behavior. Cleanup: fixture-only workflows/tasks +created by the spec are removed in teardown (try/finally pattern used by +sibling specs). diff --git a/docs/public/tasks-and-workflows.md b/docs/public/tasks-and-workflows.md index d0eafdd0f3..98623a0e4d 100644 --- a/docs/public/tasks-and-workflows.md +++ b/docs/public/tasks-and-workflows.md @@ -207,6 +207,25 @@ background** after its foreground yields while a recognized async subagent, immediately and the child may continue streaming. Other providers and foreground-generating Claude turns retain the coarse queueing behavior. +### Prevent auto-start on open + +Under **Settings → General → Task actions**, the **Prevent auto-start on open** +preference is off by default. When enabled, opening a task never launches or +resumes its agent on its own; it shows the **Start agent** button instead. The +preference applies in two situations: + +- **Opening a task in the final step of its workflow.** The task opens with a + prepared session and the agent stays stopped until you select **Start agent**. + Opening the same task with the preference off keeps the workflow step's + normal auto-start behavior. +- **Opening a task whose agent was stopped by a Kandev restart.** The session + is recovered and shown stopped instead of being resumed automatically. Select + **Start agent** to resume it. + +The preference only gates opening a task. Choosing **Start agent** (or a +workflow step transition) always starts the agent as usual, and a failed or +interrupted session still shows its recovery actions. + ## Find and organize tasks On desktop and tablet, the header switches between **Kanban**, **Pipeline**, and **List**. Kanban and Pipeline show the same workflow steps in different layouts. Kandev remembers the last selected view in that browser on the current device. Phones offer **Kanban** and **List** only; a saved desktop Pipeline preference is kept but shown as Kanban on the phone. diff --git a/docs/specs/INDEX.md b/docs/specs/INDEX.md index 21ec59fa7a..b1e19b2a26 100644 --- a/docs/specs/INDEX.md +++ b/docs/specs/INDEX.md @@ -100,6 +100,7 @@ Kandev's task model: documents, execution stages, labels, blocker escalation, su | [explicit-completion-signal](workflow/explicit-completion-signal/spec.md) | shipped | | [cancelled-turn-completion](workflow/cancelled-turn-completion/spec.md) | building | | [conditional-session-settings](workflow-session-settings/spec.md) | approved | +| [prevent-agent-autostart-on-open](prevent-agent-autostart-on-open/spec.md) | draft | | [workflow-duplication](workflow-duplication/spec.md) | draft | ## agents/ — agent governance diff --git a/docs/specs/prevent-agent-autostart-on-open/spec.md b/docs/specs/prevent-agent-autostart-on-open/spec.md new file mode 100644 index 0000000000..88d8ca5808 --- /dev/null +++ b/docs/specs/prevent-agent-autostart-on-open/spec.md @@ -0,0 +1,166 @@ +--- +status: draft +created: 2026-08-11 +owner: platform +--- + +# Prevent Agent Auto-Start On Open + +## Why + +Opening a task after a kandev restart silently starts (or resumes) the agent: +a session in a normal active state with no running process is resumed the +moment its task page loads, and a task in the final workflow step can have a +fresh agent auto-started when the step's on-enter action allows it. Users who +want to inspect the task first, or tasks that are effectively done, get an +agent spinning up unprompted. There is no way to keep the agent stopped on +open and start it explicitly instead. + +## What + +- A new per-user setting, `prevent_auto_start_agent_on_open` (default `false`), + surfaced in Settings → Task Actions as a switch. +- When the setting is ON, opening a task whose session exists but whose agent + is not running (the post-restart / recovered-idle shape) MUST NOT + automatically resume the agent. The task opens with the agent stopped and a + Start agent button is shown in the chat; clicking it resumes the agent. + (The existing session-menu resume and chat composer remain available too.) + For FAILED-but-resumable sessions the existing recovery actions (Resume + session / Start fresh session buttons) remain the manual affordance; the + new Start agent button is not rendered for FAILED sessions. +- When the setting is ON, opening a task whose current workflow step is the + final step of its workflow MUST NOT auto-start the agent when the task has + no session. The session is created in the never-started (prepared) state + and the Start agent button is shown. +- When the setting is OFF (default), opening a task behaves exactly as today. +- The setting gates only automatic starts triggered by *opening* a task. It + MUST NOT affect: workflow step transitions whose on-enter actions include + `auto_start_agent`, explicit user actions (Start agent, Resume, sending a + message), or watcher/automation/PR-triggered starts. + +## Data model + +The setting lives in the existing per-user settings blob (the `settings` +column of the `users` table, serialized as JSON). No schema migration. + +``` +users.settings.prevent_auto_start_agent_on_open bool default false +``` + +It is read by the web SPA from the boot payload and the `GET +/api/v1/user/settings` response, and written via `PATCH /api/v1/user/settings`. + +## API surface + +### User settings + +- `GET /api/v1/user/settings` returns the field as + `prevent_auto_start_agent_on_open` inside `settings`. +- `PATCH /api/v1/user/settings` accepts an optional + `prevent_auto_start_agent_on_open: bool`; omitted means "leave unchanged". +- The SSR boot payload exposes it as `preventAutoStartAgentOnOpen` (camelCase), + matching the other boot-payload settings keys. + +### WebSocket `session.ensure` + +The `session.ensure` WS request gains an optional `auto_start: bool` override. + +- Request shape: `{ task_id: string, auto_start?: boolean }` (plus the + existing optional fields). +- When `auto_start` is explicitly `false`, the backend creates the session in + the workspace-only (prepared / `created_prepare`) mode even when the task's + workflow step would otherwise allow auto-start (`created_start`). The + session is created in the never-started (`CREATED`) state. +- When `auto_start` is absent or `true`, the current behavior is unchanged: + the backend decides start-vs-prepare from the resolved agent profile and the + step's `auto_start_agent` on-enter action. +- The response shape is unchanged. + +## State machine + +No session states are added or removed. The setting changes only whether an +auto-start or auto-resume is *triggered by opening the task page*: + +| Trigger | Setting OFF (default) | Setting ON | +|---|---|---| +| Open task, no session, step allows auto-start | agent starts (`created_start`) | non-final step: unchanged; final step: `created_prepare`, Start agent button shown | +| Open task, session exists, agent not running, session resumable | auto-resume (`session.launch` intent=resume) | no auto-resume; session stays stopped and a Start agent button (resume action) is shown in the chat | +| Open task, agent already running | no-op | no-op (unchanged) | +| Workflow step transition with `auto_start_agent` on-enter | agent starts | agent starts (unchanged) | +| User clicks Start agent / Resume / sends a message | agent starts | agent starts (unchanged) | + +## Failure modes + +- The kanban workflow steps are not (yet) loaded in the client store when the + final-step check runs: the task is treated as "not in the final step", so + the ensure gate does not apply and behavior matches the setting OFF state. + Safe default: never silently block a start because of missing metadata. +- The user settings fail to hydrate (SSR fallback): the setting reads `false` + and behavior matches today. +- `session.ensure` with `auto_start: false` on a task whose agent profile + cannot be resolved: the same prepare-only outcome as today's no-profile + path; no error is surfaced beyond the existing behavior. + +## Persistence guarantees + +The setting is per-user, stored in `users.settings` (JSON blob serialized by +`internal/user/store/sqlite.go`), and survives kandev restarts. It is hydrated +into the web boot payload on every page load. There is no per-workspace or +per-task variant in this feature. + +## Scenarios + +- **GIVEN** the setting is ON and a task's session is in an active state with a + resume token but no running agent (post-restart shape), **WHEN** the user + opens the task page, **THEN** no `session.launch` resume request is sent on + open, the session stays stopped, and the task page shows a Start agent + button that resumes the agent when clicked. +- **GIVEN** the setting is ON and a task's session is FAILED but resumable, + **WHEN** the user opens the task page, **THEN** no auto-resume is sent on + open and the session keeps the existing recovery actions (Resume session and + Start fresh session buttons). The new Start agent button is not rendered for + FAILED sessions. +- **GIVEN** the setting is ON and the task's current workflow step is the final + step, **WHEN** the user opens the task and it has no session, **THEN** + `session.ensure` is called with `auto_start: false`, the session is created + in the prepared (`CREATED`) state, and the Start agent button is shown + without any agent process starting. +- **GIVEN** the setting is ON and the task's current workflow step is NOT the + final step, **WHEN** the user opens the task and it has no session, **THEN** + auto-start behavior is unchanged (the agent starts when the step's on-enter + action allows it). +- **GIVEN** the setting is OFF (default), **WHEN** the user opens any task, + **THEN** today's auto-start and auto-resume behavior is unchanged. +- **GIVEN** the setting is ON and a task in the final step already has a + never-started (`CREATED`) session, **WHEN** the task is opened, **THEN** the + Start agent button is shown and no agent starts. +- **GIVEN** the setting is ON, **WHEN** the user explicitly starts or resumes + the agent (Start agent button, session menu Resume, or sending a message), + **THEN** the agent starts normally. +- **GIVEN** the setting is ON, **WHEN** a workflow step transition with + `auto_start_agent` in its on-enter actions moves the task into that step, + **THEN** the agent still auto-starts. +- **GIVEN** the setting is ON and a task is opened in the kanban preview + panel, **WHEN** the preview opens, **THEN** the same gates apply (no + auto-resume, no final-step auto-start). + +## Out of scope + +- The office board task pages (simple and advanced mode). They do not + auto-start or auto-resume agents on open today (`useEnsureTaskSession` and + `useSessionResumption` are not wired into those flows); the latent + `ensure_execution` gap in the `session.ensure` WS handler is left as-is. +- Watcher / automation / PR-triggered auto-starts. They are not "opening a + task". +- Workflow on-enter `auto_start_agent` transitions. Only open-time behavior is + gated. +- Server-side enforcement of the preference for non-web clients. The gate is + implemented by the web client not issuing the resume/start request; the + backend contract change is an opt-in request override. +- A per-workspace or per-workflow variant of the setting. + +## Open questions + +- Whether the option should also gate the office advanced mode's + `ensureExecution` resume once that WS field is actually wired. Currently a + no-op; intentionally out of scope until the office flow auto-starts.