fix(workflows): hide improve-kandev system workflow from settings UI (#842)
This commit is contained in:
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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(".")
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<void> {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -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<Workflow[]>(initialWorkflows);
|
||||
const [savedWorkflowItems, setSavedWorkflowItems] = useState<Workflow[]>(initialWorkflows);
|
||||
|
||||
|
||||
@@ -185,6 +185,7 @@ export type WorkflowPayload = {
|
||||
name: string;
|
||||
description?: string;
|
||||
agent_profile_id?: string;
|
||||
hidden?: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
|
||||
@@ -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<AppState>;
|
||||
}
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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<AppState>): 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) => {
|
||||
|
||||
Reference in New Issue
Block a user