From 21202ef4375a88314be262bf00f08193e27d1e30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= <57680069+zeval@users.noreply.github.com> Date: Sun, 10 May 2026 17:02:40 +0100 Subject: [PATCH 01/19] fix(web): mobile task switcher sheet skeleton while snapshot loads (#860) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(web): show skeleton in mobile task switcher sheet while snapshot loads When the user opens the mobile task switcher inside a task page before the workflow snapshot has hydrated kanban, the sheet rendered "No tasks yet." instead of a loading state — and stayed that way if the fetch silently failed. useWorkflowSnapshot now drives kanban.isLoading, useTasks exposes it as { tasks, isLoading }, and the sheet wires that into TaskSwitcher's existing skeleton. Fetch errors are surfaced via console.warn so an indefinite empty list isn't silent anymore. * fix(web): guard snapshot finally on cancel and drop redundant subscription Skip the workflow-snapshot fetch's finally block when the effect was superseded by a newer workflowId — otherwise the old fetch's settle would clear the loading flag the new effect just set, briefly flashing the empty-state UI mid-switch. Also drop the redundant kanbanIsLoading subscription in useSheetData (useTasks already encapsulates it) and make the setState mock in use-tasks.test.ts actually mutate state so useWorkflowSnapshot's side effects are exercised by the test. * fix(web): scope snapshot finally clear to the effect that raised the flag If kanban already matched the requested workflowId, the effect skipped raising isLoading=true — but its finally still cleared it on settle, collapsing a skeleton a concurrent caller (e.g. workspace switch) had set independently. Track whether this effect raised the flag and only clear in that case. Also collapse the multi-line useTasks comment per CLAUDE.md style. * fix(web): suppress superseded snapshot fetch warnings Skip the catch-handler console.warn when the effect has been cancelled — a stale fetch shouldn't surface noise after a newer workflow has taken over. * test(web): flush microtasks explicitly in race test waitFor on a never-true assertion resolves immediately, hiding the intent. Use explicit Promise.resolve() flushes to land the superseded fetch's .then/.finally chain before asserting. * style(web): collapse multi-line comments per CLAUDE.md --- .../session-task-switcher-sheet-hooks.ts | 6 +- .../mobile/session-task-switcher-sheet.tsx | 2 +- apps/web/hooks/use-tasks.test.ts | 121 +++++++++++++++ apps/web/hooks/use-tasks.ts | 14 +- apps/web/hooks/use-workflow-snapshot.test.ts | 139 ++++++++++++++++++ apps/web/hooks/use-workflow-snapshot.ts | 20 ++- 6 files changed, 289 insertions(+), 13 deletions(-) create mode 100644 apps/web/hooks/use-tasks.test.ts create mode 100644 apps/web/hooks/use-workflow-snapshot.test.ts 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 04611835b1..325c23b7de 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 @@ -87,11 +87,10 @@ export function useSheetData(workspaceId: string | null, workflowId: string | nu const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId); const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId); const messagesBySession = useAppStore((state) => state.messages.bySession); - const { tasks } = useTasks(workflowId); + const { tasks, isLoading: tasksLoading } = useTasks(workflowId); const steps = useAppStore((state) => state.kanban.steps); const workspaces = useAppStore((state) => state.workspaces.items); const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); - const kanbanIsLoading = useAppStore((state) => state.kanban.isLoading ?? false); const selectedTaskId = useMemo(() => { if (activeSessionId) return sessionsById[activeSessionId]?.task_id ?? activeTaskId; @@ -157,7 +156,8 @@ export function useSheetData(workspaceId: string | null, workflowId: string | nu selectedTaskId, steps, workspaces, - kanbanIsLoading, + // Skeleton while snapshot hydrates kanban — otherwise shows "No tasks yet." even when tasks exist. + tasksLoading, tasksWithRepositories, dialogSteps, }; diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx index 509ced78ce..08e11ecad4 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx +++ b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx @@ -114,7 +114,7 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({ onArchiveTask={actions.handleArchiveTask} onDeleteTask={actions.handleDeleteTask} deletingTaskId={actions.deletingTaskId} - isLoading={data.kanbanIsLoading} + isLoading={data.tasksLoading} /> diff --git a/apps/web/hooks/use-tasks.test.ts b/apps/web/hooks/use-tasks.test.ts new file mode 100644 index 0000000000..24987e05fe --- /dev/null +++ b/apps/web/hooks/use-tasks.test.ts @@ -0,0 +1,121 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderHook } from "@testing-library/react"; + +const mockHydrate = vi.fn(); +const mockSetState = vi.fn(); +const mockFetchWorkflowSnapshot = vi.fn(); + +type Task = { id: string; title: string }; +type MockState = { + connection: { status: string }; + kanban: { workflowId: string | null; tasks: Task[]; steps: unknown[]; isLoading?: boolean }; + hydrate: typeof mockHydrate; +}; + +let mockState: MockState = { + connection: { status: "connected" }, + kanban: { workflowId: null, tasks: [], steps: [] }, + hydrate: mockHydrate, +}; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (s: MockState) => unknown) => selector(mockState), + useAppStoreApi: () => ({ + getState: () => mockState, + setState: (updater: (s: MockState) => MockState) => { + // Apply the updater so useWorkflowSnapshot's isLoading transitions are + // visible to subsequent reads in the same render cycle. Without this + // the mock would silently swallow side effects. + mockState = updater(mockState); + mockSetState(mockState); + }, + }), +})); + +vi.mock("@/lib/api", () => ({ + fetchWorkflowSnapshot: (...args: unknown[]) => mockFetchWorkflowSnapshot(...args), +})); + +vi.mock("@/lib/ssr/mapper", () => ({ + snapshotToState: (snapshot: unknown) => ({ snapshot }), +})); + +import { useTasks } from "./use-tasks"; + +function setMockState(patch: Partial & { workflowId?: string | null }) { + mockState = { + ...mockState, + kanban: { ...mockState.kanban, ...patch }, + }; +} + +describe("useTasks — loading and matching", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Never resolves so we observe pre-resolution loading state. + mockFetchWorkflowSnapshot.mockReturnValue(new Promise(() => {})); + mockState = { + connection: { status: "connected" }, + kanban: { workflowId: null, tasks: [], steps: [], isLoading: false }, + hydrate: mockHydrate, + }; + }); + + it("returns empty list and not-loading when workflowId is null", () => { + const { result } = renderHook(() => useTasks(null)); + expect(result.current.tasks).toEqual([]); + expect(result.current.isLoading).toBe(false); + }); + + it("reports loading once useWorkflowSnapshot has flipped kanban.isLoading", () => { + setMockState({ workflowId: null, isLoading: true }); + const { result } = renderHook(() => useTasks("wf-1")); + expect(result.current.tasks).toEqual([]); + expect(result.current.isLoading).toBe(true); + }); + + it("does not report loading when fetch has settled but workflowId mismatches", () => { + // Simulates a failed snapshot fetch — `kanban.isLoading` is back to false + // and `kanban.workflowId` never advanced to the requested id. Caller + // shows the empty-state UI rather than an infinite skeleton. + setMockState({ workflowId: null, isLoading: false }); + const { result } = renderHook(() => useTasks("wf-1")); + expect(result.current.tasks).toEqual([]); + expect(result.current.isLoading).toBe(false); + }); + + it("returns tasks and not-loading once kanban.workflowId matches", () => { + setMockState({ + workflowId: "wf-1", + tasks: [ + { id: "t1", title: "One" }, + { id: "t2", title: "Two" }, + ], + isLoading: false, + }); + const { result } = renderHook(() => useTasks("wf-1")); + expect(result.current.tasks).toHaveLength(2); + expect(result.current.isLoading).toBe(false); + }); + + it("filters out tasks that belong to a different workflow snapshot", () => { + setMockState({ + workflowId: "wf-other", + tasks: [{ id: "t1", title: "One" }], + isLoading: false, + }); + const { result } = renderHook(() => useTasks("wf-1")); + expect(result.current.tasks).toEqual([]); + expect(result.current.isLoading).toBe(false); + }); + + it("respects kanban.isLoading even when workflowId already matches", () => { + setMockState({ + workflowId: "wf-1", + tasks: [{ id: "t1", title: "One" }], + isLoading: true, + }); + const { result } = renderHook(() => useTasks("wf-1")); + expect(result.current.isLoading).toBe(true); + }); +}); diff --git a/apps/web/hooks/use-tasks.ts b/apps/web/hooks/use-tasks.ts index a5e2e898f5..6823ed26f7 100644 --- a/apps/web/hooks/use-tasks.ts +++ b/apps/web/hooks/use-tasks.ts @@ -6,14 +6,14 @@ export function useTasks(workflowId: string | null) { useWorkflowSnapshot(workflowId); const kanbanWorkflowId = useAppStore((state) => state.kanban.workflowId); + const kanbanIsLoading = useAppStore((state) => state.kanban.isLoading ?? false); const tasks = useAppStore((state) => state.kanban.tasks); - const workflowTasks = useMemo(() => { - if (!workflowId || kanbanWorkflowId !== workflowId) { - return []; - } - return tasks; - }, [workflowId, kanbanWorkflowId, tasks]); + const matchesActive = !!workflowId && kanbanWorkflowId === workflowId; + const workflowTasks = useMemo(() => (matchesActive ? tasks : []), [matchesActive, tasks]); - return { tasks: workflowTasks }; + // Loading only while a snapshot fetch is in-flight; settles to false on success/error to avoid an infinite skeleton. + const isLoading = !!workflowId && kanbanIsLoading; + + return { tasks: workflowTasks, isLoading }; } diff --git a/apps/web/hooks/use-workflow-snapshot.test.ts b/apps/web/hooks/use-workflow-snapshot.test.ts new file mode 100644 index 0000000000..014b6bc4d1 --- /dev/null +++ b/apps/web/hooks/use-workflow-snapshot.test.ts @@ -0,0 +1,139 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderHook, waitFor } from "@testing-library/react"; + +const mockHydrate = vi.fn(); +const mockFetchWorkflowSnapshot = vi.fn(); +const mockSetState = vi.fn(); + +type MockKanban = { + workflowId: string | null; + tasks: unknown[]; + steps: unknown[]; + isLoading?: boolean; +}; +type MockState = { + connection: { status: string }; + kanban: MockKanban; + hydrate: typeof mockHydrate; +}; + +let mockState: MockState = { + connection: { status: "connected" }, + kanban: { workflowId: null, tasks: [], steps: [], isLoading: false }, + hydrate: mockHydrate, +}; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (s: MockState) => unknown) => selector(mockState), + useAppStoreApi: () => ({ + getState: () => mockState, + setState: (updater: (s: MockState) => MockState) => { + const next = updater(mockState); + mockSetState(next); + mockState = next; + }, + }), +})); + +vi.mock("@/lib/api", () => ({ + fetchWorkflowSnapshot: (...args: unknown[]) => mockFetchWorkflowSnapshot(...args), +})); + +vi.mock("@/lib/ssr/mapper", () => ({ + snapshotToState: (snapshot: unknown) => ({ snapshot }), +})); + +import { useWorkflowSnapshot } from "./use-workflow-snapshot"; + +function resetState(kanban: Partial = {}) { + vi.clearAllMocks(); + mockState = { + connection: { status: "connected" }, + kanban: { + workflowId: null, + tasks: [], + steps: [], + isLoading: false, + ...kanban, + }, + hydrate: mockHydrate, + }; +} + +describe("useWorkflowSnapshot — kanban.isLoading", () => { + beforeEach(() => resetState()); + + it("flips isLoading true while a fetch for an un-hydrated workflow is in flight", () => { + mockFetchWorkflowSnapshot.mockReturnValue(new Promise(() => {})); + renderHook(() => useWorkflowSnapshot("wf-1")); + expect(mockState.kanban.isLoading).toBe(true); + }); + + it("flips isLoading back to false after the fetch resolves", async () => { + mockFetchWorkflowSnapshot.mockResolvedValue({ steps: [], tasks: [] }); + renderHook(() => useWorkflowSnapshot("wf-1")); + await waitFor(() => expect(mockHydrate).toHaveBeenCalled()); + await waitFor(() => expect(mockState.kanban.isLoading).toBe(false)); + }); + + it("flips isLoading back to false after the fetch rejects", async () => { + mockFetchWorkflowSnapshot.mockRejectedValue(new Error("nope")); + renderHook(() => useWorkflowSnapshot("wf-1")); + await waitFor(() => expect(mockState.kanban.isLoading).toBe(false)); + expect(mockHydrate).not.toHaveBeenCalled(); + }); + + it("does not flip isLoading true if the requested workflow is already hydrated", () => { + resetState({ workflowId: "wf-1", isLoading: false }); + mockFetchWorkflowSnapshot.mockReturnValue(new Promise(() => {})); + renderHook(() => useWorkflowSnapshot("wf-1")); + expect(mockState.kanban.isLoading).toBe(false); + }); + + it("does not clear isLoading on settle when it didn't raise the flag (already-hydrated re-fetch)", async () => { + // Mimic a workspace switch having set isLoading=true after the snapshot + // hydrated for this workflowId. A silent re-fetch (e.g. WS reconnect) + // must not collapse that skeleton. + resetState({ workflowId: "wf-1", isLoading: true }); + mockFetchWorkflowSnapshot.mockResolvedValue({ steps: [], tasks: [] }); + renderHook(() => useWorkflowSnapshot("wf-1")); + await waitFor(() => expect(mockHydrate).toHaveBeenCalled()); + expect(mockState.kanban.isLoading).toBe(true); + }); + + it("does nothing when workflowId is null", () => { + renderHook(() => useWorkflowSnapshot(null)); + expect(mockFetchWorkflowSnapshot).not.toHaveBeenCalled(); + expect(mockState.kanban.isLoading).toBe(false); + }); + + it("does not clear isLoading when an old fetch settles after workflowId changes", async () => { + // First fetch never settles synchronously — we resolve it manually + // *after* re-rendering with a new workflowId, simulating the race where + // the user switches workflows mid-fetch. + let resolveFirst!: (snapshot: { steps: unknown[]; tasks: unknown[] }) => void; + const firstFetch = new Promise<{ steps: unknown[]; tasks: unknown[] }>((r) => { + resolveFirst = r; + }); + const secondFetch = new Promise<{ steps: unknown[]; tasks: unknown[] }>(() => {}); + mockFetchWorkflowSnapshot.mockReturnValueOnce(firstFetch).mockReturnValueOnce(secondFetch); + + const { rerender } = renderHook(({ id }: { id: string | null }) => useWorkflowSnapshot(id), { + initialProps: { id: "wf-1" as string | null }, + }); + expect(mockState.kanban.isLoading).toBe(true); + + // User switches to wf-2 before wf-1 finishes loading + rerender({ id: "wf-2" }); + expect(mockState.kanban.isLoading).toBe(true); + + // Old fetch lands now; flush its .then/.finally microtask chain so we + // can assert the negatives without relying on waitFor (which would + // resolve immediately for never-true assertions). + resolveFirst({ steps: [], tasks: [] }); + await Promise.resolve(); + await Promise.resolve(); + expect(mockHydrate).not.toHaveBeenCalled(); + expect(mockState.kanban.isLoading).toBe(true); + }); +}); diff --git a/apps/web/hooks/use-workflow-snapshot.ts b/apps/web/hooks/use-workflow-snapshot.ts index 511ac55d8e..d18fb9935d 100644 --- a/apps/web/hooks/use-workflow-snapshot.ts +++ b/apps/web/hooks/use-workflow-snapshot.ts @@ -9,12 +9,28 @@ export function useWorkflowSnapshot(workflowId: string | null) { useEffect(() => { if (!workflowId) return; + let cancelled = false; + const setLoading = store.getState().kanban.workflowId !== workflowId; + if (setLoading) { + store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: true } })); + } fetchWorkflowSnapshot(workflowId, { cache: "no-store" }) .then((snapshot) => { + if (cancelled) return; store.getState().hydrate(snapshotToState(snapshot)); }) - .catch(() => { - // Ignore snapshot errors — will retry on WS reconnect. + .catch((error) => { + // Suppress superseded-fetch noise; retry happens on WS reconnect. + if (cancelled) return; + console.warn("[useWorkflowSnapshot] failed to load snapshot:", error); + }) + .finally(() => { + // Only clear the flag this effect raised; skip when cancelled or when a concurrent caller owns it. + if (cancelled || !setLoading) return; + store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } })); }); + return () => { + cancelled = true; + }; }, [workflowId, store, connectionStatus]); } From 5223a1cd17d7d04305bff513fb3d8c9b1563fc6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= <57680069+zeval@users.noreply.github.com> Date: Sun, 10 May 2026 17:04:56 +0100 Subject: [PATCH 02/19] fix(prompts): warn on duplicate custom prompt name instead of 500 (#859) * fix(backend): return 409 on duplicate prompt name Pre-check by name in CreatePrompt and rename paths and surface ErrPromptAlreadyExists as 409 with the underlying error message. Previously the SQLite UNIQUE constraint bubbled up as a 500 with a generic body, so the frontend had nothing actionable to show. * feat(web): toast on prompt save errors with e2e coverage Wire useToast in the Prompts settings page so create/update/delete failures surface a warning instead of being swallowed silently. Add data-testid hooks plus Playwright specs covering duplicate-name create, rename-to-existing, and the happy path. * fix(backend): close TOCTOU + tighten prompt error handling Address PR review: - log client errors (4xx) at Info, reserve Error for unexpected 500s - switch handler error mapping to errors.Is so wrapped sentinels still resolve to the right HTTP status - drop the unreachable existing==nil branch in assertNameAvailable - translate SQLite UNIQUE constraint errors that slip through the pre-check race into ErrPromptAlreadyExists so concurrent dup-name inserts return 409 instead of 500 --- .../internal/prompts/handlers/handlers.go | 42 +++++-- .../prompts/handlers/handlers_test.go | 114 ++++++++++++++++++ .../internal/prompts/service/service.go | 47 +++++++- .../internal/prompts/service/service_test.go | 104 ++++++++++++++++ .../components/settings/prompts-settings.tsx | 36 ++++-- apps/web/e2e/helpers/api-client.ts | 17 +++ .../tests/settings/prompts-settings.spec.ts | 92 ++++++++++++++ 7 files changed, 428 insertions(+), 24 deletions(-) create mode 100644 apps/backend/internal/prompts/handlers/handlers_test.go create mode 100644 apps/web/e2e/tests/settings/prompts-settings.spec.ts diff --git a/apps/backend/internal/prompts/handlers/handlers.go b/apps/backend/internal/prompts/handlers/handlers.go index f1b8448751..111d14aa9a 100644 --- a/apps/backend/internal/prompts/handlers/handlers.go +++ b/apps/backend/internal/prompts/handlers/handlers.go @@ -1,6 +1,7 @@ package handlers import ( + "errors" "net/http" "github.com/gin-gonic/gin" @@ -51,12 +52,15 @@ func (h *Handlers) httpCreatePrompt(c *gin.Context) { } resp, err := h.controller.CreatePrompt(c.Request.Context(), req) if err != nil { - status := http.StatusInternalServerError - if err == service.ErrInvalidPrompt { - status = http.StatusBadRequest + status, message := http.StatusInternalServerError, "failed to create prompt" + switch { + case errors.Is(err, service.ErrInvalidPrompt): + status, message = http.StatusBadRequest, err.Error() + case errors.Is(err, service.ErrPromptAlreadyExists): + status, message = http.StatusConflict, err.Error() } - h.logger.Error("failed to create prompt", zap.Error(err)) - c.JSON(status, gin.H{"error": "failed to create prompt"}) + logRejection(h.logger, "create prompt rejected", "failed to create prompt", err, status) + c.JSON(status, gin.H{"error": message}) return } c.JSON(http.StatusOK, resp) @@ -70,20 +74,32 @@ func (h *Handlers) httpUpdatePrompt(c *gin.Context) { } resp, err := h.controller.UpdatePrompt(c.Request.Context(), c.Param("id"), req) if err != nil { - status := http.StatusInternalServerError - switch err { - case service.ErrInvalidPrompt: - status = http.StatusBadRequest - case service.ErrPromptNotFound: - status = http.StatusNotFound + status, message := http.StatusInternalServerError, "failed to update prompt" + switch { + case errors.Is(err, service.ErrInvalidPrompt): + status, message = http.StatusBadRequest, err.Error() + case errors.Is(err, service.ErrPromptNotFound): + status, message = http.StatusNotFound, err.Error() + case errors.Is(err, service.ErrPromptAlreadyExists): + status, message = http.StatusConflict, err.Error() } - h.logger.Error("failed to update prompt", zap.Error(err)) - c.JSON(status, gin.H{"error": "failed to update prompt"}) + logRejection(h.logger, "update prompt rejected", "failed to update prompt", err, status) + c.JSON(status, gin.H{"error": message}) return } c.JSON(http.StatusOK, resp) } +// logRejection keeps the error-rate dashboard clean by logging client-driven +// 4xx outcomes at Info level and reserving Error for unexpected 500s. +func logRejection(log *logger.Logger, infoMsg, errorMsg string, err error, status int) { + if status >= http.StatusInternalServerError { + log.Error(errorMsg, zap.Error(err)) + return + } + log.Info(infoMsg, zap.Error(err), zap.Int("status", status)) +} + func (h *Handlers) httpDeletePrompt(c *gin.Context) { if err := h.controller.DeletePrompt(c.Request.Context(), c.Param("id")); err != nil { h.logger.Error("failed to delete prompt", zap.Error(err)) diff --git a/apps/backend/internal/prompts/handlers/handlers_test.go b/apps/backend/internal/prompts/handlers/handlers_test.go new file mode 100644 index 0000000000..eb4f04347a --- /dev/null +++ b/apps/backend/internal/prompts/handlers/handlers_test.go @@ -0,0 +1,114 @@ +package handlers + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/prompts/controller" + "github.com/kandev/kandev/internal/prompts/service" + promptstore "github.com/kandev/kandev/internal/prompts/store" +) + +func newTestRouter(t *testing.T) (*gin.Engine, func()) { + t.Helper() + gin.SetMode(gin.TestMode) + + tmpDir := t.TempDir() + dbConn, err := db.OpenSQLite(filepath.Join(tmpDir, "test.db")) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + sqlxDB := sqlx.NewDb(dbConn, "sqlite3") + repo, repoCleanup, err := promptstore.Provide(sqlxDB, sqlxDB) + if err != nil { + t.Fatalf("provide repo: %v", err) + } + svc := service.NewService(repo) + ctrl := controller.NewController(svc) + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + + router := gin.New() + RegisterRoutes(router, ctrl, log) + + cleanup := func() { + if err := sqlxDB.Close(); err != nil { + t.Errorf("close sqlite: %v", err) + } + if err := repoCleanup(); err != nil { + t.Errorf("close repo: %v", err) + } + } + return router, cleanup +} + +func postJSON(t *testing.T, router *gin.Engine, path string, body any) *httptest.ResponseRecorder { + t.Helper() + buf, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(buf)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + return rec +} + +// Duplicate prompt name on POST /api/v1/prompts must surface as 409 with a +// human-readable error message — not a generic 500 — so the frontend can show +// a useful warning rather than crashing the user out of the create form. +func TestHTTPCreatePrompt_DuplicateName_Returns409(t *testing.T) { + router, cleanup := newTestRouter(t) + defer cleanup() + + first := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "dupe", "content": "first", + }) + if first.Code != http.StatusOK { + t.Fatalf("seed prompt: status %d body %s", first.Code, first.Body.String()) + } + + second := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "dupe", "content": "second", + }) + if second.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d body %s", second.Code, second.Body.String()) + } + + var resp struct { + Error string `json:"error"` + } + if err := json.Unmarshal(second.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal response: %v", err) + } + if resp.Error == "" { + t.Fatal("expected non-empty error message") + } + if !bytes.Contains([]byte(resp.Error), []byte("already exists")) { + t.Fatalf("expected 'already exists' in message, got %q", resp.Error) + } +} + +// Built-in prompts (seeded with names like "code-review") share the unique +// name space with user-created prompts, so creating a custom prompt that +// collides with a built-in must also return 409, not 500. +func TestHTTPCreatePrompt_BuiltinName_Returns409(t *testing.T) { + router, cleanup := newTestRouter(t) + defer cleanup() + + rec := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "code-review", "content": "shadow", + }) + if rec.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d body %s", rec.Code, rec.Body.String()) + } +} diff --git a/apps/backend/internal/prompts/service/service.go b/apps/backend/internal/prompts/service/service.go index f2047f4a75..aaa275e338 100644 --- a/apps/backend/internal/prompts/service/service.go +++ b/apps/backend/internal/prompts/service/service.go @@ -2,6 +2,7 @@ package service import ( "context" + "database/sql" "errors" "strings" @@ -10,8 +11,9 @@ import ( ) var ( - ErrPromptNotFound = errors.New("prompt not found") - ErrInvalidPrompt = errors.New("invalid prompt") + ErrPromptNotFound = errors.New("prompt not found") + ErrInvalidPrompt = errors.New("invalid prompt") + ErrPromptAlreadyExists = errors.New("prompt with this name already exists") ) type Service struct { @@ -32,16 +34,48 @@ func (s *Service) CreatePrompt(ctx context.Context, name, content string) (*mode if name == "" || content == "" { return nil, ErrInvalidPrompt } + if err := s.assertNameAvailable(ctx, name, ""); err != nil { + return nil, err + } prompt := &models.Prompt{ Name: name, Content: content, } if err := s.repo.CreatePrompt(ctx, prompt); err != nil { - return nil, err + return nil, translateNameConflict(err) } return prompt, nil } +// translateNameConflict closes the TOCTOU window between assertNameAvailable +// and the write: the SQLite UNIQUE index on custom_prompts.name is the only +// authoritative guard, and a concurrent write that loses the race surfaces a +// "UNIQUE constraint failed" driver error which would otherwise fall through +// to a generic 500. +func translateNameConflict(err error) error { + if err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") { + return ErrPromptAlreadyExists + } + return err +} + +// assertNameAvailable returns ErrPromptAlreadyExists if a different prompt with +// the given name already exists. excludeID lets callers exclude the prompt +// being updated so unchanged-name saves do not falsely trip. +func (s *Service) assertNameAvailable(ctx context.Context, name, excludeID string) error { + existing, err := s.repo.GetPromptByName(ctx, name) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return err + } + if existing.ID == excludeID { + return nil + } + return ErrPromptAlreadyExists +} + func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *string, content *string) (*models.Prompt, error) { prompt, err := s.repo.GetPromptByID(ctx, promptID) if err != nil { @@ -52,6 +86,11 @@ func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *strin if trimmed == "" { return nil, ErrInvalidPrompt } + if trimmed != prompt.Name { + if err := s.assertNameAvailable(ctx, trimmed, prompt.ID); err != nil { + return nil, err + } + } prompt.Name = trimmed } if content != nil { @@ -62,7 +101,7 @@ func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *strin prompt.Content = trimmed } if err := s.repo.UpdatePrompt(ctx, prompt); err != nil { - return nil, err + return nil, translateNameConflict(err) } return prompt, nil } diff --git a/apps/backend/internal/prompts/service/service_test.go b/apps/backend/internal/prompts/service/service_test.go index b7a22dc197..5b60ca372e 100644 --- a/apps/backend/internal/prompts/service/service_test.go +++ b/apps/backend/internal/prompts/service/service_test.go @@ -2,11 +2,14 @@ package service import ( "context" + "database/sql" + "errors" "path/filepath" "testing" "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/prompts/models" promptstore "github.com/kandev/kandev/internal/prompts/store" ) @@ -69,3 +72,104 @@ func TestService_UpdatePrompt(t *testing.T) { t.Fatalf("expected content %q, got %q", content, updated.Content) } } + +func TestService_CreatePromptDuplicateName(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + if _, err := svc.CreatePrompt(ctx, "shared-name", "first"); err != nil { + t.Fatalf("seed prompt: %v", err) + } + if _, err := svc.CreatePrompt(ctx, "shared-name", "second"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } + // Trimmed input still detected. + if _, err := svc.CreatePrompt(ctx, " shared-name ", "third"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists for trimmed name, got %v", err) + } +} + +func TestService_UpdatePromptRenameToExisting(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + if _, err := svc.CreatePrompt(ctx, "alpha", "a"); err != nil { + t.Fatalf("seed alpha: %v", err) + } + beta, err := svc.CreatePrompt(ctx, "beta", "b") + if err != nil { + t.Fatalf("seed beta: %v", err) + } + + rename := "alpha" + if _, err := svc.UpdatePrompt(ctx, beta.ID, &rename, nil); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} + +// Saving a prompt without changing its name (e.g. content-only edit, or sending +// the same name through the PATCH) must not trip the duplicate-name guard. +func TestService_UpdatePromptSameName(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + prompt, err := svc.CreatePrompt(ctx, "stable", "v1") + if err != nil { + t.Fatalf("seed prompt: %v", err) + } + + sameName := "stable" + newContent := "v2" + updated, err := svc.UpdatePrompt(ctx, prompt.ID, &sameName, &newContent) + if err != nil { + t.Fatalf("update with same name: %v", err) + } + if updated.Content != newContent { + t.Fatalf("expected content %q, got %q", newContent, updated.Content) + } +} + +// raceRepo simulates a TOCTOU loss against the SQLite UNIQUE index: the +// pre-check sees no row, but the write fails because a concurrent insert +// landed first. The service must translate that into ErrPromptAlreadyExists +// rather than letting the raw driver error fall through to a 500. +type raceRepo struct { + promptstore.Repository + createErr error + updateErr error +} + +func (r *raceRepo) GetPromptByID(_ context.Context, id string) (*models.Prompt, error) { + return &models.Prompt{ID: id, Name: "old", Content: "x"}, nil +} + +func (r *raceRepo) GetPromptByName(_ context.Context, _ string) (*models.Prompt, error) { + return nil, sql.ErrNoRows +} + +func (r *raceRepo) CreatePrompt(_ context.Context, _ *models.Prompt) error { return r.createErr } +func (r *raceRepo) UpdatePrompt(_ context.Context, _ *models.Prompt) error { return r.updateErr } + +func TestService_CreatePrompt_TranslatesUniqueConstraintRace(t *testing.T) { + svc := NewService(&raceRepo{ + createErr: errors.New("UNIQUE constraint failed: custom_prompts.name"), + }) + + if _, err := svc.CreatePrompt(context.Background(), "any", "content"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} + +func TestService_UpdatePrompt_TranslatesUniqueConstraintRace(t *testing.T) { + svc := NewService(&raceRepo{ + updateErr: errors.New("UNIQUE constraint failed: custom_prompts.name"), + }) + + rename := "new-name" + if _, err := svc.UpdatePrompt(context.Background(), "id-1", &rename, nil); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} diff --git a/apps/web/components/settings/prompts-settings.tsx b/apps/web/components/settings/prompts-settings.tsx index a5b7cd3d19..a2dc0d1f46 100644 --- a/apps/web/components/settings/prompts-settings.tsx +++ b/apps/web/components/settings/prompts-settings.tsx @@ -15,6 +15,7 @@ import { import { Input } from "@kandev/ui/input"; import { Textarea } from "@kandev/ui/textarea"; import { SettingsPageTemplate } from "@/components/settings/settings-page-template"; +import { useToast } from "@/components/toast-provider"; import { useCustomPrompts } from "@/hooks/domains/settings/use-custom-prompts"; import { useAppStore } from "@/components/state-provider"; import { createPrompt, deletePrompt, updatePrompt } from "@/lib/api"; @@ -26,6 +27,10 @@ const defaultFormState = { content: "", }; +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : "Request failed"; +} + type PromptFormState = typeof defaultFormState; type PromptCreateFormProps = { @@ -46,12 +51,16 @@ function PromptCreateForm({ isBusy, }: PromptCreateFormProps) { return ( -
+
Add prompt
onFormChange({ name: event.target.value })} placeholder="Prompt name" + data-testid="prompt-name-input" />