From af6756bbbc276f0f20778d5c0309a80708bfb68b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Wed, 15 Jul 2026 19:34:18 +0100 Subject: [PATCH] feat: add archive confirmation preference (#1708) --- .../internal/backendapp/boot_state_routes.go | 1 + .../boot_state_user_settings_test.go | 18 ++++ .../internal/user/controller/controller.go | 1 + apps/backend/internal/user/dto/dto.go | 3 + apps/backend/internal/user/dto/dto_test.go | 11 +++ apps/backend/internal/user/models/models.go | 1 + apps/backend/internal/user/service/service.go | 5 + .../internal/user/service/service_test.go | 57 +++++++++++ apps/backend/internal/user/store/sqlite.go | 8 ++ .../internal/user/store/sqlite_test.go | 39 ++++++++ .../archive-confirmation-settings.test.tsx | 97 +++++++++++++++++++ .../archive-confirmation-settings.tsx | 61 ++++++++++++ .../settings/editors-settings-state.tsx | 1 + apps/web/components/settings/general-nav.ts | 15 ++- .../components/settings/general-settings.tsx | 16 +++ .../task/chat/pr-archive-banners.tsx | 2 +- .../task/task-archive-confirm-dialog.test.tsx | 93 ++++++++++++++++-- .../task/task-archive-confirm-dialog.tsx | 48 ++++++++- apps/web/e2e/fixtures/test-base.ts | 2 + apps/web/e2e/helpers/api-client.ts | 1 + .../archive-confirmation-preference.spec.ts | 44 +++++++++ ...le-archive-confirmation-preference.spec.ts | 65 +++++++++++++ .../hooks/use-ensure-user-settings.test.ts | 1 + apps/web/hooks/use-user-display-settings.ts | 7 ++ apps/web/lib/ssr/user-settings.test.ts | 26 ++++- apps/web/lib/ssr/user-settings.ts | 2 + .../state/slices/settings/settings-slice.ts | 1 + apps/web/lib/state/slices/settings/types.ts | 1 + apps/web/lib/types/backend.ts | 1 + apps/web/lib/types/http-user-settings.ts | 2 + apps/web/lib/ws/handlers/users.test.ts | 12 +++ apps/web/lib/ws/handlers/users.ts | 1 + apps/web/src/settings-routes.test.ts | 7 ++ apps/web/src/settings-routes.tsx | 2 + .../archive-confirmation-preference/plan.md | 60 ++++++++++++ .../task-01-backend-preference.md | 39 ++++++++ .../task-02-frontend-behavior.md | 41 ++++++++ .../task-03-e2e-and-verification.md | 42 ++++++++ docs/specs/INDEX.md | 1 + docs/specs/tasks/archive-confirmation.md | 62 ++++++++++++ 40 files changed, 883 insertions(+), 14 deletions(-) create mode 100644 apps/backend/internal/backendapp/boot_state_user_settings_test.go create mode 100644 apps/web/components/settings/archive-confirmation-settings.test.tsx create mode 100644 apps/web/components/settings/archive-confirmation-settings.tsx create mode 100644 apps/web/e2e/tests/task/archive-confirmation-preference.spec.ts create mode 100644 apps/web/e2e/tests/task/mobile-archive-confirmation-preference.spec.ts create mode 100644 docs/plans/archive-confirmation-preference/plan.md create mode 100644 docs/plans/archive-confirmation-preference/task-01-backend-preference.md create mode 100644 docs/plans/archive-confirmation-preference/task-02-frontend-behavior.md create mode 100644 docs/plans/archive-confirmation-preference/task-03-e2e-and-verification.md create mode 100644 docs/specs/tasks/archive-confirmation.md diff --git a/apps/backend/internal/backendapp/boot_state_routes.go b/apps/backend/internal/backendapp/boot_state_routes.go index 0ac80cc7d3..300621780b 100644 --- a/apps/backend/internal/backendapp/boot_state_routes.go +++ b/apps/backend/internal/backendapp/boot_state_routes.go @@ -454,6 +454,7 @@ func mapUserSettingsState(response userdto.UserSettingsResponse, workspaceID str "enablePreviewOnClick": settings.EnablePreviewOnClick, "chatSubmitKey": defaultString(settings.ChatSubmitKey, "cmd_enter"), "reviewAutoMarkOnScroll": settings.ReviewAutoMarkOnScroll, + "confirmTaskArchive": settings.ConfirmTaskArchive, "showReleaseNotification": settings.ShowReleaseNotification, "releaseNotesLastSeenVersion": nullString(settings.ReleaseNotesLastSeenVersion), "lspAutoStartLanguages": stringSlice(settings.LspAutoStartLanguages), diff --git a/apps/backend/internal/backendapp/boot_state_user_settings_test.go b/apps/backend/internal/backendapp/boot_state_user_settings_test.go new file mode 100644 index 0000000000..f5283e09f9 --- /dev/null +++ b/apps/backend/internal/backendapp/boot_state_user_settings_test.go @@ -0,0 +1,18 @@ +package backendapp + +import ( + "testing" + + userdto "github.com/kandev/kandev/internal/user/dto" +) + +func TestMapUserSettingsStateIncludesArchiveConfirmation(t *testing.T) { + state := mapUserSettingsState(userdto.UserSettingsResponse{ + Settings: userdto.UserSettingsDTO{ConfirmTaskArchive: true}, + }, "workspace-1") + + got, ok := state["confirmTaskArchive"].(bool) + if !ok || !got { + t.Fatalf("confirmTaskArchive = %#v, want true", state["confirmTaskArchive"]) + } +} diff --git a/apps/backend/internal/user/controller/controller.go b/apps/backend/internal/user/controller/controller.go index ba6400b1e6..6883205ec4 100644 --- a/apps/backend/internal/user/controller/controller.go +++ b/apps/backend/internal/user/controller/controller.go @@ -56,6 +56,7 @@ func (c *Controller) UpdateUserSettings(ctx context.Context, req dto.UpdateUserS EnablePreviewOnClick: req.EnablePreviewOnClick, ChatSubmitKey: req.ChatSubmitKey, ReviewAutoMarkOnScroll: req.ReviewAutoMarkOnScroll, + ConfirmTaskArchive: req.ConfirmTaskArchive, ShowReleaseNotification: req.ShowReleaseNotification, ReleaseNotesLastSeenVersion: req.ReleaseNotesLastSeenVersion, LspAutoStartLanguages: req.LspAutoStartLanguages, diff --git a/apps/backend/internal/user/dto/dto.go b/apps/backend/internal/user/dto/dto.go index af6a323063..00564c3f0c 100644 --- a/apps/backend/internal/user/dto/dto.go +++ b/apps/backend/internal/user/dto/dto.go @@ -28,6 +28,7 @@ type UserSettingsDTO struct { EnablePreviewOnClick bool `json:"enable_preview_on_click"` ChatSubmitKey string `json:"chat_submit_key"` ReviewAutoMarkOnScroll bool `json:"review_auto_mark_on_scroll"` + ConfirmTaskArchive bool `json:"confirm_task_archive"` ShowReleaseNotification bool `json:"show_release_notification"` ReleaseNotesLastSeenVersion string `json:"release_notes_last_seen_version"` LspAutoStartLanguages []string `json:"lsp_auto_start_languages"` @@ -84,6 +85,7 @@ type UpdateUserSettingsRequest struct { EnablePreviewOnClick *bool `json:"enable_preview_on_click,omitempty"` ChatSubmitKey *string `json:"chat_submit_key,omitempty"` ReviewAutoMarkOnScroll *bool `json:"review_auto_mark_on_scroll,omitempty"` + ConfirmTaskArchive *bool `json:"confirm_task_archive,omitempty"` ShowReleaseNotification *bool `json:"show_release_notification,omitempty"` ReleaseNotesLastSeenVersion *string `json:"release_notes_last_seen_version,omitempty"` LspAutoStartLanguages *[]string `json:"lsp_auto_start_languages,omitempty"` @@ -196,6 +198,7 @@ func FromUserSettings(settings *models.UserSettings) UserSettingsDTO { EnablePreviewOnClick: settings.EnablePreviewOnClick, ChatSubmitKey: settings.ChatSubmitKey, ReviewAutoMarkOnScroll: settings.ReviewAutoMarkOnScroll, + ConfirmTaskArchive: settings.ConfirmTaskArchive, ShowReleaseNotification: settings.ShowReleaseNotification, ReleaseNotesLastSeenVersion: settings.ReleaseNotesLastSeenVersion, LspAutoStartLanguages: settings.LspAutoStartLanguages, diff --git a/apps/backend/internal/user/dto/dto_test.go b/apps/backend/internal/user/dto/dto_test.go index 672172a182..9ade3644e5 100644 --- a/apps/backend/internal/user/dto/dto_test.go +++ b/apps/backend/internal/user/dto/dto_test.go @@ -3,8 +3,19 @@ package dto import ( "encoding/json" "testing" + + "github.com/kandev/kandev/internal/user/models" ) +func TestFromUserSettingsIncludesArchiveConfirmation(t *testing.T) { + for _, want := range []bool{true, false} { + dto := FromUserSettings(&models.UserSettings{ConfirmTaskArchive: want}) + if dto.ConfirmTaskArchive != want { + t.Fatalf("ConfirmTaskArchive = %v, want %v", dto.ConfirmTaskArchive, want) + } + } +} + func TestNullableSidebarDraft(t *testing.T) { t.Run("omitted field is not set", func(t *testing.T) { var req UpdateUserSettingsRequest diff --git a/apps/backend/internal/user/models/models.go b/apps/backend/internal/user/models/models.go index c828198e33..4924fd6e22 100644 --- a/apps/backend/internal/user/models/models.go +++ b/apps/backend/internal/user/models/models.go @@ -26,6 +26,7 @@ type UserSettings struct { EnablePreviewOnClick bool `json:"enable_preview_on_click"` ChatSubmitKey string `json:"chat_submit_key"` // "enter" | "cmd_enter" ReviewAutoMarkOnScroll bool `json:"review_auto_mark_on_scroll"` + ConfirmTaskArchive bool `json:"confirm_task_archive"` ShowReleaseNotification bool `json:"show_release_notification"` ReleaseNotesLastSeenVersion string `json:"release_notes_last_seen_version"` LspAutoStartLanguages []string `json:"lsp_auto_start_languages"` diff --git a/apps/backend/internal/user/service/service.go b/apps/backend/internal/user/service/service.go index 61d42bcc3e..d7c29839af 100644 --- a/apps/backend/internal/user/service/service.go +++ b/apps/backend/internal/user/service/service.go @@ -47,6 +47,7 @@ type UpdateUserSettingsRequest struct { EnablePreviewOnClick *bool ChatSubmitKey *string ReviewAutoMarkOnScroll *bool + ConfirmTaskArchive *bool ShowReleaseNotification *bool ReleaseNotesLastSeenVersion *string LspAutoStartLanguages *[]string @@ -213,6 +214,9 @@ func applyBasicSettings(settings *models.UserSettings, req *UpdateUserSettingsRe if req.ReviewAutoMarkOnScroll != nil { settings.ReviewAutoMarkOnScroll = *req.ReviewAutoMarkOnScroll } + if req.ConfirmTaskArchive != nil { + settings.ConfirmTaskArchive = *req.ConfirmTaskArchive + } if req.ShowReleaseNotification != nil { settings.ShowReleaseNotification = *req.ShowReleaseNotification } @@ -542,6 +546,7 @@ func (s *Service) publishUserSettingsEvent(ctx context.Context, settings *models "enable_preview_on_click": settings.EnablePreviewOnClick, "chat_submit_key": settings.ChatSubmitKey, "review_auto_mark_on_scroll": settings.ReviewAutoMarkOnScroll, + "confirm_task_archive": settings.ConfirmTaskArchive, "show_release_notification": settings.ShowReleaseNotification, "release_notes_last_seen_version": settings.ReleaseNotesLastSeenVersion, "lsp_auto_start_languages": settings.LspAutoStartLanguages, diff --git a/apps/backend/internal/user/service/service_test.go b/apps/backend/internal/user/service/service_test.go index 93c51b0c01..becc0f7ed8 100644 --- a/apps/backend/internal/user/service/service_test.go +++ b/apps/backend/internal/user/service/service_test.go @@ -104,6 +104,42 @@ func TestApplyBasicSettings_ReleaseNotes(t *testing.T) { }) } +func TestApplyBasicSettings_ConfirmTaskArchive(t *testing.T) { + t.Run("omitted value leaves confirmation enabled", func(t *testing.T) { + settings := &models.UserSettings{ConfirmTaskArchive: true} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !settings.ConfirmTaskArchive { + t.Fatal("expected archive confirmation to remain enabled") + } + }) + + t.Run("explicit false disables confirmation", func(t *testing.T) { + settings := &models.UserSettings{ConfirmTaskArchive: true} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{ + ConfirmTaskArchive: ptr(false), + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if settings.ConfirmTaskArchive { + t.Fatal("expected archive confirmation to be disabled") + } + }) + + t.Run("explicit true re-enables confirmation", func(t *testing.T) { + settings := &models.UserSettings{ConfirmTaskArchive: false} + if err := applyBasicSettings(settings, &UpdateUserSettingsRequest{ + ConfirmTaskArchive: ptr(true), + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !settings.ConfirmTaskArchive { + t.Fatal("expected archive confirmation to be enabled") + } + }) +} + func TestApplyBasicSettings_TasksListPreferences(t *testing.T) { t.Run("sets valid sort and group", func(t *testing.T) { settings := &models.UserSettings{} @@ -656,6 +692,27 @@ func TestUpdateUserSettingsCombinesSettingsAndTaskCreatePatch(t *testing.T) { } } +func TestPublishUserSettingsEventIncludesArchiveConfirmation(t *testing.T) { + log, err := logger.NewFromZap(zap.NewNop()) + if err != nil { + t.Fatalf("logger.NewFromZap: %v", err) + } + eventBus := &recordingEventBus{} + svc := NewService(&recordingUserRepository{}, eventBus, log) + svc.publishUserSettingsEvent(context.Background(), &models.UserSettings{ConfirmTaskArchive: false}) + + if len(eventBus.publishedEvents) != 1 { + t.Fatalf("expected one settings event, got %d", len(eventBus.publishedEvents)) + } + eventData, ok := eventBus.publishedEvents[0].Data.(map[string]interface{}) + if !ok { + t.Fatalf("expected event data map, got %T", eventBus.publishedEvents[0].Data) + } + if confirmTaskArchive, ok := eventData["confirm_task_archive"].(bool); !ok || confirmTaskArchive { + t.Fatalf("confirm_task_archive = %#v, want false", eventData["confirm_task_archive"]) + } +} + func TestClearDefaultEditorIDPreservesTaskCreateLastUsed(t *testing.T) { log, err := logger.NewFromZap(zap.NewNop()) if err != nil { diff --git a/apps/backend/internal/user/store/sqlite.go b/apps/backend/internal/user/store/sqlite.go index 149532f59f..e480d55f5d 100644 --- a/apps/backend/internal/user/store/sqlite.go +++ b/apps/backend/internal/user/store/sqlite.go @@ -337,6 +337,7 @@ func marshalUserSettingsPayload(settings *models.UserSettings) ([]byte, error) { "enable_preview_on_click": settings.EnablePreviewOnClick, "chat_submit_key": settings.ChatSubmitKey, "review_auto_mark_on_scroll": settings.ReviewAutoMarkOnScroll, + "confirm_task_archive": settings.ConfirmTaskArchive, "show_release_notification": settings.ShowReleaseNotification, "release_notes_last_seen_version": settings.ReleaseNotesLastSeenVersion, "lsp_auto_start_languages": lspAutoStart, @@ -453,6 +454,7 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin settings.TasksListGroup = models.TasksListGroupDefault settings.ShowReleaseNotification = true settings.ReviewAutoMarkOnScroll = true + settings.ConfirmTaskArchive = true settings.ChatSubmitKey = "cmd_enter" settings.KeyboardShortcuts = map[string]interface{}{} settings.TerminalLinkBehavior = "new_tab" @@ -475,6 +477,7 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin EnablePreviewOnClick bool `json:"enable_preview_on_click"` ChatSubmitKey string `json:"chat_submit_key"` ReviewAutoMarkOnScroll *bool `json:"review_auto_mark_on_scroll"` + ConfirmTaskArchive *bool `json:"confirm_task_archive"` ShowReleaseNotification *bool `json:"show_release_notification"` ReleaseNotesLastSeenVersion string `json:"release_notes_last_seen_version"` LspAutoStartLanguages []string `json:"lsp_auto_start_languages"` @@ -525,6 +528,11 @@ func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID strin } else { settings.ReviewAutoMarkOnScroll = true } + if payload.ConfirmTaskArchive != nil { + settings.ConfirmTaskArchive = *payload.ConfirmTaskArchive + } else { + settings.ConfirmTaskArchive = true + } if payload.ShowReleaseNotification != nil { settings.ShowReleaseNotification = *payload.ShowReleaseNotification } else { diff --git a/apps/backend/internal/user/store/sqlite_test.go b/apps/backend/internal/user/store/sqlite_test.go index d200339ece..ab40894e47 100644 --- a/apps/backend/internal/user/store/sqlite_test.go +++ b/apps/backend/internal/user/store/sqlite_test.go @@ -67,6 +67,45 @@ func TestScanUserSettingsChangesPanelLayoutDefault(t *testing.T) { }) } +func TestScanUserSettingsConfirmTaskArchiveDefault(t *testing.T) { + tests := []struct { + name string + raw string + want bool + }{ + {name: "empty settings require confirmation", raw: `{}`, want: true}, + {name: "missing setting requires confirmation", raw: `{"chat_submit_key":"enter"}`, want: true}, + {name: "explicit false skips confirmation", raw: `{"confirm_task_archive":false}`, want: false}, + } + + 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.ConfirmTaskArchive != tt.want { + t.Fatalf("ConfirmTaskArchive = %v, want %v", settings.ConfirmTaskArchive, tt.want) + } + }) + } +} + +func TestMarshalUserSettingsPersistsDisabledArchiveConfirmation(t *testing.T) { + raw, err := marshalUserSettingsPayload(&models.UserSettings{ConfirmTaskArchive: false}) + 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, ok := payload["confirm_task_archive"].(bool); !ok || got { + t.Fatalf("confirm_task_archive = %#v, want false", payload["confirm_task_archive"]) + } +} + func TestScanUserSettingsSystemMetricsDisplayDefault(t *testing.T) { settings, err := scanUserSettings(settingsScanner{raw: "{}"}, DefaultUserID) if err != nil { diff --git a/apps/web/components/settings/archive-confirmation-settings.test.tsx b/apps/web/components/settings/archive-confirmation-settings.test.tsx new file mode 100644 index 0000000000..2547c90cbe --- /dev/null +++ b/apps/web/components/settings/archive-confirmation-settings.test.tsx @@ -0,0 +1,97 @@ +import { type ReactNode } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { StateProvider, useAppStore } from "@/components/state-provider"; +import { defaultState } from "@/lib/state/default-state"; + +const updateUserSettings = vi.fn(); +const CONFIRMATION_LABEL = "Confirm before archiving tasks"; +const DATA_STATE_ATTRIBUTE = "data-state"; +const CHECKED_STATE = "checked"; +const UNCHECKED_STATE = "unchecked"; + +vi.mock("@/lib/api", () => ({ + updateUserSettings: (...args: unknown[]) => updateUserSettings(...args), +})); + +import { ArchiveConfirmationSettings } from "./archive-confirmation-settings"; + +function renderSettings(confirmTaskArchive = true, children?: ReactNode) { + return render( + + + {children} + , + ); +} + +function RemoteSettingsUpdate() { + const settings = useAppStore((state) => state.userSettings); + const setUserSettings = useAppStore((state) => state.setUserSettings); + + return ( + + ); +} + +beforeEach(() => { + updateUserSettings.mockReset().mockResolvedValue({ settings: {} }); +}); + +afterEach(cleanup); + +describe("ArchiveConfirmationSettings", () => { + it("is enabled by default and persists an explicit false value", async () => { + renderSettings(); + const toggle = screen.getByRole("switch", { name: CONFIRMATION_LABEL }); + + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(CHECKED_STATE); + fireEvent.click(toggle); + + await waitFor(() => + expect(updateUserSettings).toHaveBeenCalledWith({ confirm_task_archive: false }), + ); + expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE); + }); + + it("rolls back when saving fails", async () => { + updateUserSettings.mockRejectedValueOnce(new Error("save failed")); + renderSettings(); + const toggle = screen.getByRole("switch", { name: CONFIRMATION_LABEL }); + + fireEvent.click(toggle); + + await waitFor(() => expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE)); + await waitFor(() => expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(CHECKED_STATE)); + }); + + it("does not overwrite a newer settings update when saving fails", async () => { + let rejectSave: (reason?: unknown) => void = () => {}; + updateUserSettings.mockImplementationOnce( + () => + new Promise((_, reject: (reason?: unknown) => void) => { + rejectSave = reject; + }), + ); + renderSettings(true, ); + const toggle = screen.getByRole("switch", { name: CONFIRMATION_LABEL }); + + fireEvent.click(toggle); + await waitFor(() => expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE)); + fireEvent.click(screen.getByRole("button", { name: "Apply remote settings" })); + rejectSave(new Error("save failed")); + + await waitFor(() => expect(toggle.getAttribute(DATA_STATE_ATTRIBUTE)).toBe(UNCHECKED_STATE)); + }); +}); diff --git a/apps/web/components/settings/archive-confirmation-settings.tsx b/apps/web/components/settings/archive-confirmation-settings.tsx new file mode 100644 index 0000000000..dac3c5a6ec --- /dev/null +++ b/apps/web/components/settings/archive-confirmation-settings.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { useState } from "react"; +import { Card, 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"; + +export function ArchiveConfirmationSettings() { + const confirmTaskArchive = useAppStore((state) => state.userSettings.confirmTaskArchive); + const setUserSettings = useAppStore((state) => state.setUserSettings); + const storeApi = useAppStoreApi(); + const [isSaving, setIsSaving] = useState(false); + + const handleToggle = async (checked: boolean) => { + if (isSaving) return; + + const current = storeApi.getState().userSettings; + const previous = current.confirmTaskArchive; + const workspaceId = current.workspaceId; + setIsSaving(true); + setUserSettings({ ...current, confirmTaskArchive: checked }); + + try { + await updateUserSettings({ confirm_task_archive: checked }); + } catch { + const latest = storeApi.getState().userSettings; + if (latest.workspaceId === workspaceId && latest.confirmTaskArchive === checked) { + setUserSettings({ ...latest, confirmTaskArchive: previous }); + } + } finally { + setIsSaving(false); + } + }; + + return ( + + + Archive Confirmation + + +
+
+ +

+ Show cleanup details and subtask options before an archive starts. +

+
+ +
+
+
+ ); +} diff --git a/apps/web/components/settings/editors-settings-state.tsx b/apps/web/components/settings/editors-settings-state.tsx index 93ab06a241..824c024fe2 100644 --- a/apps/web/components/settings/editors-settings-state.tsx +++ b/apps/web/components/settings/editors-settings-state.tsx @@ -243,6 +243,7 @@ function mapEditorBehaviorFields( return { chatSubmitKey: s.chat_submit_key ?? "cmd_enter", reviewAutoMarkOnScroll: s.review_auto_mark_on_scroll ?? true, + confirmTaskArchive: s.confirm_task_archive ?? true, showReleaseNotification: s.show_release_notification ?? true, releaseNotesLastSeenVersion: (s.release_notes_last_seen_version as string) || null, savedLayouts: s.saved_layouts ?? [], diff --git a/apps/web/components/settings/general-nav.ts b/apps/web/components/settings/general-nav.ts index 6a20d0f60c..d6313c8f8d 100644 --- a/apps/web/components/settings/general-nav.ts +++ b/apps/web/components/settings/general-nav.ts @@ -1,4 +1,11 @@ -import { IconBell, IconCommand, IconCode, IconPalette, IconTerminal2 } from "@tabler/icons-react"; +import { + IconArchive, + IconBell, + IconCommand, + IconCode, + IconPalette, + IconTerminal2, +} from "@tabler/icons-react"; import type { Icon as TablerIcon } from "@tabler/icons-react"; export type GeneralNavItem = { @@ -39,4 +46,10 @@ export const GENERAL_NAV_ITEMS: GeneralNavItem[] = [ description: "Chat input and command shortcuts", icon: IconCommand, }, + { + href: "/settings/general/task-actions", + label: "Task Actions", + description: "Archive safeguards and task action preferences", + icon: IconArchive, + }, ]; diff --git a/apps/web/components/settings/general-settings.tsx b/apps/web/components/settings/general-settings.tsx index 50995a4927..9b94166664 100644 --- a/apps/web/components/settings/general-settings.tsx +++ b/apps/web/components/settings/general-settings.tsx @@ -9,6 +9,7 @@ import { IconPalette, IconKeyboard, IconGitBranch, + IconArchive, } from "@tabler/icons-react"; import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card"; import { Label } from "@kandev/ui/label"; @@ -21,6 +22,7 @@ import { GENERAL_NAV_ITEMS } from "@/components/settings/general-nav"; import { useAppStore, useAppStoreApi } from "@/components/state-provider"; import { updateUserSettings } from "@/lib/api"; import type { Theme } from "@/lib/settings/types"; +import { ArchiveConfirmationSettings } from "@/components/settings/archive-confirmation-settings"; function ThemeSettingsCard() { const { theme: currentTheme, setTheme } = useTheme(); @@ -187,6 +189,20 @@ export function GeneralSettings() { ); } +export function TaskActionsSettings() { + return ( +
+ } + title="Task Actions" + description="Configure safeguards for task actions" + > + + +
+ ); +} + export function AppearanceSettings() { return (
diff --git a/apps/web/components/task/chat/pr-archive-banners.tsx b/apps/web/components/task/chat/pr-archive-banners.tsx index a134759e8f..aa4cdd5c08 100644 --- a/apps/web/components/task/chat/pr-archive-banners.tsx +++ b/apps/web/components/task/chat/pr-archive-banners.tsx @@ -54,7 +54,7 @@ function useBannerArchiveConfirm(taskId: string) { // Presentational banner shared by PRMergedBanner / PRClosedBanner — an icon, a // message, and Archive + Dismiss controls. Colors/icon/testIds are supplied by // the caller so the two variants stay visually distinct. The Archive control -// opens the shared archive confirmation dialog rather than archiving directly. +// routes through the shared preference-aware archive flow. function ArchiveDismissBanner({ testIdPrefix, icon, 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 bb718696cf..9a58d3b0b8 100644 --- a/apps/web/components/task/task-archive-confirm-dialog.test.tsx +++ b/apps/web/components/task/task-archive-confirm-dialog.test.tsx @@ -1,5 +1,8 @@ +import { StrictMode, type ReactNode } from "react"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { render, screen, cleanup } from "@testing-library/react"; +import { render, screen, cleanup, fireEvent, waitFor } from "@testing-library/react"; +import { StateProvider, useAppStore } from "@/components/state-provider"; +import { defaultState } from "@/lib/state/default-state"; const mockGetSubtaskCount = vi.fn(); @@ -9,6 +12,32 @@ vi.mock("@/lib/api", () => ({ import { TaskArchiveConfirmDialog } from "./task-archive-confirm-dialog"; +function renderDialog(ui: ReactNode, confirmTaskArchive = true) { + return render( + + {ui} + , + ); +} + +function DisableArchiveConfirmationButton() { + const settings = useAppStore((state) => state.userSettings); + const setUserSettings = useAppStore((state) => state.setUserSettings); + + return ( + + ); +} + beforeEach(() => { mockGetSubtaskCount.mockReset(); mockGetSubtaskCount.mockResolvedValue({ count: 0 }); @@ -16,9 +45,59 @@ beforeEach(() => { afterEach(cleanup); +describe("TaskArchiveConfirmDialog preference", () => { + it("archives once without rendering a dialog when confirmation is disabled", async () => { + const onConfirm = vi.fn(); + const onOpenChange = vi.fn(); + + renderDialog( + + + , + false, + ); + + await waitFor(() => expect(onConfirm).toHaveBeenCalledWith({ cascade: false })); + expect(onConfirm).toHaveBeenCalledTimes(1); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(screen.queryByRole("alertdialog")).toBeNull(); + }); + + it("does not auto-archive an already-open dialog after a settings sync", () => { + const onConfirm = vi.fn(); + + renderDialog( + <> + + {}} + taskTitle="My task" + taskId="task-1" + executorType="worktree" + onConfirm={onConfirm} + /> + , + ); + + expect(screen.getByRole("alertdialog")).toBeTruthy(); + fireEvent.click(screen.getByText("Disable archive confirmation", { selector: "button" })); + + expect(onConfirm).not.toHaveBeenCalled(); + expect(screen.getByRole("alertdialog")).toBeTruthy(); + }); +}); + describe("TaskArchiveConfirmDialog cleanup copy", () => { it("renders local-executor reassurance about untouched repo", () => { - render( + renderDialog( {}} @@ -32,7 +111,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => { }); it("renders worktree-executor copy about worktree + branch removal", () => { - render( + renderDialog( {}} @@ -46,7 +125,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => { }); it("warns about sandbox destruction for sprites executor", () => { - render( + renderDialog( {}} @@ -61,7 +140,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => { }); it("describes Docker container removal for local_docker", () => { - render( + renderDialog( {}} @@ -75,7 +154,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => { }); it("renders grouped copy for bulk archive", () => { - render( + renderDialog( {}} @@ -91,7 +170,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => { }); it("no longer renders the old hardcoded worktree line for non-worktree executors", () => { - render( + renderDialog( {}} diff --git a/apps/web/components/task/task-archive-confirm-dialog.tsx b/apps/web/components/task/task-archive-confirm-dialog.tsx index f1c4d8ccea..ba35bb2efc 100644 --- a/apps/web/components/task/task-archive-confirm-dialog.tsx +++ b/apps/web/components/task/task-archive-confirm-dialog.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { IconLoader } from "@tabler/icons-react"; import { AlertDialog, @@ -13,6 +13,7 @@ import { AlertDialogTitle, } from "@kandev/ui/alert-dialog"; import { Checkbox } from "@kandev/ui/checkbox"; +import { useAppStore } from "@/components/state-provider"; import { useSubtaskCount } from "@/hooks/use-subtask-count"; import { getCleanupSummary, getBulkCleanupSummary } from "./task-cleanup-summary"; @@ -33,6 +34,40 @@ type TaskArchiveConfirmDialogProps = { confirmTestId?: string; }; +type ArchiveOpenMode = "pending" | "confirm" | "bypass"; + +function useArchiveConfirmationMode( + open: boolean, + confirmTaskArchive: boolean, + onConfirm: TaskArchiveConfirmDialogProps["onConfirm"], + onOpenChange: TaskArchiveConfirmDialogProps["onOpenChange"], +) { + const wasOpenRef = useRef(false); + const [archiveOpenMode, setArchiveOpenMode] = useState("pending"); + + useEffect(() => { + const openedNow = open && !wasOpenRef.current; + wasOpenRef.current = open; + + if (!open) { + setArchiveOpenMode("pending"); + return; + } + if (!openedNow) return; + + if (confirmTaskArchive) { + setArchiveOpenMode("confirm"); + return; + } + + setArchiveOpenMode("bypass"); + onConfirm({ cascade: false }); + onOpenChange(false); + }, [confirmTaskArchive, onConfirm, onOpenChange, open]); + + return archiveOpenMode === "confirm" || (archiveOpenMode === "pending" && confirmTaskArchive); +} + export function TaskArchiveConfirmDialog({ open, onOpenChange, @@ -47,6 +82,7 @@ export function TaskArchiveConfirmDialog({ onConfirm, confirmTestId, }: TaskArchiveConfirmDialogProps) { + const confirmTaskArchive = useAppStore((state) => state.userSettings?.confirmTaskArchive ?? true); const safeCount = count ?? 0; const label = isBulkOperation ? `task${safeCount !== 1 ? "s" : ""}` : "task"; const title = isBulkOperation ? `Archive ${safeCount} ${label}?` : "Archive task?"; @@ -58,13 +94,21 @@ export function TaskArchiveConfirmDialog({ : getCleanupSummary(executorType); const [cascade, setCascade] = useState(false); - const subtaskCount = useSubtaskCount(open, taskId, taskIds); + const requiresConfirmation = useArchiveConfirmationMode( + open, + confirmTaskArchive, + onConfirm, + onOpenChange, + ); + const subtaskCount = useSubtaskCount(open && requiresConfirmation, taskId, taskIds); const handleOpenChange = (next: boolean) => { if (!next) setCascade(false); onOpenChange(next); }; + if (!requiresConfirmation) return null; + return ( e.stopPropagation()}> diff --git a/apps/web/e2e/fixtures/test-base.ts b/apps/web/e2e/fixtures/test-base.ts index a087536ed9..8bdbb375eb 100644 --- a/apps/web/e2e/fixtures/test-base.ts +++ b/apps/web/e2e/fixtures/test-base.ts @@ -167,6 +167,7 @@ export const test = backendFixture.extend< workflow_filter_id: seedData.workflowId, keyboard_shortcuts: {}, enable_preview_on_click: false, + confirm_task_archive: true, sidebar_views: [], // Reset to default kanban view. Pipeline-view tests switch this to // "graph2", which persists per-workspace; without this reset the next @@ -229,6 +230,7 @@ test.beforeEach(async ({ apiClient, seedData }) => { workflow_filter_id: seedData.workflowId, keyboard_shortcuts: {}, enable_preview_on_click: false, + confirm_task_archive: true, sidebar_views: [], kanban_view_mode: "", }); diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index 0ae47f962b..2017d05e87 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -657,6 +657,7 @@ export class ApiClient { async saveUserSettings(settings: { enable_preview_on_click?: boolean; + confirm_task_archive?: boolean; workspace_id?: string; workflow_filter_id?: string; repository_ids?: string[]; diff --git a/apps/web/e2e/tests/task/archive-confirmation-preference.spec.ts b/apps/web/e2e/tests/task/archive-confirmation-preference.spec.ts new file mode 100644 index 0000000000..e5b500e2f4 --- /dev/null +++ b/apps/web/e2e/tests/task/archive-confirmation-preference.spec.ts @@ -0,0 +1,44 @@ +import { test, expect } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +test.describe("Archive confirmation preference", () => { + test("disabling confirmation archives immediately from the desktop sidebar", async ({ + testPage, + apiClient, + seedData, + }) => { + await testPage.goto("/settings/general/task-actions"); + const toggle = testPage.getByRole("switch", { name: "Confirm before archiving tasks" }); + await expect(toggle).toBeChecked(); + await toggle.click(); + await expect(toggle).not.toBeChecked(); + await expect + .poll(async () => (await apiClient.getUserSettings()).settings.confirm_task_archive) + .toBe(false); + + const taskOptions = { + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + }; + const navTask = await apiClient.seedTask( + seedData.workspaceId, + "Archive Preference Nav", + taskOptions, + ); + await apiClient.seedTask(seedData.workspaceId, "Archive Without Confirmation", taskOptions); + + await testPage.goto(`/t/${navTask.task_id}`); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await expect(session.taskInSidebar("Archive Without Confirmation")).toBeVisible({ + timeout: 15_000, + }); + + await session.openSidebarMenuAndClick("Archive Without Confirmation", "Archive"); + + await expect(testPage.getByRole("alertdialog")).toHaveCount(0); + await expect(session.taskInSidebar("Archive Without Confirmation")).toHaveCount(0, { + timeout: 15_000, + }); + }); +}); diff --git a/apps/web/e2e/tests/task/mobile-archive-confirmation-preference.spec.ts b/apps/web/e2e/tests/task/mobile-archive-confirmation-preference.spec.ts new file mode 100644 index 0000000000..658613cba8 --- /dev/null +++ b/apps/web/e2e/tests/task/mobile-archive-confirmation-preference.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from "../../fixtures/test-base"; +import { SessionPage } from "../../pages/session-page"; + +test.describe("Archive confirmation preference on mobile", () => { + test("disabling confirmation archives immediately from the task switcher", async ({ + testPage, + apiClient, + seedData, + }) => { + await testPage.goto("/settings/general/task-actions"); + const toggle = testPage.getByRole("switch", { name: "Confirm before archiving tasks" }); + await expect(toggle).toBeChecked(); + await toggle.click(); + await expect(toggle).not.toBeChecked(); + await expect + .poll(async () => (await apiClient.getUserSettings()).settings.confirm_task_archive) + .toBe(false); + + const taskOptions = { + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + }; + const navTask = await apiClient.seedTask( + seedData.workspaceId, + "Mobile Archive Preference Nav", + taskOptions, + ); + await apiClient.seedTask( + seedData.workspaceId, + "Mobile Archive Without Confirmation", + taskOptions, + ); + + await testPage.goto(`/t/${navTask.task_id}`); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await testPage.getByTestId("mobile-session-menu").click(); + + const sheet = testPage.getByRole("dialog"); + const taskRow = sheet + .getByTestId("sidebar-task-item") + .filter({ hasText: "Mobile Archive Without Confirmation" }); + await expect(taskRow).toBeVisible({ timeout: 15_000 }); + + await taskRow.dispatchEvent("pointerdown", { + pointerType: "touch", + isPrimary: true, + button: 0, + clientX: 120, + clientY: 240, + }); + await testPage.waitForTimeout(1000); + await taskRow.dispatchEvent("pointerup", { + pointerType: "touch", + isPrimary: true, + button: 0, + clientX: 120, + clientY: 240, + }); + await testPage.getByRole("menuitem", { name: "Archive" }).click(); + + await expect(testPage.getByRole("alertdialog")).toHaveCount(0); + await expect(taskRow).toHaveCount(0, { timeout: 15_000 }); + }); +}); diff --git a/apps/web/hooks/use-ensure-user-settings.test.ts b/apps/web/hooks/use-ensure-user-settings.test.ts index 55f227228b..7ab184be76 100644 --- a/apps/web/hooks/use-ensure-user-settings.test.ts +++ b/apps/web/hooks/use-ensure-user-settings.test.ts @@ -58,6 +58,7 @@ function makeUnloadedSettings(): UserSettingsState { enablePreviewOnClick: false, chatSubmitKey: "cmd_enter", reviewAutoMarkOnScroll: true, + confirmTaskArchive: true, showReleaseNotification: true, releaseNotesLastSeenVersion: null, savedLayouts: [], diff --git a/apps/web/hooks/use-user-display-settings.ts b/apps/web/hooks/use-user-display-settings.ts index 11dc1b8715..50a2a8ca8d 100644 --- a/apps/web/hooks/use-user-display-settings.ts +++ b/apps/web/hooks/use-user-display-settings.ts @@ -68,6 +68,12 @@ function carryForwardCoreSettings(current: DisplaySettings) { }; } +function carryForwardTaskActionSettings(current: DisplaySettings) { + return { + confirmTaskArchive: current.confirmTaskArchive ?? true, + }; +} + function carryForwardSidebarSettings(current: DisplaySettings) { return { sidebarViews: current.sidebarViews ?? [], @@ -100,6 +106,7 @@ function carryForwardSyncedLocalSettings(current: DisplaySettings) { function carryForwardSettings(current: DisplaySettings) { return { ...carryForwardCoreSettings(current), + ...carryForwardTaskActionSettings(current), ...carryForwardSidebarSettings(current), ...carryForwardSyncedLocalSettings(current), ...carryForwardLspSettings(current), diff --git a/apps/web/lib/ssr/user-settings.test.ts b/apps/web/lib/ssr/user-settings.test.ts index 901f0bb325..8ea24499c1 100644 --- a/apps/web/lib/ssr/user-settings.test.ts +++ b/apps/web/lib/ssr/user-settings.test.ts @@ -7,6 +7,8 @@ import { } from "./user-settings"; import { workspaceId as toWorkspaceId } from "@/lib/types/ids"; +const UPDATED_AT = "2026-01-01T00:00:00Z"; + describe("buildCoreFields", () => { it("maps terminal_font_family to terminalFontFamily", () => { const settings = { @@ -27,7 +29,7 @@ describe("buildCoreFields", () => { keyboard_shortcuts: {}, terminal_link_behavior: "new_tab", terminal_font_family: "JetBrains Mono", - updated_at: "2026-01-01T00:00:00Z", + updated_at: UPDATED_AT, } as unknown as Parameters[0]; const result = buildCoreFields(settings); @@ -53,7 +55,7 @@ describe("buildCoreFields", () => { keyboard_shortcuts: {}, terminal_link_behavior: "new_tab", terminal_font_family: "", - updated_at: "2026-01-01T00:00:00Z", + updated_at: UPDATED_AT, } as unknown as Parameters[0]; const result = buildCoreFields(settings); @@ -115,6 +117,24 @@ describe("buildTerminalFields via buildCoreFields", () => { }); describe("mapUserSettingsResponse", () => { + it("requires archive confirmation when settings are unavailable", () => { + expect(mapUserSettingsResponse(null).confirmTaskArchive).toBe(true); + }); + + it("preserves an explicitly disabled archive confirmation preference", () => { + const result = mapUserSettingsResponse({ + settings: { + user_id: "default-user", + workspace_id: toWorkspaceId(""), + repository_ids: [], + confirm_task_archive: false, + updated_at: UPDATED_AT, + }, + }); + + expect(result.confirmTaskArchive).toBe(false); + }); + it("returns null terminalFontFamily when response is null", () => { const result = mapUserSettingsResponse(null); expect(result.terminalFontFamily).toBeNull(); @@ -148,7 +168,7 @@ describe("mapUserSettingsResponse", () => { sort: { key: "updatedAt", direction: "desc" }, group: "workflow", }, - updated_at: "2026-01-01T00:00:00Z", + updated_at: UPDATED_AT, }, }); diff --git a/apps/web/lib/ssr/user-settings.ts b/apps/web/lib/ssr/user-settings.ts index 9fd34813cd..02fda06bea 100644 --- a/apps/web/lib/ssr/user-settings.ts +++ b/apps/web/lib/ssr/user-settings.ts @@ -107,6 +107,7 @@ function buildBehaviorFields(s: UserSettingsData) { enablePreviewOnClick: s.enable_preview_on_click ?? false, chatSubmitKey: s.chat_submit_key ?? "cmd_enter", reviewAutoMarkOnScroll: s.review_auto_mark_on_scroll ?? true, + confirmTaskArchive: s.confirm_task_archive ?? true, showReleaseNotification: s.show_release_notification ?? true, releaseNotesLastSeenVersion: s.release_notes_last_seen_version || null, keyboardShortcuts: s.keyboard_shortcuts ?? {}, @@ -165,6 +166,7 @@ export function mapUserSettingsResponse(response: UserSettingsResponse | null) { enablePreviewOnClick: false, chatSubmitKey: "cmd_enter" as const, reviewAutoMarkOnScroll: true, + confirmTaskArchive: true, showReleaseNotification: true, releaseNotesLastSeenVersion: null, savedLayouts: [] as SavedLayout[], diff --git a/apps/web/lib/state/slices/settings/settings-slice.ts b/apps/web/lib/state/slices/settings/settings-slice.ts index ad45b6bdeb..1a4dcebe3d 100644 --- a/apps/web/lib/state/slices/settings/settings-slice.ts +++ b/apps/web/lib/state/slices/settings/settings-slice.ts @@ -35,6 +35,7 @@ export const defaultSettingsState: SettingsSliceState = { terminalLinkBehavior: "new_tab", chatSubmitKey: "cmd_enter", reviewAutoMarkOnScroll: true, + confirmTaskArchive: true, showReleaseNotification: true, releaseNotesLastSeenVersion: null, lspAutoStartLanguages: [], diff --git a/apps/web/lib/state/slices/settings/types.ts b/apps/web/lib/state/slices/settings/types.ts index cba073f37a..3f5148a286 100644 --- a/apps/web/lib/state/slices/settings/types.ts +++ b/apps/web/lib/state/slices/settings/types.ts @@ -152,6 +152,7 @@ export type UserSettingsState = { enablePreviewOnClick: boolean; chatSubmitKey: "enter" | "cmd_enter"; reviewAutoMarkOnScroll: boolean; + confirmTaskArchive: boolean; showReleaseNotification: boolean; releaseNotesLastSeenVersion: string | null; lspAutoStartLanguages: string[]; diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index 8e4a3b1ee6..10e9a19e1c 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -336,6 +336,7 @@ export type UserSettingsUpdatedPayload = { enable_preview_on_click?: boolean; chat_submit_key?: string; review_auto_mark_on_scroll?: boolean; + confirm_task_archive?: boolean; show_release_notification?: boolean; release_notes_last_seen_version?: string; lsp_auto_start_languages?: string[]; diff --git a/apps/web/lib/types/http-user-settings.ts b/apps/web/lib/types/http-user-settings.ts index 540ddb41de..310a16ecfc 100644 --- a/apps/web/lib/types/http-user-settings.ts +++ b/apps/web/lib/types/http-user-settings.ts @@ -52,6 +52,7 @@ export type UserSettings = { enable_preview_on_click?: boolean; chat_submit_key?: "enter" | "cmd_enter"; review_auto_mark_on_scroll?: boolean; + confirm_task_archive?: boolean; show_release_notification?: boolean; release_notes_last_seen_version?: string; lsp_auto_start_languages?: string[]; @@ -97,6 +98,7 @@ export type UserSettingsUpdatePayload = { enable_preview_on_click?: boolean; chat_submit_key?: "enter" | "cmd_enter"; review_auto_mark_on_scroll?: boolean; + confirm_task_archive?: boolean; show_release_notification?: boolean; release_notes_last_seen_version?: string; lsp_auto_start_languages?: string[]; diff --git a/apps/web/lib/ws/handlers/users.test.ts b/apps/web/lib/ws/handlers/users.test.ts index b1994f6558..3d99fad9ce 100644 --- a/apps/web/lib/ws/handlers/users.test.ts +++ b/apps/web/lib/ws/handlers/users.test.ts @@ -25,6 +25,18 @@ function userSettingsMessage( } describe("user settings websocket handler", () => { + it("applies archive confirmation preferences and defaults missing values to enabled", () => { + const store = makeStore(); + + registerUsersHandlers(store)["user.settings.updated"]?.( + userSettingsMessage({ confirm_task_archive: false }), + ); + expect(store.getState().userSettings.confirmTaskArchive).toBe(false); + + registerUsersHandlers(store)["user.settings.updated"]?.(userSettingsMessage({})); + expect(store.getState().userSettings.confirmTaskArchive).toBe(true); + }); + it("preserves local collapsed groups when syncing sidebar views", () => { const store = makeStore(); store.setState((state) => ({ diff --git a/apps/web/lib/ws/handlers/users.ts b/apps/web/lib/ws/handlers/users.ts index b118998d83..888610547e 100644 --- a/apps/web/lib/ws/handlers/users.ts +++ b/apps/web/lib/ws/handlers/users.ts @@ -75,6 +75,7 @@ function buildBehaviorSettings(payload: UserSettingsUpdatedPayload) { enablePreviewOnClick: payload.enable_preview_on_click ?? false, chatSubmitKey: (payload.chat_submit_key as "enter" | "cmd_enter") ?? "cmd_enter", reviewAutoMarkOnScroll: payload.review_auto_mark_on_scroll ?? true, + confirmTaskArchive: payload.confirm_task_archive ?? true, showReleaseNotification: payload.show_release_notification ?? true, releaseNotesLastSeenVersion: (payload.release_notes_last_seen_version as string) || null, terminalLinkBehavior: diff --git a/apps/web/src/settings-routes.test.ts b/apps/web/src/settings-routes.test.ts index 7197dec4b5..584490d903 100644 --- a/apps/web/src/settings-routes.test.ts +++ b/apps/web/src/settings-routes.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from "vitest"; import { isValidElement, type ReactElement } from "react"; import IntegrationsGitLabPage from "@/app/settings/integrations/gitlab/page"; +import { TaskActionsSettings } from "@/components/settings/general-settings"; import { workspaceId, workflowId } from "@/lib/types/ids"; import type { ListWorkspacesResponse, UserSettingsResponse } from "@/lib/types/http"; import { buildSettingsInitialStateForRoute, renderSettingsRoute } from "./settings-routes"; @@ -110,6 +111,12 @@ describe("buildSettingsInitialStateForRoute", () => { }); describe("renderSettingsRoute", () => { + it("renders task action preferences from General settings", () => { + const route = renderSettingsRoute("/settings/general/task-actions"); + expect(isValidElement(route)).toBe(true); + expect((route as ReactElement).type).toBe(TaskActionsSettings); + }); + it("passes the route workspace id to the GitLab integration page", () => { expect(gitLabRouteWorkspaceId("/settings/workspace/ws-2/integrations/gitlab")).toBe("ws-2"); expect(gitLabRouteWorkspaceId("/settings/workspace/ws%202/integrations/gitlab")).toBe("ws 2"); diff --git a/apps/web/src/settings-routes.tsx b/apps/web/src/settings-routes.tsx index babf2c0814..22f38c0fc3 100644 --- a/apps/web/src/settings-routes.tsx +++ b/apps/web/src/settings-routes.tsx @@ -33,6 +33,7 @@ import { AppearanceSettings, GeneralSettings, KeyboardShortcutsSettings, + TaskActionsSettings, } from "@/components/settings/general-settings"; import { NotificationsSettings } from "@/components/settings/notifications-settings"; import { PromptsSettings } from "@/components/settings/prompts-settings"; @@ -126,6 +127,7 @@ const SETTINGS_ROUTES: Record = { "/settings/general/secrets": () => , "/settings/general/shell": () => , "/settings/general/sprites": () => , + "/settings/general/task-actions": () => , "/settings/general/terminal": () => , "/settings/workspace": () => , "/settings/agents": () => , diff --git a/docs/plans/archive-confirmation-preference/plan.md b/docs/plans/archive-confirmation-preference/plan.md new file mode 100644 index 0000000000..cd4f073a9d --- /dev/null +++ b/docs/plans/archive-confirmation-preference/plan.md @@ -0,0 +1,60 @@ +--- +spec: docs/specs/tasks/archive-confirmation.md +created: 2026-07-15 +status: completed +--- + +# Implementation Plan: Archive Confirmation Preference + +## Overview + +Extend the existing per-user JSON settings contract with a default-true archive confirmation preference. Hydrate it into frontend state, expose an optimistic General settings toggle, and let the shared archive dialog execute immediately with cascade disabled when confirmation is off so every current archive surface inherits the behavior. + +## Backend + +- Add `ConfirmTaskArchive bool` to the user settings model and DTO plus `*bool` PATCH fields in `apps/backend/internal/user/dto/dto.go` and `apps/backend/internal/user/service/service.go`. +- Preserve missing-field compatibility in `apps/backend/internal/user/store/sqlite.go` by decoding the stored JSON field through a pointer and defaulting it to `true`. +- Include `confirm_task_archive` in stored JSON, user settings events, and the Go boot-payload mapping. +- Cover defaulting, explicit false persistence, patch application, and DTO mapping with focused Go tests. + +## Frontend + +- Add `confirm_task_archive` to HTTP/WS types and `confirmTaskArchive` to the settings slice, boot/SSR mapping, and WS update handler, defaulting missing values to `true`. +- Add a **Confirm before archiving tasks** switch to a dedicated Task Actions section under General settings, with optimistic persistence and rollback on failure. +- Update `TaskArchiveConfirmDialog` to read the preference. On an open transition while confirmation is disabled, invoke `onConfirm({ cascade: false })`, close the controlled state, and render no dialog content. + +## Tests + +- **Default true and explicit false:** `apps/backend/internal/user/store/sqlite_test.go`, `apps/backend/internal/user/service/service_test.go`, and `apps/backend/internal/user/dto/dto_test.go`. +- **Frontend mapping and live updates:** `apps/web/lib/ssr/user-settings.test.ts` and `apps/web/lib/ws/handlers/users.test.ts`. +- **Dialog behavior:** `apps/web/components/task/task-archive-confirm-dialog.test.tsx` verifies enabled confirmation and confirmation-free single execution with `cascade: false`. +- **Settings rollback:** `apps/web/components/settings/archive-confirmation-settings.test.tsx` verifies optimistic update, persistence payload, disabled state, and rollback. + +## E2E Tests + +- Desktop: disable confirmation, archive from the sidebar, assert no alert dialog and task removal. +- Mobile: disable confirmation, archive through the mobile task switcher, assert no alert dialog and task removal. +- Use the existing production-build E2E fixtures and user-settings reset path. + +## Implementation Waves + +1. [x] [task-01-backend-preference](task-01-backend-preference.md) +2. [x] [task-02-frontend-behavior](task-02-frontend-behavior.md) +3. [x] [task-03-e2e-and-verification](task-03-e2e-and-verification.md) + +## Verification + +```bash +make -C apps/backend fmt +rtk go test ./internal/user/... ./internal/backendapp/... +cd apps && pnpm --filter @kandev/web test -- --run lib/ssr/user-settings.test.ts lib/ws/handlers/users.test.ts components/task/task-archive-confirm-dialog.test.tsx components/settings/archive-confirmation-settings.test.tsx +cd apps/web && pnpm e2e:run tests/task/archive-confirmation-preference.spec.ts +cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/task/mobile-archive-confirmation-preference.spec.ts +make -C apps/backend lint +cd apps/web && pnpm run typecheck && pnpm run lint +``` + +## Risks + +- React Strict Mode can replay effects, so the confirmation bypass must guard one archive execution per open transition. +- Existing user rows omit the new boolean; both backend JSON decoding and frontend fallback must fail safely to confirmation enabled. diff --git a/docs/plans/archive-confirmation-preference/task-01-backend-preference.md b/docs/plans/archive-confirmation-preference/task-01-backend-preference.md new file mode 100644 index 0000000000..8986b6ffce --- /dev/null +++ b/docs/plans/archive-confirmation-preference/task-01-backend-preference.md @@ -0,0 +1,39 @@ +--- +id: "01-backend-preference" +title: "Backend archive confirmation preference" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/tasks/archive-confirmation.md" +--- + +# Task 01: Backend Archive Confirmation Preference + +## Acceptance + +- The user settings GET, PATCH, boot payload, and WebSocket event expose `confirm_task_archive`. +- Missing stored values resolve to `true`; explicit `false` values persist and round-trip. + +## Verification + +`rtk go test ./internal/user/... ./internal/backendapp/...` + +## Files Likely Touched + +- `apps/backend/internal/user/models/models.go` +- `apps/backend/internal/user/dto/dto.go` +- `apps/backend/internal/user/controller/controller.go` +- `apps/backend/internal/user/service/service.go` +- `apps/backend/internal/user/store/sqlite.go` +- `apps/backend/internal/user/**/*_test.go` +- `apps/backend/internal/backendapp/boot_state_routes.go` +- `apps/backend/internal/backendapp/helpers_test.go` + +## Inputs + +Spec sections: Data model, API surface, Persistence guarantees, and default-enabled scenario. Follow the existing `show_release_notification` default-true pattern. + +## Output Contract + +Report contract/defaulting changes, tests run, files touched, blockers, and risks; mark this task and the plan entry done. diff --git a/docs/plans/archive-confirmation-preference/task-02-frontend-behavior.md b/docs/plans/archive-confirmation-preference/task-02-frontend-behavior.md new file mode 100644 index 0000000000..ea18bbb066 --- /dev/null +++ b/docs/plans/archive-confirmation-preference/task-02-frontend-behavior.md @@ -0,0 +1,41 @@ +--- +id: "02-frontend-behavior" +title: "Frontend archive confirmation behavior" +status: done +wave: 2 +depends_on: ["01-backend-preference"] +plan: "plan.md" +spec: "../../specs/tasks/archive-confirmation.md" +--- + +# Task 02: Frontend Archive Confirmation Behavior + +## Acceptance + +- General settings exposes a default-enabled archive confirmation switch with optimistic save and rollback. +- All UI archive surfaces continue to confirm while enabled and immediately archive with `cascade: false` while disabled. +- Missing boot/API/WS values resolve to confirmation enabled. + +## Verification + +`cd apps && pnpm --filter @kandev/web test -- --run lib/ssr/user-settings.test.ts lib/ws/handlers/users.test.ts components/task/task-archive-confirm-dialog.test.tsx components/settings/general-settings.test.tsx` + +## Files Likely Touched + +- `apps/web/lib/types/http-user-settings.ts` +- `apps/web/lib/types/backend.ts` +- `apps/web/lib/state/slices/settings/types.ts` +- `apps/web/lib/state/slices/settings/settings-slice.ts` +- `apps/web/lib/ssr/user-settings.ts` +- `apps/web/lib/ws/handlers/users.ts` +- `apps/web/components/settings/general-settings.tsx` +- `apps/web/components/task/task-archive-confirm-dialog.tsx` +- Nearby focused tests. + +## Inputs + +Backend task 01 contract; spec What, Failure modes, and Scenarios. Reuse the optimistic switch pattern from changelog and notification settings. + +## Output Contract + +Report state/UI/dialog behavior, tests run, files touched, blockers, and risks; mark this task and the plan entry done. diff --git a/docs/plans/archive-confirmation-preference/task-03-e2e-and-verification.md b/docs/plans/archive-confirmation-preference/task-03-e2e-and-verification.md new file mode 100644 index 0000000000..f5e1546da9 --- /dev/null +++ b/docs/plans/archive-confirmation-preference/task-03-e2e-and-verification.md @@ -0,0 +1,42 @@ +--- +id: "03-e2e-and-verification" +title: "Archive preference E2E and verification" +status: done +wave: 3 +depends_on: ["02-frontend-behavior"] +plan: "plan.md" +spec: "../../specs/tasks/archive-confirmation.md" +--- + +# Task 03: Archive Preference E2E and Verification + +## Acceptance + +- Desktop and mobile Playwright coverage prove confirmation-free archive from reachable archive controls. +- Focused tests, backend formatting/lint, frontend typecheck/lint, and relevant builds pass. +- The spec and plan statuses match the shipped implementation. + +## Verification + +```bash +cd apps/web && pnpm e2e:run tests/task/archive-confirmation-preference.spec.ts +cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/task/mobile-archive-confirmation-preference.spec.ts +make -C apps/backend fmt +make -C apps/backend lint +cd apps/web && pnpm run typecheck && pnpm run lint +``` + +## Files Likely Touched + +- `apps/web/e2e/tests/task/archive-confirmation-preference.spec.ts` +- `apps/web/e2e/tests/task/mobile-archive-confirmation-preference.spec.ts` +- `docs/specs/tasks/archive-confirmation.md` +- `docs/plans/archive-confirmation-preference/*.md` + +## Inputs + +Completed backend/frontend tasks, mobile-parity skill, existing sidebar and mobile task switcher page objects. + +## Output Contract + +Report desktop/mobile behavior exercised, commands and results, files touched, blockers, residual risks, and final spec/plan status. diff --git a/docs/specs/INDEX.md b/docs/specs/INDEX.md index 90b90ae487..4bfbca3f2a 100644 --- a/docs/specs/INDEX.md +++ b/docs/specs/INDEX.md @@ -47,6 +47,7 @@ Kandev's task model: documents, execution stages, labels, blocker escalation, su | [subtree-controls](tasks/subtree-controls.md) | shipped | | [blocked-task-escalation](tasks/blocked-task-escalation.md) | draft | | [runtime-cleanup](tasks/runtime-cleanup.md) | draft | +| [archive-confirmation](tasks/archive-confirmation.md) | shipped | | [link-existing-task-github-issue](tasks/link-existing-task-github-issue.md) | building | | [wip-limit-pull-system](tasks/wip-limit-pull-system.md) | building | | [multi-branch](tasks/multi-branch/spec.md) | shipped | diff --git a/docs/specs/tasks/archive-confirmation.md b/docs/specs/tasks/archive-confirmation.md new file mode 100644 index 0000000000..bee3f2d6d8 --- /dev/null +++ b/docs/specs/tasks/archive-confirmation.md @@ -0,0 +1,62 @@ +--- +status: shipped +created: 2026-07-15 +owner: kandev +--- + +# Task Archive Confirmation + +## Why + +Frequent task archiving makes a mandatory confirmation dialog costly for users who understand the cleanup consequences. Users need to choose whether archive actions require explicit confirmation while retaining the safer confirmed behavior by default. + +## What + +- A user-level setting named **Confirm before archiving tasks** controls whether user-initiated archive actions require the archive confirmation dialog. +- The setting is enabled by default for new users and for existing users whose saved settings predate the preference. +- When enabled, archive actions continue to show the existing cleanup summary and optional subtask cascade control before archiving. +- When disabled, archive actions from every UI surface archive immediately without rendering the confirmation dialog. +- Confirmation-free archive actions do not cascade to subtasks. Users who need to archive subtasks together can temporarily enable confirmation and use the existing cascade control. +- Delete confirmations and programmatic archive operations are unaffected. + +## Data model + +`users.settings` stores `confirm_task_archive` as a boolean in the existing per-user JSON settings blob. A missing field is interpreted as `true` for backward compatibility. + +## API surface + +The existing user settings endpoints carry the preference: + +- `GET /api/v1/user/settings`: `settings.confirm_task_archive: boolean` +- `PATCH /api/v1/user/settings`: optional `confirm_task_archive: boolean` +- `user.settings.updated` WebSocket payload: `confirm_task_archive: boolean` + +No archive endpoint contract changes. + +## Failure modes + +- If saving the preference fails, the settings control returns to its previous value and archive behavior remains unchanged. +- If user settings have not loaded or omit the field, the client requires confirmation. +- Archive API failures continue to use each archive surface's existing error handling. + +## Persistence guarantees + +The preference survives backend and client restarts as part of the existing user settings record. It applies across workspaces for the current user. + +## Scenarios + +- **GIVEN** a new or upgraded user has not changed the preference, **WHEN** they request an archive from any UI surface, **THEN** the archive confirmation dialog is shown. +- **GIVEN** confirmation is enabled, **WHEN** the user cancels the archive dialog, **THEN** the task remains active. +- **GIVEN** confirmation is disabled, **WHEN** the user requests an archive from the sidebar, task banner, task card, list, pipeline, mobile task switcher, or bulk action, **THEN** the archive starts immediately and no archive confirmation dialog appears. +- **GIVEN** confirmation is disabled and a task has active subtasks, **WHEN** the user archives the task, **THEN** the parent is archived with cascade disabled and the subtasks remain active. +- **GIVEN** saving the preference fails, **WHEN** the request completes, **THEN** the control and archive behavior revert to the previously persisted value. + +## Out of scope + +- Disabling confirmation for task deletion or other destructive actions. +- Adding a per-archive cascade default when confirmation is disabled. +- Changing API, CLI, MCP, automation, or agent-driven archive behavior. + +## Implementation plan + +- [Archive Confirmation Preference](../../plans/archive-confirmation-preference/plan.md)