feat: add archive confirmation preference (#1708)

This commit is contained in:
Carlos Florêncio
2026-07-15 19:34:18 +01:00
committed by GitHub
parent 2fe91cbab8
commit af6756bbbc
40 changed files with 883 additions and 14 deletions
@@ -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),
@@ -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"])
}
}
@@ -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,
+3
View File
@@ -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,
@@ -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
@@ -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"`
@@ -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,
@@ -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 {
@@ -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 {
@@ -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 {
@@ -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(
<StateProvider
initialState={{
userSettings: { ...defaultState.userSettings, confirmTaskArchive },
}}
>
<ArchiveConfirmationSettings />
{children}
</StateProvider>,
);
}
function RemoteSettingsUpdate() {
const settings = useAppStore((state) => state.userSettings);
const setUserSettings = useAppStore((state) => state.setUserSettings);
return (
<button
type="button"
onClick={() =>
setUserSettings({ ...settings, workspaceId: "workspace-2", confirmTaskArchive: false })
}
>
Apply remote settings
</button>
);
}
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, <RemoteSettingsUpdate />);
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));
});
});
@@ -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 (
<Card>
<CardHeader>
<CardTitle className="text-base">Archive Confirmation</CardTitle>
</CardHeader>
<CardContent>
<div className="flex min-h-11 items-center justify-between gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="confirm-task-archive">Confirm before archiving tasks</Label>
<p className="text-xs text-muted-foreground">
Show cleanup details and subtask options before an archive starts.
</p>
</div>
<Switch
id="confirm-task-archive"
checked={confirmTaskArchive}
onCheckedChange={handleToggle}
disabled={isSaving}
className="shrink-0 cursor-pointer"
/>
</div>
</CardContent>
</Card>
);
}
@@ -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 ?? [],
+14 -1
View File
@@ -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,
},
];
@@ -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 (
<div className="space-y-8">
<SettingsSection
icon={<IconArchive className="h-5 w-5" />}
title="Task Actions"
description="Configure safeguards for task actions"
>
<ArchiveConfirmationSettings />
</SettingsSection>
</div>
);
}
export function AppearanceSettings() {
return (
<div className="space-y-8">
@@ -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,
@@ -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(
<StateProvider
initialState={{
userSettings: { ...defaultState.userSettings, confirmTaskArchive },
}}
>
{ui}
</StateProvider>,
);
}
function DisableArchiveConfirmationButton() {
const settings = useAppStore((state) => state.userSettings);
const setUserSettings = useAppStore((state) => state.setUserSettings);
return (
<button
type="button"
onClick={() => setUserSettings({ ...settings, confirmTaskArchive: false })}
>
Disable archive confirmation
</button>
);
}
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(
<StrictMode>
<TaskArchiveConfirmDialog
open
onOpenChange={onOpenChange}
taskTitle="My task"
taskId="task-1"
executorType="worktree"
onConfirm={onConfirm}
/>
</StrictMode>,
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(
<>
<DisableArchiveConfirmationButton />
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
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(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -32,7 +111,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => {
});
it("renders worktree-executor copy about worktree + branch removal", () => {
render(
renderDialog(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -46,7 +125,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => {
});
it("warns about sandbox destruction for sprites executor", () => {
render(
renderDialog(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -61,7 +140,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => {
});
it("describes Docker container removal for local_docker", () => {
render(
renderDialog(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -75,7 +154,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => {
});
it("renders grouped copy for bulk archive", () => {
render(
renderDialog(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -91,7 +170,7 @@ describe("TaskArchiveConfirmDialog cleanup copy", () => {
});
it("no longer renders the old hardcoded worktree line for non-worktree executors", () => {
render(
renderDialog(
<TaskArchiveConfirmDialog
open
onOpenChange={() => {}}
@@ -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<ArchiveOpenMode>("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 (
<AlertDialog open={open} onOpenChange={handleOpenChange}>
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
+2
View File
@@ -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: "",
});
+1
View File
@@ -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[];
@@ -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,
});
});
});
@@ -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 });
});
});
@@ -58,6 +58,7 @@ function makeUnloadedSettings(): UserSettingsState {
enablePreviewOnClick: false,
chatSubmitKey: "cmd_enter",
reviewAutoMarkOnScroll: true,
confirmTaskArchive: true,
showReleaseNotification: true,
releaseNotesLastSeenVersion: null,
savedLayouts: [],
@@ -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),
+23 -3
View File
@@ -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<typeof buildCoreFields>[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<typeof buildCoreFields>[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,
},
});
+2
View File
@@ -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[],
@@ -35,6 +35,7 @@ export const defaultSettingsState: SettingsSliceState = {
terminalLinkBehavior: "new_tab",
chatSubmitKey: "cmd_enter",
reviewAutoMarkOnScroll: true,
confirmTaskArchive: true,
showReleaseNotification: true,
releaseNotesLastSeenVersion: null,
lspAutoStartLanguages: [],
@@ -152,6 +152,7 @@ export type UserSettingsState = {
enablePreviewOnClick: boolean;
chatSubmitKey: "enter" | "cmd_enter";
reviewAutoMarkOnScroll: boolean;
confirmTaskArchive: boolean;
showReleaseNotification: boolean;
releaseNotesLastSeenVersion: string | null;
lspAutoStartLanguages: string[];
+1
View File
@@ -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[];
+2
View File
@@ -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[];
+12
View File
@@ -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) => ({
+1
View File
@@ -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:
+7
View File
@@ -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");
+2
View File
@@ -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<string, RouteRenderer> = {
"/settings/general/secrets": () => <SecretsSettings />,
"/settings/general/shell": () => <SettingsRedirect to="/settings/general/terminal" />,
"/settings/general/sprites": () => <SpritesSettings />,
"/settings/general/task-actions": () => <TaskActionsSettings />,
"/settings/general/terminal": () => <TerminalSettings />,
"/settings/workspace": () => <WorkspacesPage />,
"/settings/agents": () => <AgentsSettingsPage />,
@@ -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.
@@ -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.
@@ -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.
@@ -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.
+1
View File
@@ -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 |
+62
View File
@@ -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)