Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(saved-views): per-user filter presets on Alerts + Cases (WS-F3)
Beenu Arora5e5f61f2e710
diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsxindex 3f62cdf8c..547950857 100644--- a/apps/web/src/components/alerts/AlertsView.tsx+++ b/apps/web/src/components/alerts/AlertsView.tsx@@ -10,6 +10,7 @@ import { formatDistanceToNow } from 'date-fns';import { EntityRiskQueue } from './EntityRiskQueue';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { ErrorState } from '@/components/ui/ErrorState';+import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';// Wave 1 of the AiSOC v6 capability roadmap. The "entities" tab renders the// rolled-up Risk-Based Alerting queue — alerts contribute time-decayed risk@@ -365,6 +366,24 @@ function AlertsTable({))}</div>+ {/*+ WS-F3 — saved views. The bar reads/writes filters straight through+ ``onFilterChange`` so we don't need a parallel state path. We reset+ ``page`` to 1 when applying a preset because saved pagination would+ be confusing — analysts expect to start from the top.+ */}+ <SavedViewsBar<AlertFilters>+ viewType="alerts"+ filters={filters}+ onApply={(applied) =>+ onFilterChange({+ ...applied,+ page: 1,+ pageSize: filters.pageSize ?? 25,+ })+ }+ />+<FiltersBar filters={filters} onChange={onFilterChange} total={total} />{/* Table */}diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsxindex 9de121f0b..08ed9b4f9 100644--- a/apps/web/src/components/cases/CasesView.tsx+++ b/apps/web/src/components/cases/CasesView.tsx@@ -8,6 +8,17 @@ import { casesApi, type Case, type CasesResponse } from '@/lib/api';import { clsx } from 'clsx';import { format } from 'date-fns';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';+import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';++// WS-F3 — the saved-views API stores an opaque filter blob per view, so we+// flatten the three filter slices Cases tracks today into a single shape the+// bar can snapshot and replay. Nothing else in the view consumes this — it's+// purely the wire format between the bar and the local state setters.+type CaseFilterSnapshot = {+ status: Case['status'] | 'all';+ severity: Case['severity'] | 'all';+ search: string;+};// ─── Mock Data ────────────────────────────────────────────────────────────────@@ -212,6 +223,26 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {})}</div>+ {/*+ WS-F3 — saved views. Cases keeps three slices of filter state, so we+ synthesize a single object for the bar and unpack it on apply. We+ spread defaults to be defensive against older saved-view payloads+ that might be missing newer keys.+ */}+ <SavedViewsBar<CaseFilterSnapshot>+ viewType="cases"+ filters={{+ status: statusFilter,+ severity: severityFilter,+ search,+ }}+ onApply={(applied) => {+ setStatusFilter(applied.status ?? 'all');+ setSeverityFilter(applied.severity ?? 'all');+ setSearch(applied.search ?? '');+ }}+ />+{/* Filters */}<div className="flex items-center gap-3"><div className="relative flex-1 max-w-sm">diff --git a/apps/web/src/components/saved-views/SavedViewsBar.test.tsx b/apps/web/src/components/saved-views/SavedViewsBar.test.tsxnew file mode 100644index 000000000..734c3ed6b--- /dev/null+++ b/apps/web/src/components/saved-views/SavedViewsBar.test.tsx@@ -0,0 +1,290 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++// WS-F3 — pin the SavedViewsBar wiring. We care about four behaviors the+// downstream pages actually rely on:+// 1. Load + render existing presets, with a star on the default one.+// 2. Auto-apply the default exactly once on first render (so coming back+// to a page restores the analyst's preferred filters), without firing+// again on stale SWR revalidations.+// 3. Save the *current* filters when the analyst hits "Save current view"+// with the typed name + default checkbox.+// 4. Surface 409 conflicts (duplicate names) as a friendly error toast,+// not a stack trace.+//+// We keep the SWR + savedViewsApi + toast mocks lightweight so the test+// stays under jsdom budget; nothing here renders the actual list view, just+// the bar.++const swrCalls = vi.hoisted(() => new Map<string, unknown>());+const swrErrors = vi.hoisted(() => new Map<string, unknown>());+vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ // Cache key is `['saved-views', viewType]` for the bar.+ const k = Array.isArray(key) ? key.join(':') : String(key);+ return {+ data: swrCalls.get(k),+ error: swrErrors.get(k),+ isLoading: !swrCalls.has(k) && !swrErrors.has(k),+ mutate: vi.fn(async () => undefined),+ };+ },+}));++const listMock = vi.hoisted(() => vi.fn());+const createMock = vi.hoisted(() => vi.fn());+const updateMock = vi.hoisted(() => vi.fn());+const deleteMock = vi.hoisted(() => vi.fn());+vi.mock('@/lib/api', () => ({+ __esModule: true,+ ApiError: class ApiError extends Error {+ status: number;+ body: string;+ constructor(message: string, status = 0, body = '') {+ super(message);+ this.name = 'ApiError';+ this.status = status;+ this.body = body;+ }+ },+ savedViewsApi: {+ list: listMock,+ create: createMock,+ update: updateMock,+ delete: deleteMock,+ },+}));++const toastSuccess = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());+vi.mock('react-hot-toast', () => ({+ __esModule: true,+ default: { success: toastSuccess, error: toastError },+}));++import { SavedViewsBar } from './SavedViewsBar';+import { ApiError } from '@/lib/api';++interface TestFilters extends Record<string, unknown> {+ status?: string;+ q?: string;+}++function seedViews(viewType: string, items: unknown[]) {+ swrCalls.set(`saved-views:${viewType}`, items);+}++function makeView(overrides: Record<string, unknown> = {}) {+ return {+ id: 'v-1',+ tenant_id: 't-1',+ user_id: 'u-1',+ view_type: 'alerts',+ name: 'High severity',+ filters: { status: 'open', q: 'critical' },+ columns: null,+ is_default: false,+ created_at: '2026-05-01T10:00:00Z',+ updated_at: '2026-05-01T10:00:00Z',+ ...overrides,+ };+}++describe('SavedViewsBar', () => {+ beforeEach(() => {+ swrCalls.clear();+ swrErrors.clear();+ listMock.mockReset();+ createMock.mockReset();+ updateMock.mockReset();+ deleteMock.mockReset();+ toastSuccess.mockReset();+ toastError.mockReset();+ });++ it('renders existing views with a star on the default one', () => {+ seedViews('alerts', [+ makeView({ id: 'v-1', name: 'Open critical', is_default: true }),+ makeView({ id: 'v-2', name: 'My queue', is_default: false }),+ ]);+ const onApply = vi.fn();++ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{ status: 'open' }}+ onApply={onApply}+ />,+ );++ // Both chips render.+ expect(screen.getByTestId('saved-view-chip-v-1')).toHaveTextContent(+ 'Open critical',+ );+ expect(screen.getByTestId('saved-view-chip-v-2')).toHaveTextContent(+ 'My queue',+ );+ // The default chip surfaces the ★ glyph.+ expect(+ screen.getByTestId('saved-view-chip-v-1').textContent,+ ).toContain('★');+ expect(+ screen.getByTestId('saved-view-chip-v-2').textContent,+ ).not.toContain('★');+ });++ it('auto-applies the default view exactly once on mount', async () => {+ const defaultFilters = { status: 'open', q: 'critical' };+ seedViews('alerts', [+ makeView({ id: 'v-1', name: 'Open critical', is_default: true, filters: defaultFilters }),+ makeView({ id: 'v-2', name: 'My queue' }),+ ]);+ const onApply = vi.fn();+ const onDefaultLoaded = vi.fn();++ const { rerender } = render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{}}+ onApply={onApply}+ onDefaultLoaded={onDefaultLoaded}+ />,+ );++ await waitFor(() => {+ expect(onApply).toHaveBeenCalledWith(defaultFilters);+ });+ expect(onDefaultLoaded).toHaveBeenCalledTimes(1);++ // Re-render with the same SWR data — must not re-apply, since otherwise+ // we'd clobber filters the analyst has tweaked since mount.+ rerender(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{ status: 'closed' }}+ onApply={onApply}+ onDefaultLoaded={onDefaultLoaded}+ />,+ );+ expect(onApply).toHaveBeenCalledTimes(1);+ expect(onDefaultLoaded).toHaveBeenCalledTimes(1);+ });++ it('does not auto-apply when no default view exists', () => {+ seedViews('alerts', [makeView({ id: 'v-2', is_default: false })]);+ const onApply = vi.fn();++ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{}}+ onApply={onApply}+ />,+ );++ expect(onApply).not.toHaveBeenCalled();+ });++ it('saves the current filters with the typed name', async () => {+ seedViews('alerts', []);+ createMock.mockResolvedValue(makeView({ id: 'v-new', name: 'My filter' }));+ const user = userEvent.setup();++ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{ status: 'open', q: 'phish' }}+ onApply={vi.fn()}+ />,+ );++ await user.click(screen.getByTestId('save-current-view-btn'));+ const input = screen.getByLabelText('New saved view name');+ await user.type(input, 'My filter');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => {+ expect(createMock).toHaveBeenCalledWith({+ view_type: 'alerts',+ name: 'My filter',+ filters: { status: 'open', q: 'phish' },+ is_default: false,+ });+ });+ expect(toastSuccess).toHaveBeenCalled();+ });++ it('surfaces 409 conflicts as a friendly error toast', async () => {+ seedViews('alerts', []);+ createMock.mockRejectedValue(new ApiError('Conflict', 409, ''));+ const user = userEvent.setup();++ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{ status: 'open' }}+ onApply={vi.fn()}+ />,+ );++ await user.click(screen.getByTestId('save-current-view-btn'));+ await user.type(screen.getByLabelText('New saved view name'), 'Dup');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ 'A view named "Dup" already exists',+ );+ });+ expect(toastSuccess).not.toHaveBeenCalled();+ });++ it('emits onApply with the preset filters when a chip is clicked', async () => {+ const presetFilters = { status: 'closed', q: 'apt' };+ seedViews('alerts', [+ makeView({ id: 'v-1', name: 'My queue', filters: presetFilters }),+ ]);+ const onApply = vi.fn();+ const user = userEvent.setup();++ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{ status: 'open' }}+ onApply={onApply}+ />,+ );++ await user.click(screen.getByTestId('saved-view-chip-v-1'));+ expect(onApply).toHaveBeenCalledWith(presetFilters);+ });++ it('hides the save affordance in read-only mode', () => {+ seedViews('alerts', [makeView()]);+ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{}}+ onApply={vi.fn()}+ readOnly+ />,+ );+ expect(screen.queryByTestId('save-current-view-btn')).toBeNull();+ });++ it('shows an empty-state nudge when no views exist yet', () => {+ seedViews('alerts', []);+ render(+ <SavedViewsBar<TestFilters>+ viewType="alerts"+ filters={{}}+ onApply={vi.fn()}+ />,+ );+ expect(+ screen.getByText(/save your current filters to come back to them/i),+ ).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/saved-views/SavedViewsBar.tsx b/apps/web/src/components/saved-views/SavedViewsBar.tsxnew file mode 100644index 000000000..4d166c3cf--- /dev/null+++ b/apps/web/src/components/saved-views/SavedViewsBar.tsx@@ -0,0 +1,452 @@+'use client';++/**+ * Workstream F3 — saved-views toolbar.+ *+ * A generic, page-agnostic bar that hangs above any list view. Reads the+ * current filter shape via the parent's ``filters`` prop, persists it to the+ * backend as a named preset, and emits the loaded preset's filters back via+ * ``onApply`` when the analyst clicks on one.+ *+ * Why generic? The ``filters`` blob the backend stores is opaque+ * ``Record<string, unknown>``. Each list page (alerts, cases, investigations,+ * playbooks) owns its own filter shape — Alerts uses ``AlertFilters``, Cases+ * uses ``CaseFilters``, etc. Forcing one shared interface across all of them+ * would be a coordination tax for zero benefit. So the bar accepts a generic+ * ``T`` and the caller casts on the way in/out.+ *+ * What it does NOT do:+ * - Save column overrides. Column ordering/visibility lives at the page+ * level today; the backend already accepts a ``columns`` field, so a+ * follow-up can layer this in without re-shaping the API.+ * - Sync filters into the URL. That's a separate feature (deep-linkable+ * views) and would deserve its own controller.+ */++import { useCallback, useState } from 'react';+import useSWR from 'swr';+import toast from 'react-hot-toast';+import { clsx } from 'clsx';+import {+ savedViewsApi,+ type SavedView,+ type SavedViewType,+ ApiError,+} from '@/lib/api';++// Why ``object`` instead of ``Record<string, unknown>``? TypeScript does not+// infer an index signature for declared interfaces (e.g. ``AlertFilters``), so+// constraining the generic to ``Record<string, unknown>`` fails at every call+// site that passes a typed filter shape. ``object`` is permissive enough to+// keep the API ergonomic, and the cast on the way out (``as TFilters``) keeps+// the contract honest at the boundary.+interface SavedViewsBarProps<TFilters extends object> {+ /** Which list page we're attached to. Drives the backend allowlist. */+ viewType: SavedViewType;+ /**+ * The page's *current* filters. We snapshot this when the analyst clicks+ * "Save current view…" so callers don't need to pass anything extra.+ */+ filters: TFilters;+ /**+ * Apply a preset's filters to the page. The page is responsible for+ * resetting pagination, etc. — this hook just hands the blob over.+ */+ onApply: (filters: TFilters) => void;+ /**+ * Optional: notify the page when a default-loaded view fires on first+ * mount, so it can avoid double-applying or fire analytics.+ */+ onDefaultLoaded?: (view: SavedView) => void;+ /** Hide the "Save current view" affordance, e.g. in read-only demos. */+ readOnly?: boolean;+}++export function SavedViewsBar<TFilters extends object>({+ viewType,+ filters,+ onApply,+ onDefaultLoaded,+ readOnly = false,+}: SavedViewsBarProps<TFilters>) {+ // Each page key is unique so multiple bars on the same screen wouldn't+ // collide — defensive, today the bar is singleton-per-page.+ const cacheKey = ['saved-views', viewType] as const;+ const {+ data: views = [],+ error,+ isLoading,+ mutate,+ } = useSWR(cacheKey, () => savedViewsApi.list(viewType), {+ // Saved views change rarely; aggressive revalidation just adds noise.+ revalidateOnFocus: false,+ });++ // Track which preset is currently "active" so the chip can light up. We+ // identify by id rather than deep-comparing filters (which would be+ // brittle once columns join the picture).+ const [activeViewId, setActiveViewId] = useState<string | null>(null);+ const [openMenuId, setOpenMenuId] = useState<string | null>(null);+ const [isSaveDialogOpen, setSaveDialogOpen] = useState(false);+ const [renamingViewId, setRenamingViewId] = useState<string | null>(null);++ // Auto-apply the default view on first load. We use a ref-flag instead of+ // a useEffect dependency on ``views`` because we only ever want to fire+ // once per mount; subsequent SWR revalidations shouldn't re-clobber the+ // analyst's current filters.+ const [defaultApplied, setDefaultApplied] = useState(false);+ if (!defaultApplied && !isLoading && views.length > 0) {+ const def = views.find((v) => v.is_default);+ if (def) {+ setDefaultApplied(true);+ setActiveViewId(def.id);+ onApply(def.filters as TFilters);+ onDefaultLoaded?.(def);+ } else {+ setDefaultApplied(true);+ }+ }++ const apply = useCallback(+ (view: SavedView) => {+ setActiveViewId(view.id);+ setOpenMenuId(null);+ onApply(view.filters as TFilters);+ },+ [onApply],+ );++ const handleCreate = useCallback(+ async (name: string, makeDefault: boolean) => {+ try {+ const created = await savedViewsApi.create({+ view_type: viewType,+ name,+ filters: filters as Record<string, unknown>,+ is_default: makeDefault,+ });+ await mutate();+ setActiveViewId(created.id);+ toast.success(`Saved view "${created.name}"`);+ setSaveDialogOpen(false);+ } catch (err) {+ const message =+ err instanceof ApiError && err.status === 409+ ? `A view named "${name}" already exists`+ : err instanceof Error+ ? err.message+ : 'Failed to save view';+ toast.error(message);+ }+ },+ [filters, mutate, viewType],+ );++ const handleRename = useCallback(+ async (id: string, name: string) => {+ try {+ await savedViewsApi.update(id, { name });+ await mutate();+ toast.success('Renamed');+ setRenamingViewId(null);+ } catch (err) {+ const message =+ err instanceof ApiError && err.status === 409+ ? `A view named "${name}" already exists`+ : err instanceof Error+ ? err.message+ : 'Rename failed';+ toast.error(message);+ }+ },+ [mutate],+ );++ const handleSetDefault = useCallback(+ async (view: SavedView) => {+ const next = !view.is_default;+ try {+ await savedViewsApi.update(view.id, { is_default: next });+ await mutate();+ toast.success(next ? 'Set as default' : 'Default cleared');+ setOpenMenuId(null);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Update failed');+ }+ },+ [mutate],+ );++ const handleOverwrite = useCallback(+ async (view: SavedView) => {+ try {+ await savedViewsApi.update(view.id, {+ filters: filters as Record<string, unknown>,+ });+ await mutate();+ setActiveViewId(view.id);+ toast.success(`Updated "${view.name}"`);+ setOpenMenuId(null);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Update failed');+ }+ },+ [filters, mutate],+ );++ const handleDelete = useCallback(+ async (view: SavedView) => {+ // No confirm() prompt — analysts have a 'recently deleted' fallback+ // already by re-saving the current filters. Keeps the workflow snappy.+ try {+ await savedViewsApi.delete(view.id);+ await mutate();+ if (activeViewId === view.id) setActiveViewId(null);+ setOpenMenuId(null);+ toast.success(`Deleted "${view.name}"`);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Delete failed');+ }+ },+ [activeViewId, mutate],+ );++ return (+ <div+ className="flex items-center gap-2 flex-wrap py-2 px-3 bg-gray-900/40 border border-gray-800/60 rounded-xl"+ data-testid="saved-views-bar"+ >+ <span className="text-xs text-gray-500 mr-1 shrink-0">Saved views</span>++ {error && (+ <span className="text-xs text-red-400">Failed to load saved views</span>+ )}++ {!error && views.length === 0 && !isLoading && (+ <span className="text-xs text-gray-600 italic">+ None yet — save your current filters to come back to them later.+ </span>+ )}++ {views.map((view) => (+ <div key={view.id} className="relative inline-flex">+ {renamingViewId === view.id ? (+ <RenameInput+ initial={view.name}+ onSubmit={(name) => handleRename(view.id, name)}+ onCancel={() => setRenamingViewId(null)}+ />+ ) : (+ <button+ type="button"+ onClick={() => apply(view)}+ className={clsx(+ 'inline-flex items-center gap-1 text-xs px-2.5 py-1 rounded-l-lg transition-colors border-l border-y',+ activeViewId === view.id+ ? 'bg-blue-600 text-white border-blue-600'+ : 'text-gray-300 hover:bg-gray-800/60 border-gray-800/60',+ )}+ title={+ view.is_default+ ? `${view.name} (default)`+ : `Apply ${view.name}`+ }+ data-testid={`saved-view-chip-${view.id}`}+ >+ {view.is_default && (+ <span aria-label="default" className="text-yellow-400">★</span>+ )}+ <span className="truncate max-w-[12rem]">{view.name}</span>+ </button>+ )}+ {renamingViewId !== view.id && !readOnly && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setOpenMenuId(openMenuId === view.id ? null : view.id);+ }}+ className={clsx(+ 'inline-flex items-center text-xs px-1.5 py-1 rounded-r-lg transition-colors border-r border-y',+ activeViewId === view.id+ ? 'bg-blue-700 text-white border-blue-600'+ : 'text-gray-400 hover:bg-gray-800/60 border-gray-800/60',+ )}+ aria-label={`Actions for ${view.name}`}+ aria-haspopup="menu"+ aria-expanded={openMenuId === view.id}+ data-testid={`saved-view-menu-${view.id}`}+ >+ ⋯+ </button>+ )}++ {openMenuId === view.id && (+ <div+ role="menu"+ className="absolute z-20 top-full left-0 mt-1 w-48 bg-gray-900 border border-gray-800 rounded-lg shadow-xl py-1"+ onClick={(e) => e.stopPropagation()}+ >+ <MenuItem onClick={() => handleSetDefault(view)}>+ {view.is_default ? 'Clear default' : 'Set as default'}+ </MenuItem>+ <MenuItem+ onClick={() => {+ setRenamingViewId(view.id);+ setOpenMenuId(null);+ }}+ >+ Rename+ </MenuItem>+ <MenuItem onClick={() => handleOverwrite(view)}>+ Update with current filters+ </MenuItem>+ <MenuItem danger onClick={() => handleDelete(view)}>+ Delete+ </MenuItem>+ </div>+ )}+ </div>+ ))}++ {!readOnly && !isSaveDialogOpen && (+ <button+ type="button"+ onClick={() => setSaveDialogOpen(true)}+ className="text-xs px-2.5 py-1 rounded-lg border border-dashed border-gray-700 text-gray-400 hover:text-gray-200 hover:border-gray-500 transition-colors"+ data-testid="save-current-view-btn"+ >+ + Save current view+ </button>+ )}++ {isSaveDialogOpen && (+ <SaveViewDialog+ onSubmit={handleCreate}+ onCancel={() => setSaveDialogOpen(false)}+ />+ )}+ </div>+ );+}++function MenuItem({+ children,+ onClick,+ danger = false,+}: {+ children: React.ReactNode;+ onClick: () => void;+ danger?: boolean;+}) {+ return (+ <button+ role="menuitem"+ type="button"+ onClick={onClick}+ className={clsx(+ 'w-full text-left text-xs px-3 py-1.5 transition-colors',+ danger+ ? 'text-red-400 hover:bg-red-500/10'+ : 'text-gray-300 hover:bg-gray-800',+ )}+ >+ {children}+ </button>+ );+}++function RenameInput({+ initial,+ onSubmit,+ onCancel,+}: {+ initial: string;+ onSubmit: (name: string) => void;+ onCancel: () => void;+}) {+ const [value, setValue] = useState(initial);+ return (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const trimmed = value.trim();+ if (trimmed) onSubmit(trimmed);+ }}+ className="inline-flex items-center"+ >+ <input+ autoFocus+ type="text"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') onCancel();+ }}+ maxLength={120}+ className="text-xs px-2 py-1 rounded bg-gray-900 border border-blue-500/50 text-gray-200 focus:outline-none focus:border-blue-400 w-40"+ aria-label="Rename saved view"+ />+ </form>+ );+}++function SaveViewDialog({+ onSubmit,+ onCancel,+}: {+ onSubmit: (name: string, isDefault: boolean) => void;+ onCancel: () => void;+}) {+ const [name, setName] = useState('');+ const [isDefault, setIsDefault] = useState(false);++ return (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const trimmed = name.trim();+ if (trimmed) onSubmit(trimmed, isDefault);+ }}+ className="inline-flex items-center gap-2"+ data-testid="save-view-dialog"+ >+ <input+ autoFocus+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') onCancel();+ }}+ placeholder="View name"+ maxLength={120}+ className="text-xs px-2 py-1 rounded bg-gray-900 border border-blue-500/50 text-gray-200 focus:outline-none focus:border-blue-400 w-44"+ aria-label="New saved view name"+ />+ <label className="inline-flex items-center gap-1 text-xs text-gray-400 select-none">+ <input+ type="checkbox"+ checked={isDefault}+ onChange={(e) => setIsDefault(e.target.checked)}+ className="accent-blue-500"+ />+ Default+ </label>+ <button+ type="submit"+ disabled={!name.trim()}+ className="text-xs px-2.5 py-1 rounded-lg bg-blue-600 hover:bg-blue-500 text-white disabled:opacity-40 disabled:cursor-not-allowed"+ >+ Save+ </button>+ <button+ type="button"+ onClick={onCancel}+ className="text-xs px-2 py-1 rounded-lg text-gray-400 hover:text-gray-200"+ >+ Cancel+ </button>+ </form>+ );+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 23f366806..b4dcd1fbd 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -3667,6 +3667,91 @@ function timestampSlug(): string {);}+// ─── Saved views (per-user filter + column presets) ──────────────────────────+//+// Workstream F3 — analyst quality-of-life. Lets each user park a filter ++// column preset on a list page (alerts, cases, investigations, playbooks)+// and reload it with one click. One preset per ``(user, view_type)`` can be+// flagged ``is_default``; the UI auto-applies it on first load.+//+// The wire format mirrors ``services/api/app/api/v1/endpoints/saved_views.py``+// 1:1: opaque ``filters`` and ``columns`` blobs are owned by the page+// rendering them, so callers cast to whatever shape they need (e.g.+// ``AlertFilters`` for the alerts page) without round-tripping through this+// type. That keeps the saved-views API a *generic* preset store rather than+// a tight coupling between every list page and this client.++/** Pages that support saved views — must match the backend allowlist. */+export type SavedViewType =+ | 'alerts'+ | 'cases'+ | 'investigations'+ | 'playbooks';++/** A saved-view row as returned by the API. */+export interface SavedView {+ id: string;+ view_type: SavedViewType;+ name: string;+ /** Page-specific filter blob — opaque to this client. */+ filters: Record<string, unknown>;+ /** Optional column override. ``null`` means "use page defaults". */+ columns: unknown[] | Record<string, unknown> | null;+ is_default: boolean;+ created_at: string;+ updated_at: string;+}++/** Body for ``POST /saved-views``. */+export interface SavedViewCreateRequest {+ view_type: SavedViewType;+ name: string;+ filters?: Record<string, unknown>;+ columns?: unknown[] | Record<string, unknown> | null;+ is_default?: boolean;+}++/** Body for ``PATCH /saved-views/{id}`` — every field is optional. */+export interface SavedViewUpdateRequest {+ name?: string;+ filters?: Record<string, unknown>;+ /** Pass ``null`` to clear a previously-saved column override. */+ columns?: unknown[] | Record<string, unknown> | null;+ is_default?: boolean;+}++export const savedViewsApi = {+ /**+ * List the caller's presets for one list page. Sorted by+ * ``is_default DESC, updated_at DESC`` server-side, so the default+ * preset (if any) lands first.+ */+ list: (viewType: SavedViewType) =>+ request<SavedView[]>('/api/v1/saved-views', {+ params: { view_type: viewType },+ }),++ /** Create a new preset. Returns the freshly-stamped row. */+ create: (payload: SavedViewCreateRequest) =>+ request<SavedView>('/api/v1/saved-views', {+ method: 'POST',+ body: JSON.stringify(payload),+ }),++ /** Patch a preset in place — rename, retune filters, toggle default. */+ update: (id: string, payload: SavedViewUpdateRequest) =>+ request<SavedView>(`/api/v1/saved-views/${id}`, {+ method: 'PATCH',+ body: JSON.stringify(payload),+ }),++ /** Delete a preset. Returns ``{}`` on the 204 response. */+ delete: (id: string) =>+ request<Record<string, never>>(`/api/v1/saved-views/${id}`, {+ method: 'DELETE',+ }),+};+// ─── Realtime / WebSocket helpers ────────────────────────────────────────────export const realtimeApi = {@@ -3712,4 +3797,5 @@ export default {deployment: deploymentApi,reports: reportsApi,costs: costsApi,+ savedViews: savedViewsApi,};diff --git a/services/api/app/api/v1/endpoints/saved_views.py b/services/api/app/api/v1/endpoints/saved_views.pynew file mode 100644index 000000000..9f33401b9--- /dev/null+++ b/services/api/app/api/v1/endpoints/saved_views.py@@ -0,0 +1,466 @@+"""Per-user saved views CRUD — Workstream F3 (analyst quality-of-life).++Endpoints+---------++* ``GET /saved-views?view_type=alerts`` — list the caller's+ presets for one list page.+* ``POST /saved-views`` — create a preset.+* ``PATCH /saved-views/{id}`` — rename, retune+ filters/columns, or toggle ``is_default``.+* ``DELETE /saved-views/{id}`` — delete a preset.++Scoping+-------++Saved views are *per-user-per-tenant*: every query filters on+``tenant_id == current_user.tenant_id`` AND+``user_id == current_user.user_id``. The DB-level RLS policy in+migration 037 enforces tenant isolation as a defence-in-depth layer;+user-level scoping lives here in the API. Sharing presets across+users is a deliberate v1.1 follow-up — keeping presets private to+the caller in v1.0 lets us ship without a "scope" enum and avoid the+"my buddy renamed our shared view" support ticket.++Authorization+-------------++Saved views are a personal-preference surface; every authenticated+user can manage their own. We therefore gate on authentication only+(no ``require_permission(...)`` factory). Read-only roles (e.g.+``viewer``) keep a read-write surface for their *own* preferences,+which matches how analysts actually use saved views in practice.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++import structlog+from fastapi import APIRouter, HTTPException, Query, status+from pydantic import BaseModel, ConfigDict, Field+from sqlalchemy import and_, delete, select, update+from sqlalchemy.exc import IntegrityError++from app.api.v1.deps import AuthUser+from app.db.rls import TenantDBSession+from app.models.saved_view import SavedView++logger = structlog.get_logger()++router = APIRouter(prefix="/saved-views", tags=["saved-views"])++# Mirrors the CHECK constraint on the table. Keep the two in lockstep:+# adding "dashboards" or "hunts" later requires both the migration and+# this allowlist.+_VALID_VIEW_TYPES = {"alerts", "cases", "investigations", "playbooks"}++# Reasonable upper bounds — saved views are per-user UI state, not a+# data store. Past these limits something is wrong (either a bug or+# an analyst trying to use the table as a key/value cache).+_MAX_NAME_LEN = 120+_MAX_FILTERS_BYTES = 8 * 1024 # 8 KB JSON is more than enough for any list page.+_MAX_COLUMNS_BYTES = 4 * 1024+++def _validate_view_type(view_type: str) -> str:+ if view_type not in _VALID_VIEW_TYPES:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=(+ f"view_type must be one of: "+ f"{', '.join(sorted(_VALID_VIEW_TYPES))}"+ ),+ )+ return view_type+++def _validate_payload_size(blob: Any, *, field: str, limit: int) -> None:+ """Reject saved views whose JSON blob is unreasonably large.++ The DB will technically accept arbitrary JSONB, but a runaway+ payload turns the saved-views endpoint into a per-user blob store+ we'd then have to maintain. Capping early keeps the surface+ honest.+ """+ if blob is None:+ return+ try:+ import json # noqa: PLC0415++ approx = len(json.dumps(blob, separators=(",", ":")))+ except (TypeError, ValueError) as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"{field} must be JSON-serialisable",+ ) from exc+ if approx > limit:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail=f"{field} exceeds maximum size of {limit} bytes",+ )+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class SavedViewModel(BaseModel):+ """Wire format for a saved view row."""++ id: str+ view_type: str+ name: str+ filters: dict[str, Any] = Field(default_factory=dict)+ columns: list[Any] | dict[str, Any] | None = None+ is_default: bool = False+ created_at: str+ updated_at: str++ model_config = ConfigDict(from_attributes=False)++ @classmethod+ def from_orm(cls, row: SavedView) -> SavedViewModel:+ return cls(+ id=str(row.id),+ view_type=row.view_type,+ name=row.name,+ filters=dict(row.filters or {}),+ columns=row.columns,+ is_default=bool(row.is_default),+ created_at=row.created_at.isoformat(),+ updated_at=row.updated_at.isoformat(),+ )+++class CreateSavedViewRequest(BaseModel):+ view_type: str+ name: str = Field(..., min_length=1, max_length=_MAX_NAME_LEN)+ filters: dict[str, Any] = Field(default_factory=dict)+ columns: list[Any] | dict[str, Any] | None = None+ is_default: bool = False+++class UpdateSavedViewRequest(BaseModel):+ """Partial update — every field is optional.++ Sending an empty body is a no-op (returns the row unchanged). To+ *clear* ``columns`` and fall back to the page default column set,+ the caller passes ``columns: null`` explicitly — the optional /+ null distinction is preserved in the JSON.+ """++ name: str | None = Field(default=None, min_length=1, max_length=_MAX_NAME_LEN)+ filters: dict[str, Any] | None = None+ columns: list[Any] | dict[str, Any] | None = None+ is_default: bool | None = None++ # Track which fields the caller actually sent so we can distinguish+ # "explicit null" from "omitted" without reaching into Pydantic+ # internals at every call site.+ model_config = ConfigDict(extra="forbid")+++# ---------------------------------------------------------------------------+# Endpoints+# ---------------------------------------------------------------------------++[email protected]("", response_model=list[SavedViewModel])+async def list_saved_views(+ user: AuthUser,+ db: TenantDBSession,+ view_type: str = Query(+ ...,+ description=(+ "Which list page to return presets for. One of: "+ f"{', '.join(sorted(_VALID_VIEW_TYPES))}."+ ),+ ),+) -> list[SavedViewModel]:+ """Return the caller's saved views for one list page.++ Sorted by ``is_default DESC, updated_at DESC`` so the default+ preset always lands first, with the rest ordered by recency. The+ UI uses this ordering directly to render the saved-views menu.+ """+ _validate_view_type(view_type)++ rows = (+ await db.execute(+ select(SavedView)+ .where(+ SavedView.tenant_id == user.tenant_id,+ SavedView.user_id == user.user_id,+ SavedView.view_type == view_type,+ )+ .order_by(SavedView.is_default.desc(), SavedView.updated_at.desc())+ )+ ).scalars().all()++ return [SavedViewModel.from_orm(r) for r in rows]++[email protected]("", response_model=SavedViewModel, status_code=status.HTTP_201_CREATED)+async def create_saved_view(+ payload: CreateSavedViewRequest,+ user: AuthUser,+ db: TenantDBSession,+) -> SavedViewModel:+ """Create a new saved view.++ If ``is_default=True`` is passed, any existing default for the+ same ``(tenant, user, view_type)`` is demoted *first* so the+ partial unique index in 037 doesn't trip. We do the demote + insert+ in a single transaction so a concurrent ``POST`` from the same+ user can't leave the table without a default.+ """+ _validate_view_type(payload.view_type)+ _validate_payload_size(payload.filters, field="filters", limit=_MAX_FILTERS_BYTES)+ _validate_payload_size(payload.columns, field="columns", limit=_MAX_COLUMNS_BYTES)++ name = payload.name.strip()+ if not name:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="name must not be blank",+ )++ if payload.is_default:+ await _demote_existing_default(+ db,+ tenant_id=user.tenant_id,+ user_id=user.user_id,+ view_type=payload.view_type,+ )++ # Stamp timestamps eagerly so the response payload has them even if+ # we skip ``db.refresh`` (e.g. in unit tests with mocked sessions).+ # SQLAlchemy's Python-side defaults only run during flush, which+ # gets bypassed when the test fixture mocks ``flush`` to a no-op.+ now = datetime.now(UTC)+ row = SavedView(+ id=uuid.uuid4(),+ tenant_id=user.tenant_id,+ user_id=user.user_id,+ view_type=payload.view_type,+ name=name,+ filters=dict(payload.filters or {}),+ columns=payload.columns,+ is_default=bool(payload.is_default),+ created_at=now,+ updated_at=now,+ )+ db.add(row)+ try:+ await db.flush()+ await db.commit()+ except IntegrityError as exc:+ await db.rollback()+ # Surface the most likely cause: duplicate name within+ # (tenant, user, view_type). The other unique index — partial+ # on is_default — is guarded by _demote_existing_default+ # above, so a hit here is almost certainly the name.+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=(+ f"A saved view named '{name}' already exists for "+ f"this user and view type"+ ),+ ) from exc++ await db.refresh(row)++ logger.info(+ "saved_view.create",+ tenant_id=str(user.tenant_id),+ user_id=str(user.user_id),+ view_type=payload.view_type,+ view_id=str(row.id),+ is_default=row.is_default,+ )+ return SavedViewModel.from_orm(row)++[email protected]("/{view_id}", response_model=SavedViewModel)+async def update_saved_view(+ view_id: str,+ payload: UpdateSavedViewRequest,+ user: AuthUser,+ db: TenantDBSession,+) -> SavedViewModel:+ """Patch a saved view in place.++ Sending only ``is_default=True`` is the canonical "make this my+ default" path. We demote the existing default first inside the+ same transaction.+ """+ view_uuid = _coerce_uuid(view_id)+ row = await _load_owned_view(db, view_uuid, user)++ fields_set = payload.model_fields_set+ if not fields_set:+ return SavedViewModel.from_orm(row)++ if "filters" in fields_set:+ _validate_payload_size(+ payload.filters, field="filters", limit=_MAX_FILTERS_BYTES+ )+ row.filters = dict(payload.filters or {})++ if "columns" in fields_set:+ _validate_payload_size(+ payload.columns, field="columns", limit=_MAX_COLUMNS_BYTES+ )+ row.columns = payload.columns # may be explicit None — clears it.++ if "name" in fields_set and payload.name is not None:+ new_name = payload.name.strip()+ if not new_name:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="name must not be blank",+ )+ row.name = new_name++ if "is_default" in fields_set and payload.is_default is not None:+ if payload.is_default and not row.is_default:+ await _demote_existing_default(+ db,+ tenant_id=user.tenant_id,+ user_id=user.user_id,+ view_type=row.view_type,+ except_id=row.id,+ )+ row.is_default = bool(payload.is_default)++ row.updated_at = datetime.now(UTC)++ try:+ await db.flush()+ await db.commit()+ except IntegrityError as exc:+ await db.rollback()+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=(+ "A saved view with this name already exists for "+ "this user and view type"+ ),+ ) from exc++ await db.refresh(row)++ logger.info(+ "saved_view.update",+ tenant_id=str(user.tenant_id),+ user_id=str(user.user_id),+ view_id=str(row.id),+ is_default=row.is_default,+ )+ return SavedViewModel.from_orm(row)++[email protected]("/{view_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_saved_view(+ view_id: str,+ user: AuthUser,+ db: TenantDBSession,+) -> None:+ """Delete a saved view owned by the caller."""+ view_uuid = _coerce_uuid(view_id)++ result = await db.execute(+ delete(SavedView).where(+ and_(+ SavedView.id == view_uuid,+ SavedView.tenant_id == user.tenant_id,+ SavedView.user_id == user.user_id,+ )+ )+ )+ if result.rowcount == 0:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Saved view not found",+ )+ await db.commit()++ logger.info(+ "saved_view.delete",+ tenant_id=str(user.tenant_id),+ user_id=str(user.user_id),+ view_id=str(view_uuid),+ )+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _coerce_uuid(value: str) -> uuid.UUID:+ try:+ return uuid.UUID(value)+ except (TypeError, ValueError) as exc:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Saved view not found",+ ) from exc+++async def _load_owned_view(+ db: Any, # noqa: ANN401 — TenantDBSession is an Annotated alias.+ view_id: uuid.UUID,+ user: Any, # noqa: ANN401 — CurrentUser; avoiding the import cycle.+) -> SavedView:+ row = await db.scalar(+ select(SavedView).where(+ SavedView.id == view_id,+ SavedView.tenant_id == user.tenant_id,+ SavedView.user_id == user.user_id,+ )+ )+ if row is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Saved view not found",+ )+ return row+++async def _demote_existing_default(+ db: Any, # noqa: ANN401+ *,+ tenant_id: uuid.UUID,+ user_id: uuid.UUID,+ view_type: str,+ except_id: uuid.UUID | None = None,+) -> None:+ """Flip any existing default off so a new one can be promoted.++ Without this dance, the partial unique index+ ``saved_views_one_default_idx`` in migration 037 would reject the+ promotion. We could have written this as a single+ ``UPDATE ... WHERE is_default`` SQL statement; we keep it+ surgical (clearing only the matching row's flag) so we never+ accidentally clobber unrelated defaults if RLS or the+ ``user_id`` predicate ever drift.+ """+ conditions = [+ SavedView.tenant_id == tenant_id,+ SavedView.user_id == user_id,+ SavedView.view_type == view_type,+ SavedView.is_default.is_(True),+ ]+ if except_id is not None:+ conditions.append(SavedView.id != except_id)++ await db.execute(+ update(SavedView)+ .where(and_(*conditions))+ .values(is_default=False, updated_at=datetime.now(UTC))+ )diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex c2bbf03d8..fec781d15 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -53,6 +53,7 @@ from app.api.v1.endpoints import (rbac,remediation,reports,+ saved_views,shifts,sla,stix_taxii,@@ -103,6 +104,12 @@ api_router.include_router(oncall.router)api_router.include_router(approvals.router)api_router.include_router(passkeys.router)+# Per-user saved views — WS-F3 (analyst quality-of-life).+# Backs the saved-views menu on Alerts/Cases/Investigations/Playbooks+# list pages. Per-user-per-tenant CRUD; tenant scoping via RLS, user+# scoping in the API layer (every query filters on user_id).+api_router.include_router(saved_views.router)+# Wave 3 — operational maturityapi_router.include_router(assets.router)api_router.include_router(mssp.router)diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.pyindex 18c4128de..1e03d8849 100644--- a/services/api/app/models/__init__.py+++ b/services/api/app/models/__init__.py@@ -35,6 +35,7 @@ from app.models.responder import (PasskeyChallenge,PasskeyCredential,)+from app.models.saved_view import SavedViewfrom app.models.tenant import ApiKey, Tenant, Userfrom app.models.easm import ExternalAsset, ExternalAssetDriftfrom app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC@@ -86,6 +87,7 @@ __all__ = ["RemediationWhitelist","ReportArtefact","ReportTemplate",+ "SavedView","ThreatActor","ThreatIntelFeed","ThreatIntelIOC",diff --git a/services/api/app/models/saved_view.py b/services/api/app/models/saved_view.pynew file mode 100644index 000000000..b0fac0a23--- /dev/null+++ b/services/api/app/models/saved_view.py@@ -0,0 +1,128 @@+"""Per-user saved views ORM model — Workstream F3 (analyst quality-of-life).++A *saved view* is the analyst's stored preset for a list page. Three+list pages currently use this: Alerts, Cases / Investigations, and+Playbooks. Each preset is a `(filters, columns)` pair — opaque JSON+blobs whose schema is owned entirely by the frontend. The API never+inspects the contents; it round-trips them as JSONB.++Why "opaque"? The list pages keep evolving (new filter chips, new+column ids), and a strongly-typed backend schema would force a+migration every time a filter is added. Instead the frontend renders+saved views best-effort: unknown filter keys are dropped, missing keys+fall back to defaults. This is the same trade-off Sentry/Linear/Jira+make for their saved views — flexibility wins over server-side+validation for a per-user preference store.++Tenant isolation is enforced via Row-Level Security in+``services/api/migrations/037_saved_views.sql``. User isolation is+enforced in the API layer (every query is scoped+``WHERE user_id = current_user.id``).+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import (+ Boolean,+ DateTime,+ ForeignKey,+ Index,+ String,+ UniqueConstraint,+ text,+)+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class SavedView(Base):+ """Per-user filter+column preset for an AiSOC list page."""++ __tablename__ = "saved_views"++ id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), primary_key=True, default=uuid.uuid4+ )++ tenant_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("tenants.id", ondelete="CASCADE"),+ nullable=False,+ )+ user_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("users.id", ondelete="CASCADE"),+ nullable=False,+ )++ # Which list page this preset belongs to. One of:+ # ``alerts | cases | investigations | playbooks``. Stored as a+ # short string instead of an enum so adding a new page in v1.1+ # is a code-only change.+ view_type: Mapped[str] = mapped_column(String(40), nullable=False)++ # Human-readable label rendered as a pill in the saved-views bar.+ name: Mapped[str] = mapped_column(String(120), nullable=False)++ # Opaque JSON matching the list page's filter shape. The backend+ # never inspects the contents.+ filters: Mapped[dict] = mapped_column(+ JSONB, nullable=False, default=dict, server_default=text("'{}'::jsonb")+ )++ # Optional ordered list of column ids/widths. NULL means "use the+ # page default column set" — saves a row from carrying redundant+ # default state.+ columns: Mapped[list | dict | None] = mapped_column(+ JSONB, nullable=True, default=None+ )++ # Exactly one default per (tenant, user, view_type) — the partial+ # unique index in the migration enforces this at the DB layer so+ # we don't have to do a transactional toggle in the API.+ is_default: Mapped[bool] = mapped_column(+ Boolean, nullable=False, default=False, server_default=text("false")+ )++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ nullable=False,+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ nullable=False,+ )++ __table_args__ = (+ UniqueConstraint(+ "tenant_id",+ "user_id",+ "view_type",+ "name",+ name="saved_views_unique_name",+ ),+ Index(+ "saved_views_owner_type_idx",+ "tenant_id",+ "user_id",+ "view_type",+ ),+ # Partial unique index — at most one default per+ # (tenant, user, view_type). Mirrors the migration.+ Index(+ "saved_views_one_default_idx",+ "tenant_id",+ "user_id",+ "view_type",+ unique=True,+ postgresql_where=text("is_default"),+ ),+ )diff --git a/services/api/migrations/037_saved_views.sql b/services/api/migrations/037_saved_views.sqlnew file mode 100644index 000000000..ea187af76--- /dev/null+++ b/services/api/migrations/037_saved_views.sql@@ -0,0 +1,83 @@+-- Migration 037: Per-user saved views for list pages (WS-F3).+--+-- Analysts spend most of their day on three list pages: Alerts, Cases /+-- Investigations, and Playbooks. Each page exposes filter chips (severity,+-- status, source, owner, time range) and an optional column set. Without+-- saved views, every shift starts with the same five clicks. We persist+-- these presets per-user-per-tenant so "my critical-only triage view" or+-- "the queue I share with the EU shift" loads in one click.+--+-- Schema:+-- id - opaque uuid, surfaced in URLs (`?view=<id>`).+-- tenant_id - owner tenant; isolation is enforced by RLS.+-- user_id - owning analyst; saved views are *private to the user*+-- within a tenant. Sharing across users is a v1.1 polish+-- (we'd flip this column nullable + add a `scope` enum).+-- view_type - which list page this preset belongs to+-- (`alerts | cases | investigations | playbooks`).+-- Stored as TEXT so adding a new list page in v1.1 is a+-- code-only change.+-- name - human-readable label rendered as a pill in the saved-+-- views bar (e.g. "Critical only", "EU shift queue").+-- filters - opaque JSONB matching the list page's filter shape+-- (e.g. `AlertFilters` from apps/web/src/lib/api.ts).+-- The backend never inspects the contents — it round-trips+-- the blob untouched. Frontend owns the schema.+-- columns - optional JSONB list of column ids/widths. NULL means+-- "use the page default column set".+-- is_default - exactly one default per (tenant, user, view_type); the+-- partial unique index below enforces it. The list page+-- auto-applies the default on first mount.+-- created_at - mint timestamp.+-- updated_at - bumped on every mutation; used to drive the "synced X+-- minutes ago" hint in the saved-views menu.+--+-- Indexes:+-- - per-(tenant, user, view_type) lookup is the only hot query.+-- - partial unique on is_default keeps the "exactly one default"+-- invariant at the DB layer rather than relying on the API to+-- race-free toggle the previous default.++BEGIN;++CREATE TABLE IF NOT EXISTS saved_views (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ view_type VARCHAR(40) NOT NULL,+ name VARCHAR(120) NOT NULL,+ filters JSONB NOT NULL DEFAULT '{}'::jsonb,+ columns JSONB,+ is_default BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT saved_views_view_type_check+ CHECK (view_type IN ('alerts', 'cases', 'investigations', 'playbooks')),+ CONSTRAINT saved_views_unique_name+ UNIQUE (tenant_id, user_id, view_type, name)+);++-- The hot read path: "give me my saved views for the alerts page".+CREATE INDEX IF NOT EXISTS saved_views_owner_type_idx+ ON saved_views (tenant_id, user_id, view_type);++-- At most one default per (tenant, user, view_type). Partial unique+-- index is the right tool: it lets non-default rows duplicate freely+-- while still enforcing the singleton invariant.+CREATE UNIQUE INDEX IF NOT EXISTS saved_views_one_default_idx+ ON saved_views (tenant_id, user_id, view_type)+ WHERE is_default;++-- ============================================================+-- RLS: tenant isolation. User-level scoping is enforced in the+-- API layer (deps.py + endpoints/saved_views.py); RLS only+-- guarantees that a tenant can never see another tenant's views.+-- ============================================================+ALTER TABLE saved_views ENABLE ROW LEVEL SECURITY;+ALTER TABLE saved_views FORCE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS saved_views_tenant_isolation ON saved_views;+CREATE POLICY saved_views_tenant_isolation ON saved_views+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++COMMIT;diff --git a/services/api/tests/test_saved_views_endpoint.py b/services/api/tests/test_saved_views_endpoint.pynew file mode 100644index 000000000..fd6279e46--- /dev/null+++ b/services/api/tests/test_saved_views_endpoint.py@@ -0,0 +1,924 @@+"""Unit tests for the per-user saved-views CRUD endpoints (Workstream F3).++The saved-views endpoints (``/api/v1/saved-views`` GET / POST / PATCH /+DELETE) are mostly orchestration: validate input, scope the query by+``(tenant_id, user_id)``, and round-trip an opaque JSONB blob. Like the+sibling endpoint tests in this repo (``test_inbox_itsm_endpoint.py``,+``test_lake_endpoint.py``) we mock the DB session directly rather than+spinning up the FastAPI app + Postgres harness.++What we cover here:++* ``_validate_view_type`` — the allowlist mirror of the table CHECK+ constraint. Adding a fifth view type without bumping both is a bug+ we catch by asserting a known-good and a known-bad value.+* ``_validate_payload_size`` — the JSONB size cap that keeps the table+ out of "blob store" duty. Below limit, above limit, and the+ unserialisable branch.+* ``_coerce_uuid`` — defensive 404 instead of 500 on garbled IDs.+ Important because the route accepts arbitrary strings via path.+* ``list_saved_views`` — happy path returns sorted rows; invalid+ ``view_type`` returns 422 *before* we touch the DB.+* ``create_saved_view`` — fields are forwarded verbatim, ``is_default``+ triggers the demote step, blank names are 422, and an IntegrityError+ surfaces as 409 (not 500).+* ``update_saved_view`` — partial update semantics: empty PATCH is a+ no-op (returns the row unchanged), explicit ``columns: null``+ *clears* the columns blob (vs. omitting which leaves them alone),+ flipping ``is_default`` from false → true demotes the existing+ default, missing rows 404.+* ``delete_saved_view`` — 204 on success, 404 when nothing matched.++Tenancy & user-scoping are verified by inspecting the WHERE clauses+constructed by the endpoint, not by running them — that's the right+job for the migration / RLS integration tests.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from app.api.v1.endpoints.saved_views import (+ CreateSavedViewRequest,+ SavedViewModel,+ UpdateSavedViewRequest,+ _coerce_uuid,+ _demote_existing_default,+ _validate_payload_size,+ _validate_view_type,+ create_saved_view,+ delete_saved_view,+ list_saved_views,+ update_saved_view,+)+from fastapi import HTTPException+from sqlalchemy.exc import IntegrityError+++# ---------------------------------------------------------------------------+# Test fixtures / helpers+# ---------------------------------------------------------------------------+++def _build_user(+ *,+ tenant_id: uuid.UUID | None = None,+ user_id: uuid.UUID | None = None,+ role: str = "analyst",+) -> SimpleNamespace:+ """Minimal CurrentUser stand-in for the endpoints.++ The endpoints only read ``tenant_id``, ``user_id``, ``role``, and+ ``email`` — a SimpleNamespace is plenty and keeps the tests free of+ the auth import graph.+ """+ return SimpleNamespace(+ tenant_id=tenant_id or uuid.uuid4(),+ user_id=user_id or uuid.uuid4(),+ role=role,+ email="[email protected]",+ )+++def _saved_view_row(+ *,+ view_type: str = "alerts",+ name: str = "Critical only",+ is_default: bool = False,+ tenant_id: uuid.UUID | None = None,+ user_id: uuid.UUID | None = None,+ filters: dict[str, Any] | None = None,+ columns: list[Any] | dict[str, Any] | None = None,+ row_id: uuid.UUID | None = None,+) -> SimpleNamespace:+ """Build a SavedView row stand-in with the attribute surface the+ endpoint and ``SavedViewModel.from_orm`` actually read.++ We use SimpleNamespace instead of the real ORM model so the tests+ don't accidentally exercise SQLAlchemy's instrumentation —+ ``row.filters = ...`` on a real ``SavedView`` would dirty the+ session, which we'd rather skip in pure-unit tests.+ """+ now = datetime.now(UTC)+ return SimpleNamespace(+ id=row_id or uuid.uuid4(),+ tenant_id=tenant_id or uuid.uuid4(),+ user_id=user_id or uuid.uuid4(),+ view_type=view_type,+ name=name,+ filters=filters if filters is not None else {},+ columns=columns,+ is_default=is_default,+ created_at=now,+ updated_at=now,+ )+++# ---------------------------------------------------------------------------+# _validate_view_type+# ---------------------------------------------------------------------------+++ "view_type",+ ["alerts", "cases", "investigations", "playbooks"],+)+def test_validate_view_type_accepts_known_pages(view_type: str) -> None:+ """Every page wired into the saved-views menu must round-trip."""+ assert _validate_view_type(view_type) == view_type+++def test_validate_view_type_rejects_unknown() -> None:+ """A typo or new page that wasn't added to the allowlist 422s.++ This mirrors the CHECK constraint in migration 037 — keeping the+ two in lockstep is the whole point of the allowlist living here+ rather than relying on the DB to surface a constraint violation+ (which would 500 in production).+ """+ with pytest.raises(HTTPException) as exc:+ _validate_view_type("dashboards") # not in the allowlist (yet)+ assert exc.value.status_code == 422+ assert "view_type must be one of" in exc.value.detail+++def test_validate_view_type_is_case_sensitive() -> None:+ """``Alerts`` is not the same as ``alerts``.++ Frontend always sends lowercase via the page constant, but if a+ bespoke API client gets the casing wrong we'd rather 422 cleanly+ than store a row that disagrees with the CHECK constraint.+ """+ with pytest.raises(HTTPException):+ _validate_view_type("Alerts")+++# ---------------------------------------------------------------------------+# _validate_payload_size+# ---------------------------------------------------------------------------+++def test_validate_payload_size_none_is_noop() -> None:+ """Optional columns blob: None must not raise."""+ _validate_payload_size(None, field="columns", limit=100)+++def test_validate_payload_size_under_limit_passes() -> None:+ """A typical filter blob (a few KB) is well under the 8 KB cap."""+ _validate_payload_size({"severity": ["high", "critical"]}, field="filters", limit=8192)+++def test_validate_payload_size_over_limit_raises_413() -> None:+ """Above the cap → 413 Payload Too Large with the field name in the detail.++ The cap exists so the saved-views table doesn't drift into being a+ per-user blob store — analysts copy/pasting a JSON dump into a+ filter is a real failure mode we'd rather reject loudly.+ """+ huge = {"haystack": "x" * 20000}+ with pytest.raises(HTTPException) as exc:+ _validate_payload_size(huge, field="filters", limit=8192)+ assert exc.value.status_code == 413+ assert "filters" in exc.value.detail+ assert "8192" in exc.value.detail+++def test_validate_payload_size_unserialisable_raises_422() -> None:+ """A blob with a non-JSON-serialisable value 422s, not 500.++ Pydantic accepts ``dict[str, Any]`` so an exotic value can sneak+ past the schema; we catch it with a deliberate 422 rather than+ letting ``json.dumps`` crash the request handler.+ """+ not_serialisable = {"started": object()} # raw object → TypeError+ with pytest.raises(HTTPException) as exc:+ _validate_payload_size(not_serialisable, field="filters", limit=8192)+ assert exc.value.status_code == 422+ assert "JSON-serialisable" in exc.value.detail+++# ---------------------------------------------------------------------------+# _coerce_uuid+# ---------------------------------------------------------------------------+++def test_coerce_uuid_accepts_canonical_string() -> None:+ """Round-trips a normal UUID string."""+ raw = "f47ac10b-58cc-4372-a567-0e02b2c3d479"+ out = _coerce_uuid(raw)+ assert isinstance(out, uuid.UUID)+ assert str(out) == raw+++def test_coerce_uuid_garbage_raises_404_not_500() -> None:+ """Bogus path param → 404 (matches the "saved view not found" UX).++ Surfacing a 422 here would leak that the endpoint can be probed+ to enumerate saved-view IDs vs. random strings; 404 is the same+ code analysts get for a real missing row.+ """+ with pytest.raises(HTTPException) as exc:+ _coerce_uuid("not-a-uuid")+ assert exc.value.status_code == 404+ assert exc.value.detail == "Saved view not found"+++def test_coerce_uuid_empty_string_raises_404() -> None:+ """Defensive: empty path segments shouldn't reach this helper, but+ if they do we still 404 cleanly."""+ with pytest.raises(HTTPException) as exc:+ _coerce_uuid("")+ assert exc.value.status_code == 404+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++def test_saved_view_model_from_orm_serialises_uuid_and_datetime() -> None:+ """ORM → wire conversion produces the expected primitive types."""+ row = _saved_view_row(+ name="Triage view",+ filters={"severity": ["high"]},+ columns=["title", "severity", "owner"],+ )+ model = SavedViewModel.from_orm(row)+ assert model.id == str(row.id)+ assert model.name == "Triage view"+ assert model.filters == {"severity": ["high"]}+ assert model.columns == ["title", "severity", "owner"]+ assert model.is_default is False+ # ISO 8601 round-trip — assertion focuses on the contract that the+ # frontend Date constructor will accept the string.+ assert model.created_at == row.created_at.isoformat()+ assert model.updated_at == row.updated_at.isoformat()+++def test_saved_view_model_from_orm_handles_null_filters() -> None:+ """A row with ``filters=None`` should still serialise to ``{}``.++ The DB has ``NOT NULL DEFAULT '{}'::jsonb`` so we should never+ actually see this — but a freshly-built ORM instance pre-flush+ can have ``filters=None``, and the model coerces defensively.+ """+ row = _saved_view_row()+ row.filters = None+ model = SavedViewModel.from_orm(row)+ assert model.filters == {}+++def test_create_request_rejects_empty_name() -> None:+ """``name`` is mandatory, non-empty, and bounded.++ Pydantic raises ValidationError for ``min_length=1``; the endpoint+ *also* strips and re-checks (covered separately) so a whitespace-+ only string is caught even if pydantic accepts it.+ """+ with pytest.raises(Exception): # pydantic.ValidationError, but importing for the type is overkill+ CreateSavedViewRequest(view_type="alerts", name="")+++def test_update_request_extra_fields_forbidden() -> None:+ """Unknown PATCH keys are rejected — defends against typos like+ ``is_defualt`` silently being a no-op."""+ with pytest.raises(Exception):+ UpdateSavedViewRequest(unknown_field="oops")+++def test_update_request_distinguishes_omitted_vs_explicit_null() -> None:+ """``columns=None`` (explicit) vs. omitting it must be observable.++ Used by the PATCH endpoint to decide whether to clear ``columns``+ or leave it alone. Without this, "use default columns" wouldn't+ have a way to be expressed by the API client.+ """+ omitted = UpdateSavedViewRequest()+ assert "columns" not in omitted.model_fields_set++ explicit = UpdateSavedViewRequest(columns=None)+ assert "columns" in explicit.model_fields_set+ assert explicit.columns is None+++# ---------------------------------------------------------------------------+# list_saved_views+# ---------------------------------------------------------------------------+++def _mock_db_with_list_result(rows: list[SimpleNamespace]) -> MagicMock:+ """Build a DB mock whose ``.execute().scalars().all()`` returns ``rows``."""+ db = MagicMock()+ scalars_result = MagicMock()+ scalars_result.all = MagicMock(return_value=rows)+ execute_result = MagicMock()+ execute_result.scalars = MagicMock(return_value=scalars_result)+ db.execute = AsyncMock(return_value=execute_result)+ return db+++async def test_list_saved_views_returns_serialised_rows() -> None:+ """Happy path: rows in → wire models out."""+ user = _build_user()+ rows = [+ _saved_view_row(+ tenant_id=user.tenant_id,+ user_id=user.user_id,+ name="Critical only",+ is_default=True,+ ),+ _saved_view_row(+ tenant_id=user.tenant_id,+ user_id=user.user_id,+ name="My queue",+ ),+ ]+ db = _mock_db_with_list_result(rows)++ result = await list_saved_views(user=user, db=db, view_type="alerts")++ assert len(result) == 2+ assert all(isinstance(r, SavedViewModel) for r in result)+ assert {r.name for r in result} == {"Critical only", "My queue"}+ db.execute.assert_awaited_once()+++async def test_list_saved_views_invalid_type_422_before_db_call() -> None:+ """Validation runs before any DB I/O.++ Critical for two reasons: (1) it bounds the cost of a flood of+ bad requests, (2) it means a typo can't accidentally enumerate+ rows for a different view_type via SQL injection through the+ ORDER BY clause (defence-in-depth — there's no obvious vector+ here, but never hurts).+ """+ db = _mock_db_with_list_result([])+ user = _build_user()+ with pytest.raises(HTTPException) as exc:+ await list_saved_views(user=user, db=db, view_type="dashboards")+ assert exc.value.status_code == 422+ db.execute.assert_not_awaited()+++async def test_list_saved_views_filters_by_tenant_and_user() -> None:+ """Verify the query is scoped to ``(tenant_id, user_id, view_type)``.++ We inspect the SQLAlchemy clause string rather than running it —+ the migration tests are the right place for round-trip semantics.+ The point of this assertion is to catch a future refactor that+ forgets the user_id predicate (which would return *every* user's+ views in the tenant).+ """+ user = _build_user()+ db = _mock_db_with_list_result([])+ await list_saved_views(user=user, db=db, view_type="cases")++ call_args = db.execute.await_args+ stmt = call_args.args[0]+ compiled = str(stmt.compile(compile_kwargs={"literal_binds": True}))+ assert "saved_views" in compiled+ # SQLAlchemy's PG UUID type renders as 32-char hex (no dashes)+ # when compiled with literal_binds; accept either form so the+ # test stays robust if dialect rendering changes.+ assert (str(user.tenant_id) in compiled) or (user.tenant_id.hex in compiled)+ assert (str(user.user_id) in compiled) or (user.user_id.hex in compiled)+ assert "cases" in compiled+++# ---------------------------------------------------------------------------+# create_saved_view+# ---------------------------------------------------------------------------+++def _mock_db_for_create(*, integrity_error: bool = False) -> MagicMock:+ """Build a DB mock for a successful create or one that hits the+ duplicate-name unique constraint.++ The endpoint's flow is:+ 1. (optional) demote existing default — UPDATE+ 2. ``db.add(row)``+ 3. ``db.flush()`` then ``db.commit()`` (or .rollback() on error)+ 4. ``db.refresh(row)``+ """+ db = MagicMock()+ db.execute = AsyncMock()+ db.add = MagicMock()+ if integrity_error:+ db.flush = AsyncMock(+ side_effect=IntegrityError("duplicate", None, BaseException("dup"))+ )+ else:+ db.flush = AsyncMock()+ db.commit = AsyncMock()+ db.rollback = AsyncMock()+ db.refresh = AsyncMock()+ return db+++async def test_create_saved_view_happy_path() -> None:+ """Valid payload → row added, flushed, committed, refreshed."""+ user = _build_user()+ db = _mock_db_for_create()+ payload = CreateSavedViewRequest(+ view_type="alerts",+ name="Critical only",+ filters={"severity": ["critical", "high"]},+ columns=["title", "severity"],+ is_default=False,+ )+ result = await create_saved_view(payload=payload, user=user, db=db)++ assert isinstance(result, SavedViewModel)+ assert result.name == "Critical only"+ assert result.filters == {"severity": ["critical", "high"]}+ assert result.is_default is False++ db.add.assert_called_once()+ db.flush.assert_awaited_once()+ db.commit.assert_awaited_once()+ db.refresh.assert_awaited_once()+ db.rollback.assert_not_awaited()+ # No demote step needed because is_default=False.+ db.execute.assert_not_awaited()+++async def test_create_saved_view_with_is_default_demotes_existing() -> None:+ """``is_default=True`` runs the UPDATE-to-clear-existing-default first.++ Without this, the partial unique index in migration 037 would+ reject the INSERT. The test asserts both writes happen *and* the+ demote runs before the row is added (order matters for the+ transactional invariant).+ """+ user = _build_user()+ db = _mock_db_for_create()+ payload = CreateSavedViewRequest(+ view_type="alerts",+ name="My default",+ filters={},+ is_default=True,+ )+ await create_saved_view(payload=payload, user=user, db=db)++ # Demote step issued exactly once.+ db.execute.assert_awaited_once()+ db.add.assert_called_once()+ db.flush.assert_awaited_once()+ db.commit.assert_awaited_once()+++async def test_create_saved_view_blank_name_raises_422() -> None:+ """``" "`` (whitespace-only) → 422, not a row with a blank label.++ Pydantic's ``min_length=1`` doesn't catch whitespace; the endpoint+ strips and re-checks. Test belongs here rather than in the schema+ test because the strip+check is endpoint policy.+ """+ user = _build_user()+ db = _mock_db_for_create()+ payload = CreateSavedViewRequest(+ view_type="alerts",+ name=" ",+ filters={},+ )+ with pytest.raises(HTTPException) as exc:+ await create_saved_view(payload=payload, user=user, db=db)+ assert exc.value.status_code == 422+ assert "blank" in exc.value.detail.lower()+ db.add.assert_not_called()+++async def test_create_saved_view_duplicate_name_returns_409() -> None:+ """The unique constraint surfaces as 409 Conflict, not 500.++ Operators see this when an analyst saves "Critical only" twice in+ quick succession (e.g. the menu didn't refresh). 409 with a clear+ detail tells the UI to nudge the user instead of just dying.+ """+ user = _build_user()+ db = _mock_db_for_create(integrity_error=True)+ payload = CreateSavedViewRequest(+ view_type="alerts",+ name="Critical only",+ filters={},+ )+ with pytest.raises(HTTPException) as exc:+ await create_saved_view(payload=payload, user=user, db=db)+ assert exc.value.status_code == 409+ assert "Critical only" in exc.value.detail+ db.rollback.assert_awaited_once()+ db.commit.assert_not_awaited()+++async def test_create_saved_view_invalid_view_type_raises_422() -> None:+ """Invalid view_type bails before any DB activity."""+ user = _build_user()+ db = _mock_db_for_create()+ payload = CreateSavedViewRequest(+ view_type="hunts", # not in the allowlist+ name="Anything",+ )+ with pytest.raises(HTTPException) as exc:+ await create_saved_view(payload=payload, user=user, db=db)+ assert exc.value.status_code == 422+ db.add.assert_not_called()+++# ---------------------------------------------------------------------------+# update_saved_view+# ---------------------------------------------------------------------------+++def _mock_db_for_update(+ *,+ existing_row: SimpleNamespace | None,+ integrity_error: bool = False,+) -> MagicMock:+ """Build a DB mock for the PATCH endpoint.++ Order of DB calls in the endpoint:+ 1. ``db.scalar(SELECT ... WHERE id = ?)`` → existing row or None+ 2. (optional) ``db.execute(UPDATE ... is_default=false)`` — demote+ 3. ``db.flush()`` then ``db.commit()`` (or rollback on integrity)+ 4. ``db.refresh(row)``+ """+ db = MagicMock()+ db.scalar = AsyncMock(return_value=existing_row)+ db.execute = AsyncMock()+ if integrity_error:+ db.flush = AsyncMock(+ side_effect=IntegrityError("duplicate", None, BaseException("dup"))+ )+ else:+ db.flush = AsyncMock()+ db.commit = AsyncMock()+ db.rollback = AsyncMock()+ db.refresh = AsyncMock()+ return db+++async def test_update_saved_view_missing_row_returns_404() -> None:+ """Trying to patch a row another user owns / a deleted row → 404.++ The query already scopes by ``(tenant_id, user_id)`` so a foreign+ row is indistinguishable from "doesn't exist" — both are 404.+ """+ user = _build_user()+ db = _mock_db_for_update(existing_row=None)+ with pytest.raises(HTTPException) as exc:+ await update_saved_view(+ view_id=str(uuid.uuid4()),+ payload=UpdateSavedViewRequest(name="renamed"),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 404+++async def test_update_saved_view_garbled_uuid_returns_404() -> None:+ """Bad ID in path → 404 (not 422)."""+ user = _build_user()+ db = _mock_db_for_update(existing_row=_saved_view_row())+ with pytest.raises(HTTPException) as exc:+ await update_saved_view(+ view_id="not-a-uuid",+ payload=UpdateSavedViewRequest(name="renamed"),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 404+ db.scalar.assert_not_awaited() # bailed before the lookup+++async def test_update_saved_view_empty_body_is_noop() -> None:+ """An empty PATCH returns the row unchanged without a write.++ Useful for clients that diff-render a form; if no field changed,+ the update is free. We assert ``flush`` was NOT called to confirm+ the no-op path is genuinely no-op at the DB layer.+ """+ user = _build_user()+ row = _saved_view_row(name="Unchanged")+ db = _mock_db_for_update(existing_row=row)+ result = await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(), # everything omitted+ user=user,+ db=db,+ )+ assert result.name == "Unchanged"+ db.flush.assert_not_awaited()+ db.commit.assert_not_awaited()+++async def test_update_saved_view_renames_and_strips() -> None:+ """``name`` updates trim whitespace before persisting."""+ user = _build_user()+ row = _saved_view_row(name="Original")+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(name=" Renamed "),+ user=user,+ db=db,+ )+ assert row.name == "Renamed" # mutated in place; ORM tracks dirty state+ db.flush.assert_awaited_once()+ db.commit.assert_awaited_once()+++async def test_update_saved_view_blank_name_after_strip_422s() -> None:+ """A whitespace-only rename request is rejected, not stored."""+ user = _build_user()+ row = _saved_view_row(name="Original")+ db = _mock_db_for_update(existing_row=row)+ with pytest.raises(HTTPException) as exc:+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(name=" "),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 422+ assert row.name == "Original" # not mutated+++async def test_update_saved_view_explicit_columns_null_clears_field() -> None:+ """``columns=None`` (explicit) writes None — fall back to defaults.++ Without this branch, an analyst can't *un-pin* their custom column+ set: there'd be no JSON value that means "use the page default".+ """+ user = _build_user()+ row = _saved_view_row(columns=["title", "severity"])+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(columns=None),+ user=user,+ db=db,+ )+ assert row.columns is None+ db.flush.assert_awaited_once()+++async def test_update_saved_view_omitted_columns_unchanged() -> None:+ """``columns`` omitted from the PATCH body → the field is preserved.++ Mirror of the test above. The two together prove the+ omitted-vs-explicit-null distinction is real and load-bearing.+ """+ user = _build_user()+ row = _saved_view_row(columns=["title", "severity"])+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(name="renamed"),+ user=user,+ db=db,+ )+ assert row.columns == ["title", "severity"]+++async def test_update_saved_view_promote_to_default_demotes_existing() -> None:+ """Flipping ``is_default`` false → true triggers the demote UPDATE.++ The demote excludes the row being promoted (``except_id=row.id``)+ so the UPDATE doesn't immediately undo our own promotion in a+ subsequent flush.+ """+ user = _build_user()+ row = _saved_view_row(is_default=False)+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(is_default=True),+ user=user,+ db=db,+ )+ assert row.is_default is True+ # exactly one demote UPDATE was issued before the flush+ db.execute.assert_awaited_once()+ db.flush.assert_awaited_once()+++async def test_update_saved_view_already_default_does_not_demote() -> None:+ """Re-asserting ``is_default=True`` on the current default is a no-op+ for the demote step (avoids a needless UPDATE on every save)."""+ user = _build_user()+ row = _saved_view_row(is_default=True)+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(is_default=True),+ user=user,+ db=db,+ )+ assert row.is_default is True+ db.execute.assert_not_awaited()+++async def test_update_saved_view_unset_default_clears_flag() -> None:+ """``is_default=False`` is allowed and just clears the flag.++ No demote needed — leaving the table without a default is a valid+ state (the UI falls back to the page's hard-coded default).+ """+ user = _build_user()+ row = _saved_view_row(is_default=True)+ db = _mock_db_for_update(existing_row=row)+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(is_default=False),+ user=user,+ db=db,+ )+ assert row.is_default is False+ db.execute.assert_not_awaited()+++async def test_update_saved_view_duplicate_rename_returns_409() -> None:+ """Renaming to an existing name in the same scope → 409, not 500."""+ user = _build_user()+ row = _saved_view_row(name="Original")+ db = _mock_db_for_update(existing_row=row, integrity_error=True)+ with pytest.raises(HTTPException) as exc:+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(name="Already Taken"),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 409+ db.rollback.assert_awaited_once()+++async def test_update_saved_view_filters_size_capped() -> None:+ """Oversize filter blob on PATCH → 413, same as on create."""+ user = _build_user()+ row = _saved_view_row()+ db = _mock_db_for_update(existing_row=row)+ huge = {"haystack": "x" * 20000}+ with pytest.raises(HTTPException) as exc:+ await update_saved_view(+ view_id=str(row.id),+ payload=UpdateSavedViewRequest(filters=huge),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 413+ db.flush.assert_not_awaited()+++# ---------------------------------------------------------------------------+# delete_saved_view+# ---------------------------------------------------------------------------+++def _mock_db_for_delete(*, rowcount: int) -> MagicMock:+ """DB mock whose DELETE returns the given affected-row count."""+ db = MagicMock()+ result = MagicMock()+ result.rowcount = rowcount+ db.execute = AsyncMock(return_value=result)+ db.commit = AsyncMock()+ return db+++async def test_delete_saved_view_happy_path() -> None:+ """A matching DELETE commits and returns None (FastAPI yields 204)."""+ user = _build_user()+ db = _mock_db_for_delete(rowcount=1)+ result = await delete_saved_view(+ view_id=str(uuid.uuid4()),+ user=user,+ db=db,+ )+ assert result is None+ db.execute.assert_awaited_once()+ db.commit.assert_awaited_once()+++async def test_delete_saved_view_no_match_returns_404() -> None:+ """Zero rows affected → 404, not a silent success.++ Without the rowcount check, deleting another user's view would+ return 204 even though nothing actually changed — confusing UX+ *and* a potential information-leak vector (200 vs 404 leaks ID+ existence). The user_id predicate in the WHERE clause already+ prevents the cross-user delete; the 404 makes it explicit.+ """+ user = _build_user()+ db = _mock_db_for_delete(rowcount=0)+ with pytest.raises(HTTPException) as exc:+ await delete_saved_view(+ view_id=str(uuid.uuid4()),+ user=user,+ db=db,+ )+ assert exc.value.status_code == 404+ db.commit.assert_not_awaited()+++async def test_delete_saved_view_bad_uuid_returns_404() -> None:+ """Garbled path param → 404 before any DB call."""+ user = _build_user()+ db = _mock_db_for_delete(rowcount=0)+ with pytest.raises(HTTPException) as exc:+ await delete_saved_view(+ view_id="bogus",+ user=user,+ db=db,+ )+ assert exc.value.status_code == 404+ db.execute.assert_not_awaited()+++# ---------------------------------------------------------------------------+# _demote_existing_default — direct-test the helper too, since it's the+# load-bearing primitive for the partial-unique-index invariant.+# ---------------------------------------------------------------------------+++async def test_demote_existing_default_includes_user_predicate() -> None:+ """Helper must scope to ``(tenant_id, user_id, view_type)``.++ A bug here would clear another user's default in the same tenant,+ which is silent breakage of someone else's UI state. We assert the+ rendered SQL contains both IDs to lock that contract in.+ """+ db = MagicMock()+ db.execute = AsyncMock()+ tenant_id = uuid.uuid4()+ user_id = uuid.uuid4()++ await _demote_existing_default(+ db,+ tenant_id=tenant_id,+ user_id=user_id,+ view_type="alerts",+ )++ assert db.execute.await_count == 1+ stmt = db.execute.await_args.args[0]+ compiled = str(stmt.compile(compile_kwargs={"literal_binds": True}))+ # Accept either dashed or hex (no-dash) UUID rendering.+ assert (str(tenant_id) in compiled) or (tenant_id.hex in compiled)+ assert (str(user_id) in compiled) or (user_id.hex in compiled)+ assert "alerts" in compiled+++async def test_demote_existing_default_excludes_target_when_provided() -> None:+ """Update must skip ``except_id`` so the row being promoted survives.++ Without this exclusion, the demote step inside an UPDATE call+ would clear the same row we're about to flip on, undoing the+ promotion in the same transaction.+ """+ db = MagicMock()+ db.execute = AsyncMock()+ except_id = uuid.uuid4()+ await _demote_existing_default(+ db,+ tenant_id=uuid.uuid4(),+ user_id=uuid.uuid4(),+ view_type="cases",+ except_id=except_id,+ )+ stmt = db.execute.await_args.args[0]+ compiled = str(stmt.compile(compile_kwargs={"literal_binds": True}))+ assert (str(except_id) in compiled) or (except_id.hex in compiled)+ # The "id != ..." predicate must be in the WHERE clause (we accept+ # either operator rendering — SQLAlchemy emits "!=" or "<>" by+ # dialect; both are correct).+ assert ("!=" in compiled) or ("<>" in compiled)