From 8c70aee27d3587af8148304005cec3cb26073d1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Thu, 7 May 2026 18:42:57 +0100 Subject: [PATCH] fix(workflows): hide improve-kandev system workflow from settings UI (#842) --- apps/backend/cmd/kandev/e2e_reset.go | 54 ++++++++-- apps/backend/cmd/kandev/helpers.go | 2 +- apps/backend/config/workflows/loader.go | 32 ++++++ .../backend/internal/improvekandev/handler.go | 11 ++ .../internal/task/service/service_events.go | 1 + .../task/service/service_resources.go | 21 ++++ .../task/service/service_workflow_test.go | 39 +++++++ .../internal/workflow/service/service.go | 19 +++- .../internal/workflow/service/service_test.go | 15 +++ apps/web/e2e/helpers/api-client.ts | 15 +++ .../tests/workflow/workflow-settings.spec.ts | 46 ++++++++ .../settings/use-workflow-settings.test.ts | 41 +++++++ .../domains/settings/use-workflow-settings.ts | 14 ++- apps/web/lib/types/backend.ts | 1 + apps/web/lib/ws/handlers/workflows.test.ts | 102 ++++++++++++++++++ apps/web/lib/ws/handlers/workflows.ts | 93 +++++++++------- 16 files changed, 453 insertions(+), 53 deletions(-) create mode 100644 apps/web/lib/ws/handlers/workflows.test.ts diff --git a/apps/backend/cmd/kandev/e2e_reset.go b/apps/backend/cmd/kandev/e2e_reset.go index 63b4b2a046..3ac0c4a8e5 100644 --- a/apps/backend/cmd/kandev/e2e_reset.go +++ b/apps/backend/cmd/kandev/e2e_reset.go @@ -10,18 +10,29 @@ import ( "github.com/kandev/kandev/internal/common/logger" sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" + taskservice "github.com/kandev/kandev/internal/task/service" ) -// registerE2EResetRoutes registers the E2E data-reset endpoint. -// The endpoint is available when KANDEV_MOCK_AGENT is "true" or "only" (dev/E2E modes). -func registerE2EResetRoutes(router *gin.Engine, repo *sqliterepo.Repository, log *logger.Logger) { +// registerE2EResetRoutes registers the E2E test-only endpoints. +// The endpoints are available when KANDEV_MOCK_AGENT is "true" or "only" (dev/E2E modes). +func registerE2EResetRoutes(router *gin.Engine, repo *sqliterepo.Repository, taskSvc *taskservice.Service, log *logger.Logger) { mockMode := os.Getenv("KANDEV_MOCK_AGENT") if mockMode != "true" && mockMode != "only" { return } api := router.Group("/api/v1/e2e") - api.DELETE("/reset/:workspaceId", func(c *gin.Context) { + api.DELETE("/reset/:workspaceId", handleE2EReset(repo, log)) + // Hidden-workflow factory: lets E2E tests cover the system-only + // workflow path (e.g. improve-kandev) without depending on the real + // bootstrap endpoint, which clones from GitHub and shells out to gh. + api.POST("/hidden-workflow", handleE2ECreateHiddenWorkflow(taskSvc, log)) + + log.Info("registered E2E endpoints (test-only)") +} + +func handleE2EReset(repo *sqliterepo.Repository, log *logger.Logger) gin.HandlerFunc { + return func(c *gin.Context) { workspaceID := c.Param("workspaceId") // Optional: comma-separated workflow IDs to keep (e.g., the seeded workflow). @@ -50,7 +61,36 @@ func registerE2EResetRoutes(router *gin.Engine, repo *sqliterepo.Repository, log "deleted_tasks": deletedTasks, "deleted_workflows": deletedWorkflows, }) - }) - - log.Info("registered E2E reset endpoint (test-only)") + } +} + +type e2eHiddenWorkflowRequest struct { + WorkspaceID string `json:"workspace_id"` + Name string `json:"name"` +} + +func handleE2ECreateHiddenWorkflow(taskSvc *taskservice.Service, log *logger.Logger) gin.HandlerFunc { + return func(c *gin.Context) { + var body e2eHiddenWorkflowRequest + if err := c.ShouldBindJSON(&body); err != nil || body.WorkspaceID == "" || body.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id and name are required"}) + return + } + workflow, err := taskSvc.CreateWorkflow(c.Request.Context(), &taskservice.CreateWorkflowRequest{ + WorkspaceID: body.WorkspaceID, + Name: body.Name, + Hidden: true, + }) + if err != nil { + log.Error("e2e: failed to create hidden workflow", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusCreated, gin.H{ + "id": workflow.ID, + "workspace_id": workflow.WorkspaceID, + "name": workflow.Name, + "hidden": workflow.Hidden, + }) + } } diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index d3d2a84a00..7fb8470be6 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -648,7 +648,7 @@ func registerSecondaryRoutes( registerMCPAndDebugRoutes(p, workflowCtrl, clarificationStore, planService) - registerE2EResetRoutes(p.router, p.taskRepo, p.log) + registerE2EResetRoutes(p.router, p.taskRepo, p.taskSvc, p.log) } // registerHealthRoutes sets up the system health endpoint with all health checkers. diff --git a/apps/backend/config/workflows/loader.go b/apps/backend/config/workflows/loader.go index 5edc2e83c7..b64f715c6b 100644 --- a/apps/backend/config/workflows/loader.go +++ b/apps/backend/config/workflows/loader.go @@ -5,6 +5,7 @@ import ( "fmt" "io/fs" "strings" + "sync" "time" "github.com/kandev/kandev/internal/workflow/models" @@ -48,6 +49,37 @@ type actionYAML struct { Config map[string]any `yaml:"config,omitempty"` } +// HiddenTemplateIDs returns the set of template IDs marked `hidden: true` +// in their embedded YAML. Hidden templates are system-only flows +// (e.g. improve-kandev) that must not appear in management UI or pickers. +// +// The result is cached for the lifetime of the binary; the embedded YAML is +// static, and ListTemplates (the only caller) is on a hot path served on +// every picker / settings page load. +func HiddenTemplateIDs() (map[string]bool, error) { + hiddenOnce.Do(func() { + templates, err := LoadTemplates() + if err != nil { + hiddenErr = err + return + } + m := make(map[string]bool, len(templates)) + for _, t := range templates { + if t.Hidden { + m[t.ID] = true + } + } + hiddenIDs = m + }) + return hiddenIDs, hiddenErr +} + +var ( + hiddenOnce sync.Once + hiddenIDs map[string]bool + hiddenErr error +) + // LoadTemplates parses all embedded YAML files and returns workflow templates. func LoadTemplates() ([]*models.WorkflowTemplate, error) { entries, err := embeddedFS.ReadDir(".") diff --git a/apps/backend/internal/improvekandev/handler.go b/apps/backend/internal/improvekandev/handler.go index 00d390aabd..f8eb087eda 100644 --- a/apps/backend/internal/improvekandev/handler.go +++ b/apps/backend/internal/improvekandev/handler.go @@ -248,6 +248,17 @@ func (h *Handler) ensureWorkflow(ctx context.Context, workspaceID string) (*task } for _, w := range existing { if w.WorkflowTemplateID != nil && *w.WorkflowTemplateID == templateID { + // Heal records created before the workflow honored Hidden on insert. + // Best-effort: a DB failure here must not block the caller from getting + // their workflow ID, since the workflow itself is already usable. + if !w.Hidden { + if err := h.taskSvc.SetWorkflowHidden(ctx, w.ID, true); err != nil { + h.log.Warn("improve-kandev: failed to heal hidden flag on stale record", + zap.String("workflow_id", w.ID), zap.Error(err)) + } else { + w.Hidden = true + } + } return w, nil } } diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index 969d8d795a..0669fee689 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -221,6 +221,7 @@ func (s *Service) publishWorkflowEvent(ctx context.Context, eventType string, wo "name": workflow.Name, "description": workflow.Description, "agent_profile_id": workflow.AgentProfileID, + "hidden": workflow.Hidden, "created_at": workflow.CreatedAt.Format(time.RFC3339), "updated_at": workflow.UpdatedAt.Format(time.RFC3339), } diff --git a/apps/backend/internal/task/service/service_resources.go b/apps/backend/internal/task/service/service_resources.go index 70f745ccff..4a33a9507e 100644 --- a/apps/backend/internal/task/service/service_resources.go +++ b/apps/backend/internal/task/service/service_resources.go @@ -181,6 +181,27 @@ func (s *Service) UpdateWorkflow(ctx context.Context, id string, req *UpdateWork return workflow, nil } +// SetWorkflowHidden flips the hidden flag on a workflow. Used by system +// flows (e.g. improve-kandev) to heal records created before Hidden was +// honored on insert. +func (s *Service) SetWorkflowHidden(ctx context.Context, id string, hidden bool) error { + workflow, err := s.workflows.GetWorkflow(ctx, id) + if err != nil { + return err + } + if workflow.Hidden == hidden { + return nil + } + workflow.Hidden = hidden + workflow.UpdatedAt = time.Now().UTC() + if err := s.workflows.UpdateWorkflow(ctx, workflow); err != nil { + s.logger.Error("failed to update workflow hidden flag", zap.String("workflow_id", id), zap.Error(err)) + return err + } + s.publishWorkflowEvent(ctx, events.WorkflowUpdated, workflow) + return nil +} + // DeleteWorkflow deletes a workflow func (s *Service) DeleteWorkflow(ctx context.Context, id string) error { workflow, err := s.workflows.GetWorkflow(ctx, id) diff --git a/apps/backend/internal/task/service/service_workflow_test.go b/apps/backend/internal/task/service/service_workflow_test.go index 87b571bf81..ddbbc14d7f 100644 --- a/apps/backend/internal/task/service/service_workflow_test.go +++ b/apps/backend/internal/task/service/service_workflow_test.go @@ -38,6 +38,45 @@ func (testStepNotFound) Error() string { return "step not found" } var errStepNotFoundForTest = testStepNotFound{} +// TestService_SetWorkflowHidden_HealsStaleRecord verifies the helper used by +// the improve-kandev bootstrap to flip Hidden=true on workflows created +// before the flag was honored on insert. +func TestService_SetWorkflowHidden_HealsStaleRecord(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + + _ = repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}) + _ = repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-stale", WorkspaceID: "ws-1", Name: "Improve Kandev", Hidden: false}) + + if err := svc.SetWorkflowHidden(ctx, "wf-stale", true); err != nil { + t.Fatalf("SetWorkflowHidden: %v", err) + } + + visible, err := svc.ListWorkflows(ctx, "ws-1", false) + if err != nil { + t.Fatalf("ListWorkflows: %v", err) + } + for _, wf := range visible { + if wf.ID == "wf-stale" { + t.Fatalf("hidden workflow leaked into default listing: %+v", wf) + } + } + + all, err := svc.ListWorkflows(ctx, "ws-1", true) + if err != nil { + t.Fatalf("ListWorkflows(includeHidden): %v", err) + } + var found *models.Workflow + for _, wf := range all { + if wf.ID == "wf-stale" { + found = wf + } + } + if found == nil || !found.Hidden { + t.Fatalf("expected wf-stale to be hidden after heal, got %+v", found) + } +} + func TestService_MoveTaskRejectsInvalidWorkflowTargets(t *testing.T) { svc, _, repo := createTestService(t) ctx := context.Background() diff --git a/apps/backend/internal/workflow/service/service.go b/apps/backend/internal/workflow/service/service.go index d3efb19fa4..c0ff7109af 100644 --- a/apps/backend/internal/workflow/service/service.go +++ b/apps/backend/internal/workflow/service/service.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "go.uber.org/zap" + workflowcfg "github.com/kandev/kandev/config/workflows" "github.com/kandev/kandev/internal/common/logger" taskmodels "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/workflow/models" @@ -54,14 +55,28 @@ func NewService(repo *repository.Repository, log *logger.Logger) *Service { // Template Operations // ============================================================================ -// ListTemplates returns all workflow templates. +// ListTemplates returns user-pickable workflow templates. Templates marked +// `hidden: true` in their embedded YAML (e.g. improve-kandev) are excluded +// from the management UI and the create-workflow picker. func (s *Service) ListTemplates(ctx context.Context) ([]*models.WorkflowTemplate, error) { templates, err := s.repo.ListTemplates(ctx) if err != nil { s.logger.Error("failed to list templates", zap.Error(err)) return nil, err } - return templates, nil + hidden, err := workflowcfg.HiddenTemplateIDs() + if err != nil { + s.logger.Error("failed to load embedded template visibility", zap.Error(err)) + return nil, err + } + result := make([]*models.WorkflowTemplate, 0, len(templates)) + for _, t := range templates { + if hidden[t.ID] { + continue + } + result = append(result, t) + } + return result, nil } // GetTemplate retrieves a workflow template by ID. diff --git a/apps/backend/internal/workflow/service/service_test.go b/apps/backend/internal/workflow/service/service_test.go index b16566dd8d..e43063a603 100644 --- a/apps/backend/internal/workflow/service/service_test.go +++ b/apps/backend/internal/workflow/service/service_test.go @@ -113,6 +113,21 @@ func createStep(t *testing.T, svc *Service, step *models.WorkflowStep) { require.NoError(t, err) } +// TestListTemplates_FiltersHidden verifies that templates marked +// `hidden: true` in their embedded YAML (improve-kandev) are excluded +// from the picker shown by the create-workflow dialog and the settings UI. +func TestListTemplates_FiltersHidden(t *testing.T) { + svc, _ := setupTestService(t) + + templates, err := svc.ListTemplates(context.Background()) + require.NoError(t, err) + require.NotEmpty(t, templates, "ListTemplates returned no templates; the assertion below would vacuously pass") + + for _, tmpl := range templates { + assert.NotEqual(t, "improve-kandev", tmpl.ID, "hidden template must not be returned by ListTemplates") + } +} + func TestGetNextStepByPosition(t *testing.T) { t.Run("middle step returns next step", func(t *testing.T) { svc, db := setupTestService(t) diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index 6b7ebbf2ca..323de5f675 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -571,6 +571,21 @@ export class ApiClient { await this.request("DELETE", `/api/v1/e2e/reset/${workspaceId}${params}`); } + /** + * Creates a hidden (system-only) workflow. Mirrors the path that + * improve-kandev's bootstrap takes when ensuring its workflow exists, + * without depending on the gh CLI or repo cloning. + */ + async e2eCreateHiddenWorkflow( + workspaceId: string, + name: string, + ): Promise<{ id: string; workspace_id: string; name: string; hidden: boolean }> { + return this.request("POST", "/api/v1/e2e/hidden-workflow", { + workspace_id: workspaceId, + name, + }); + } + // --- GitHub Mock Control --- async mockGitHubReset(): Promise { diff --git a/apps/web/e2e/tests/workflow/workflow-settings.spec.ts b/apps/web/e2e/tests/workflow/workflow-settings.spec.ts index 587e78d37c..72688a825e 100644 --- a/apps/web/e2e/tests/workflow/workflow-settings.spec.ts +++ b/apps/web/e2e/tests/workflow/workflow-settings.spec.ts @@ -273,4 +273,50 @@ test.describe("Seed protection", () => { expect(postKanban).toHaveLength(kanbanSteps.length); expect(postPR).toHaveLength(prSteps.length); }); + + test("hidden system workflows do not appear in the settings list", async ({ + testPage, + seedData, + apiClient, + }) => { + // Reproduces the original "Improve Kandev" leak: while the user is on + // the workspace workflow settings page, a hidden system workflow gets + // created (e.g. via the Improve Kandev dialog). The backend fires a + // `workflow.created` WS event with hidden=true; the frontend receives + // it and previously surfaced the entry as a manageable card in the + // settings list. Verify the new hidden entry never appears as a card. + const hiddenName = "Improve Kandev"; + + const page = new WorkflowSettingsPage(testPage); + await page.goto(seedData.workspaceId); + + // The seeded visible workflow is rendered before the leak attempt. + const visibleCard = await page.findWorkflowCard("E2E Workflow"); + await expect(visibleCard).toBeVisible(); + const baselineCount = await testPage.locator('[data-testid^="workflow-card-"]').count(); + + // Trigger the leak path: a hidden workflow is created and the + // `workflow.created` WS event arrives at the open settings page. + await apiClient.e2eCreateHiddenWorkflow(seedData.workspaceId, hiddenName); + + // Allow the WS event to propagate and the React effect in + // useWorkflowSettings a chance to (incorrectly) add a card. + await testPage.waitForTimeout(500); + + // No new card appeared and the hidden entry is not in the list. + const allCards = testPage.locator('[data-testid^="workflow-card-"]'); + const newCount = await allCards.count(); + const cardNames: string[] = []; + for (let i = 0; i < newCount; i++) { + const value = await allCards + .nth(i) + .locator("input") + .first() + .inputValue({ timeout: 500 }) + .catch(() => ""); + cardNames.push(value); + } + expect(cardNames).not.toContain(hiddenName); + expect(newCount).toBe(baselineCount); + }); }); diff --git a/apps/web/hooks/domains/settings/use-workflow-settings.test.ts b/apps/web/hooks/domains/settings/use-workflow-settings.test.ts index d5e1b46958..de57a2d0a5 100644 --- a/apps/web/hooks/domains/settings/use-workflow-settings.test.ts +++ b/apps/web/hooks/domains/settings/use-workflow-settings.test.ts @@ -7,6 +7,7 @@ type StoreWorkflow = { workspaceId: string; name: string; description?: string | null; + hidden?: boolean; }; type MockState = { workflows: { items: StoreWorkflow[] } }; @@ -119,6 +120,46 @@ describe("useWorkflowSettings", () => { expect(result.current.workflowItems[0].name).toEqual("Renamed B1"); }); + it("excludes hidden system workflows from the settings list", () => { + // System workflows like "Improve Kandev" live in the global store with + // hidden=true so the kanban can resolve task references, but they must + // never appear in the management UI. + const HIDDEN_SYSTEM: StoreWorkflow = { + id: "wf-improve-kandev", + workspaceId: "ws-b", + name: "Improve Kandev", + hidden: true, + }; + setStore([STORE_B1, HIDDEN_SYSTEM]); + + const { result } = renderHook(() => useWorkflowSettings([], "ws-b")); + + expect(result.current.workflowItems.map((w) => w.id)).toEqual(["wf-b1"]); + expect(result.current.savedWorkflowItems.map((w) => w.id)).toEqual(["wf-b1"]); + }); + + it("drops a workflow from the settings list once it becomes hidden", () => { + const initial = [wf("wf-b1", "ws-b", NAME_B1)]; + setStore([STORE_B1]); + + const { result, rerender } = renderHook( + ({ store }: { store: StoreWorkflow[] }) => { + setStore(store); + return useWorkflowSettings(initial, "ws-b"); + }, + { initialProps: { store: [STORE_B1] } }, + ); + + expect(result.current.workflowItems.map((w) => w.id)).toEqual(["wf-b1"]); + + // Backend flips hidden=true (e.g. healing the improve-kandev record). + act(() => { + rerender({ store: [{ ...STORE_B1, hidden: true }] }); + }); + + expect(result.current.workflowItems.map((w) => w.id)).toEqual([]); + }); + it("starts scoping store entries once a workspaceId becomes defined", () => { setStore([STORE_A1, STORE_B1]); diff --git a/apps/web/hooks/domains/settings/use-workflow-settings.ts b/apps/web/hooks/domains/settings/use-workflow-settings.ts index 773b71d9f6..408748a565 100644 --- a/apps/web/hooks/domains/settings/use-workflow-settings.ts +++ b/apps/web/hooks/domains/settings/use-workflow-settings.ts @@ -14,11 +14,15 @@ import type { Workflow } from "@/lib/types/http"; */ export function useWorkflowSettings(initialWorkflows: Workflow[], workspaceId?: string) { const storeWorkflows = useAppStore((state) => state.workflows.items); - const scopedStoreWorkflows = useMemo( - () => - workspaceId ? storeWorkflows.filter((w) => w.workspaceId === workspaceId) : storeWorkflows, - [storeWorkflows, workspaceId], - ); + // Hidden workflows (e.g. the system "Improve Kandev" template) are loaded + // into the global store with `includeHidden: true` so the kanban can resolve + // them when a task references one, but they must never surface in the + // settings management UI. Filter them out at the store boundary so all + // downstream merging logic remains hidden-agnostic. + const scopedStoreWorkflows = useMemo(() => { + const visible = storeWorkflows.filter((w) => !w.hidden); + return workspaceId ? visible.filter((w) => w.workspaceId === workspaceId) : visible; + }, [storeWorkflows, workspaceId]); const [workflowItems, setWorkflowItems] = useState(initialWorkflows); const [savedWorkflowItems, setSavedWorkflowItems] = useState(initialWorkflows); diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index 558224b660..04d08fe71e 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -185,6 +185,7 @@ export type WorkflowPayload = { name: string; description?: string; agent_profile_id?: string; + hidden?: boolean; created_at?: string; updated_at?: string; }; diff --git a/apps/web/lib/ws/handlers/workflows.test.ts b/apps/web/lib/ws/handlers/workflows.test.ts new file mode 100644 index 0000000000..340d54d2ea --- /dev/null +++ b/apps/web/lib/ws/handlers/workflows.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect } from "vitest"; +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { BackendMessageMap, WorkflowPayload } from "@/lib/types/backend"; +import { registerWorkflowsHandlers } from "./workflows"; + +type WorkflowItem = { id: string; workspaceId: string; name: string; hidden?: boolean }; + +function makeStore(items: WorkflowItem[], activeId: string | null) { + let state = { + workflows: { items, activeId }, + workspaces: { activeId: "ws-1" }, + kanban: { workflowId: null, steps: [], tasks: [] }, + } as unknown as AppState; + + return { + getState: () => state, + setState: (updater: AppState | ((s: AppState) => AppState)) => { + state = + typeof updater === "function" ? (updater as (s: AppState) => AppState)(state) : updater; + }, + subscribe: () => () => {}, + destroy: () => {}, + getInitialState: () => state, + } as unknown as StoreApi; +} + +function updatedMessage(payload: WorkflowPayload): BackendMessageMap["workflow.updated"] { + return { + id: "msg-1", + type: "notification", + action: "workflow.updated", + payload, + timestamp: "2026-01-01T00:00:00Z", + }; +} + +describe("workflow.updated handler — hidden flag reconciles activeId", () => { + it("clears activeId to next visible workflow when active becomes hidden", () => { + const store = makeStore( + [ + { id: "wf-1", workspaceId: "ws-1", name: "Improve Kandev", hidden: false }, + { id: "wf-2", workspaceId: "ws-1", name: "Default", hidden: false }, + ], + "wf-1", + ); + const handlers = registerWorkflowsHandlers(store); + + handlers["workflow.updated"]?.( + updatedMessage({ id: "wf-1", workspace_id: "ws-1", name: "Improve Kandev", hidden: true }), + ); + + expect(store.getState().workflows.activeId).toBe("wf-2"); + expect(store.getState().workflows.items.find((i) => i.id === "wf-1")?.hidden).toBe(true); + }); + + it("clears activeId to null when no visible workflow remains", () => { + const store = makeStore( + [{ id: "wf-1", workspaceId: "ws-1", name: "Only One", hidden: false }], + "wf-1", + ); + const handlers = registerWorkflowsHandlers(store); + + handlers["workflow.updated"]?.( + updatedMessage({ id: "wf-1", workspace_id: "ws-1", name: "Only One", hidden: true }), + ); + + expect(store.getState().workflows.activeId).toBeNull(); + }); + + it("leaves activeId untouched when a non-active workflow becomes hidden", () => { + const store = makeStore( + [ + { id: "wf-1", workspaceId: "ws-1", name: "Active", hidden: false }, + { id: "wf-2", workspaceId: "ws-1", name: "Other", hidden: false }, + ], + "wf-1", + ); + const handlers = registerWorkflowsHandlers(store); + + handlers["workflow.updated"]?.( + updatedMessage({ id: "wf-2", workspace_id: "ws-1", name: "Other", hidden: true }), + ); + + expect(store.getState().workflows.activeId).toBe("wf-1"); + }); + + it("leaves activeId untouched when payload omits hidden", () => { + const store = makeStore( + [{ id: "wf-1", workspaceId: "ws-1", name: "Old Name", hidden: false }], + "wf-1", + ); + const handlers = registerWorkflowsHandlers(store); + + handlers["workflow.updated"]?.( + updatedMessage({ id: "wf-1", workspace_id: "ws-1", name: "New Name" }), + ); + + expect(store.getState().workflows.activeId).toBe("wf-1"); + expect(store.getState().workflows.items[0]?.name).toBe("New Name"); + }); +}); diff --git a/apps/web/lib/ws/handlers/workflows.ts b/apps/web/lib/ws/handlers/workflows.ts index 2b54840485..71c98c3c81 100644 --- a/apps/web/lib/ws/handlers/workflows.ts +++ b/apps/web/lib/ws/handlers/workflows.ts @@ -1,6 +1,7 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { WorkflowPayload } from "@/lib/types/backend"; // eslint-disable-next-line @typescript-eslint/no-explicit-any function stepFromPayload(step: any) { @@ -18,49 +19,65 @@ function stepFromPayload(step: any) { }; } +function applyWorkflowCreated(state: AppState, payload: WorkflowPayload): AppState { + if (state.workspaces.activeId !== payload.workspace_id) return state; + if (state.workflows.items.some((item) => item.id === payload.id)) return state; + const isHidden = Boolean(payload.hidden); + return { + ...state, + workflows: { + items: [ + { + id: payload.id, + workspaceId: payload.workspace_id, + name: payload.name, + hidden: isHidden, + }, + ...state.workflows.items, + ], + // Hidden workflows must never be promoted to the active selection; + // they are system-only and would surface in the workflow picker. + activeId: state.workflows.activeId ?? (isHidden ? null : payload.id), + }, + }; +} + +function applyWorkflowUpdated(state: AppState, payload: WorkflowPayload): AppState { + const items = state.workflows.items.map((item) => + item.id === payload.id + ? { + ...item, + name: payload.name, + agent_profile_id: payload.agent_profile_id, + hidden: payload.hidden !== undefined ? Boolean(payload.hidden) : item.hidden, + } + : item, + ); + // If the active workflow just became hidden, fall back to the next visible + // entry so the kanban / picker isn't left bound to a workflow the user can + // no longer reach (the backend fires `workflow.updated`, not `workflow.deleted`, + // when `SetWorkflowHidden` flips the flag). + const activeBecameHidden = state.workflows.activeId === payload.id && payload.hidden === true; + const nextActiveId = activeBecameHidden + ? (items.find((item) => !item.hidden)?.id ?? null) + : state.workflows.activeId; + return { + ...state, + workflows: { + ...state.workflows, + activeId: nextActiveId, + items, + }, + }; +} + export function registerWorkflowsHandlers(store: StoreApi): WsHandlers { return { "workflow.created": (message) => { - store.setState((state) => { - if (state.workspaces.activeId !== message.payload.workspace_id) { - return state; - } - const exists = state.workflows.items.some((item) => item.id === message.payload.id); - if (exists) { - return state; - } - return { - ...state, - workflows: { - items: [ - { - id: message.payload.id, - workspaceId: message.payload.workspace_id, - name: message.payload.name, - }, - ...state.workflows.items, - ], - activeId: state.workflows.activeId ?? message.payload.id, - }, - }; - }); + store.setState((state) => applyWorkflowCreated(state, message.payload)); }, "workflow.updated": (message) => { - store.setState((state) => ({ - ...state, - workflows: { - ...state.workflows, - items: state.workflows.items.map((item) => - item.id === message.payload.id - ? { - ...item, - name: message.payload.name, - agent_profile_id: message.payload.agent_profile_id, - } - : item, - ), - }, - })); + store.setState((state) => applyWorkflowUpdated(state, message.payload)); }, "workflow.deleted": (message) => { store.setState((state) => {