OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: Unsaved changes warnings (#2277)
Mike Fortman697a848566fb
diff --git a/frontend/app/layout.tsx b/frontend/app/layout.tsxindex f8ee6d6cb..9221b8e55 100644--- a/frontend/app/layout.tsx+++ b/frontend/app/layout.tsx@@ -12,6 +12,7 @@ import { ChatProvider } from "@/contexts/chat-context";import { ConsoleStatusProvider } from "@/contexts/console-status-context";import { KnowledgeFilterProvider } from "@/contexts/knowledge-filter-context";import { TaskProvider } from "@/contexts/task-context";+import { UnsavedChangesProvider } from "@/contexts/unsaved-changes-context";import Providers from "./providers";const inter = Inter({@@ -64,7 +65,9 @@ export default function RootLayout({<KnowledgeFilterProvider><ConsoleStatusProvider><ChatProvider>- <LayoutWrapper>{children}</LayoutWrapper>+ <UnsavedChangesProvider>+ <LayoutWrapper>{children}</LayoutWrapper>+ </UnsavedChangesProvider></ChatProvider></ConsoleStatusProvider></KnowledgeFilterProvider>diff --git a/frontend/app/settings/_components/agent-settings-section.tsx b/frontend/app/settings/_components/agent-settings-section.tsxindex 3e90f93c1..50c9e25be 100644--- a/frontend/app/settings/_components/agent-settings-section.tsx+++ b/frontend/app/settings/_components/agent-settings-section.tsx@@ -25,6 +25,7 @@ import {import { Textarea } from "@/components/ui/textarea";import { useAuth } from "@/contexts/auth-context";import { useIsCloudBrand } from "@/contexts/brand-context";+import { useRegisterDirty } from "@/contexts/unsaved-changes-context";import { trackButton } from "@/lib/analytics";import { DEFAULT_AGENT_SETTINGS, UI_CONSTANTS } from "@/lib/constants";import { resolveLangflowEditUrl } from "@/lib/url-utils";@@ -47,6 +48,7 @@ export function AgentSettingsSection() {const [isRestoringFlow, setIsRestoringFlow] = useState<boolean>(false);const [openLlmSelector, setOpenLlmSelector] = useState(false);const [systemPrompt, setSystemPrompt] = useState<string>("");+ const [userEdited, setUserEdited] = useState(false);const { data: settings = {} } = useGetSettingsQuery({enabled: isAuthenticated || isNoAuthMode,@@ -181,6 +183,9 @@ export function AgentSettingsSection() {}}, [settings.agent?.llm_model, allLlmOptions, handleModelChange]);+ const agentDirty = systemPrompt !== (settings.agent?.system_prompt ?? "");+ useRegisterDirty("agent-settings", userEdited && agentDirty);+useEffect(() => {if (settings.agent?.system_prompt) {setSystemPrompt(settings.agent.system_prompt);@@ -207,7 +212,10 @@ export function AgentSettingsSection() {elementId: "save-agent-instructions-button",namespace: "settings",});- updateSettingsMutation.mutate({ system_prompt: systemPrompt });+ updateSettingsMutation.mutate(+ { system_prompt: systemPrompt },+ { onSuccess: () => setUserEdited(false) },+ );};const handleEditInLangflow = (closeDialog: () => void) => {@@ -253,6 +261,7 @@ export function AgentSettingsSection() {).then(() => {setSystemPrompt(DEFAULT_AGENT_SETTINGS.system_prompt);+ setUserEdited(false);toast.success("Default agent flow settings restored successfully");closeDialog();})@@ -357,7 +366,10 @@ export function AgentSettingsSection() {id="system-prompt"placeholder="Enter your agent instructions here..."value={systemPrompt}- onChange={(e) => setSystemPrompt(e.target.value)}+ onChange={(e) => {+ setUserEdited(true);+ setSystemPrompt(e.target.value);+ }}rows={6}className={`resize-none ${systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS@@ -379,9 +391,10 @@ export function AgentSettingsSection() {<div className="flex justify-end pt-2 gap-2">{settings.agent?.default_system_prompt && (<Button- onClick={() =>- setSystemPrompt(settings.agent?.default_system_prompt || "")- }+ onClick={() => {+ setUserEdited(true);+ setSystemPrompt(settings.agent?.default_system_prompt || "");+ }}variant="outline"size="sm"disabled={systemPrompt === settings.agent.default_system_prompt}diff --git a/frontend/app/settings/_components/ingest-preview-settings-section.tsx b/frontend/app/settings/_components/ingest-preview-settings-section.tsxindex 33f88ab12..44fd1567b 100644--- a/frontend/app/settings/_components/ingest-preview-settings-section.tsx+++ b/frontend/app/settings/_components/ingest-preview-settings-section.tsx@@ -6,6 +6,7 @@ import { IngestPreviewAutoOpenControl } from "@/components/ingest-preview-auto-oimport { IngestReviewDialog } from "@/components/ingest-review";import { Button } from "@/components/ui/button";import { Label } from "@/components/ui/label";+import { useRegisterDirty } from "@/contexts/unsaved-changes-context";import {INGEST_PREVIEW_AUTO_OPEN_OPTIONS,type IngestPreviewSettings,@@ -31,6 +32,8 @@ export function IngestPreviewSettingsSection() {}const isDirty = draft.autoOpen !== settings.autoOpen;+ useRegisterDirty("ingest-preview", isDirty);+const autoOpenDescription =INGEST_PREVIEW_AUTO_OPEN_OPTIONS.find((option) => option.value === draft.autoOpen,diff --git a/frontend/app/settings/_components/ingest-settings-section.tsx b/frontend/app/settings/_components/ingest-settings-section.tsxindex 32a91b404..3518a56dd 100644--- a/frontend/app/settings/_components/ingest-settings-section.tsx+++ b/frontend/app/settings/_components/ingest-settings-section.tsx@@ -40,6 +40,7 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { useAuth } from "@/contexts/auth-context";import { useIsCloudBrand } from "@/contexts/brand-context";+import { useRegisterDirty } from "@/contexts/unsaved-changes-context";import { trackButton } from "@/lib/analytics";import { DEFAULT_KNOWLEDGE_SETTINGS } from "@/lib/constants";import { resolveLangflowEditUrl } from "@/lib/url-utils";@@ -62,6 +63,7 @@ export function IngestSettingsSection() {const { isAuthenticated, isNoAuthMode, isIbmAuthMode, runMode } = useAuth();const [isRestoringFlow, setIsRestoringFlow] = useState<boolean>(false);+ const [userEdited, setUserEdited] = useState(false);const [chunkSize, setChunkSize] = useState<number>(1024);const [chunkOverlap, setChunkOverlap] = useState<number>(50);@@ -365,6 +367,7 @@ export function IngestSettingsSection() {]);const handleVlmModelChange = (value: string, provider?: string) => {+ setUserEdited(true);setVlmModel(value);if (provider) setVlmProvider(provider);setValidationError(null);@@ -397,6 +400,8 @@ export function IngestSettingsSection() {(k?.disable_ingest_with_langflow ?? disableIngestWithLangflow) ||vlmDirty;+ useRegisterDirty("ingest-settings", userEdited && knowledgeIngestDirty);+const providerConfigured =settings.providers === undefined || settings.providers === null? undefined@@ -421,11 +426,13 @@ export function IngestSettingsSection() {: "OpenAI";const handleChunkSizeChange = (value: string) => {+ setUserEdited(true);setChunkSize(Math.max(0, Number.parseInt(value, 10) || 0));setChunkValidationError(null);};const handleChunkOverlapChange = (value: string) => {+ setUserEdited(true);setChunkOverlap(Math.max(0, Number.parseInt(value, 10) || 0));setChunkValidationError(null);};@@ -505,6 +512,7 @@ export function IngestSettingsSection() {onSuccess: () => {setChunkValidationError(null);setValidationError(null);+ setUserEdited(false);},},);@@ -558,6 +566,7 @@ export function IngestSettingsSection() {setPictureDescriptions(DEFAULT_KNOWLEDGE_SETTINGS.picture_descriptions);setDisableIngestWithLangflow(false);setChunkValidationError(null);+ setUserEdited(false);toast.success("Default ingest flow settings restored successfully");closeDialog();})@@ -770,7 +779,10 @@ export function IngestSettingsSection() {<Switchid="disable-ingest-with-langflow"checked={disableIngestWithLangflow}- onCheckedChange={setDisableIngestWithLangflow}+ onCheckedChange={(v) => {+ setUserEdited(true);+ setDisableIngestWithLangflow(v);+ }}/></div><div className="flex items-center justify-between py-3 border-b border-border">@@ -788,7 +800,10 @@ export function IngestSettingsSection() {<Switchid="table-structure"checked={tableStructure}- onCheckedChange={setTableStructure}+ onCheckedChange={(v) => {+ setUserEdited(true);+ setTableStructure(v);+ }}/></div><div className="flex items-center justify-between py-3 border-b border-border">@@ -803,7 +818,14 @@ export function IngestSettingsSection() {Extracts text from images/PDFs. Ingest is slower when enabled.</div></div>- <Switch id="ocr" checked={ocr} onCheckedChange={setOcr} />+ <Switch+ id="ocr"+ checked={ocr}+ onCheckedChange={(v) => {+ setUserEdited(true);+ setOcr(v);+ }}+ /></div><div className="flex items-center justify-between py-3"><div className="flex-1">@@ -820,7 +842,10 @@ export function IngestSettingsSection() {<Switchid="picture-descriptions"checked={pictureDescriptions}- onCheckedChange={setPictureDescriptions}+ onCheckedChange={(v) => {+ setUserEdited(true);+ setPictureDescriptions(v);+ }}/></div>{showVlmSettings && (@@ -884,9 +909,10 @@ export function IngestSettingsSection() {type="text"placeholder={DEFAULT_WATSONX_API_VERSION}value={vlmWatsonxApiVersion}- onChange={(e) =>- setVlmWatsonxApiVersion(e.target.value)- }+ onChange={(e) => {+ setUserEdited(true);+ setVlmWatsonxApiVersion(e.target.value);+ }}disabled={!pictureDescriptions}/></LabelWrapper>@@ -903,7 +929,10 @@ export function IngestSettingsSection() {id="vlm-prompt"rows={3}value={vlmPrompt}- onChange={(e) => setVlmPrompt(e.target.value)}+ onChange={(e) => {+ setUserEdited(true);+ setVlmPrompt(e.target.value);+ }}disabled={!pictureDescriptions}/></LabelWrapper>@@ -917,7 +946,10 @@ export function IngestSettingsSection() {><Selectvalue={vlmResponseFormat}- onValueChange={setVlmResponseFormat}+ onValueChange={(v) => {+ setUserEdited(true);+ setVlmResponseFormat(v);+ }}disabled={!pictureDescriptions}><SelectTrigger@@ -945,9 +977,10 @@ export function IngestSettingsSection() {id="vlm-max-tokens"label="Max tokens per page"value={vlmMaxTokens}- onChange={(value) =>- setVlmMaxTokens(Math.max(1, value))- }+ onChange={(value) => {+ setUserEdited(true);+ setVlmMaxTokens(Math.max(1, value));+ }}unit="tokens"min={1}disabled={!pictureDescriptions}@@ -956,9 +989,10 @@ export function IngestSettingsSection() {id="vlm-concurrency"label="Concurrency"value={vlmConcurrency}- onChange={(value) =>- setVlmConcurrency(Math.max(1, value))- }+ onChange={(value) => {+ setUserEdited(true);+ setVlmConcurrency(Math.max(1, value));+ }}unit="requests"min={1}disabled={!pictureDescriptions}@@ -967,7 +1001,10 @@ export function IngestSettingsSection() {id="vlm-timeout"label="API timeout"value={vlmTimeout}- onChange={(value) => setVlmTimeout(Math.max(1, value))}+ onChange={(value) => {+ setUserEdited(true);+ setVlmTimeout(Math.max(1, value));+ }}unit="seconds"min={1}disabled={!pictureDescriptions}diff --git a/frontend/app/settings/_components/settings-nav.tsx b/frontend/app/settings/_components/settings-nav.tsxindex 746db3241..1fac551e7 100644--- a/frontend/app/settings/_components/settings-nav.tsx+++ b/frontend/app/settings/_components/settings-nav.tsx@@ -15,10 +15,7 @@ import { cn } from "@/lib/utils";const TABS = [{ value: "connectors", label: "Connectors" },{ value: "providers", label: "Providers", perm: "providers:write" },- // Knowledge ingest settings write workspace config (admin-only).- // Preview controls on this tab stay gated by isIngestPreviewEnabled.{ value: "ingestion", label: "Ingestion", perm: "config:write" },- // Agent settings write workspace config (admin-only).{ value: "agent", label: "Agent", perm: "config:write" },{ value: "api-keys", label: "API Keys", apiKeysTab: true },{diff --git a/frontend/app/settings/_components/settings-shell.tsx b/frontend/app/settings/_components/settings-shell.tsxindex 02e945132..5dbe7e1ab 100644--- a/frontend/app/settings/_components/settings-shell.tsx+++ b/frontend/app/settings/_components/settings-shell.tsx@@ -3,6 +3,7 @@import { useIsCloudBrand } from "@/contexts/brand-context";import { cn } from "@/lib/utils";import { SettingsNav } from "./settings-nav";+import { UnsavedChangesDialog } from "./unsaved-changes-dialog";export function SettingsShell({ children }: { children: React.ReactNode }) {const isCloudBrand = useIsCloudBrand();@@ -23,6 +24,7 @@ export function SettingsShell({ children }: { children: React.ReactNode }) {</h2><SettingsNav />{children}+ <UnsavedChangesDialog /></div>);}diff --git a/frontend/app/settings/_components/unsaved-changes-dialog.tsx b/frontend/app/settings/_components/unsaved-changes-dialog.tsxnew file mode 100644index 000000000..2ae3b6312--- /dev/null+++ b/frontend/app/settings/_components/unsaved-changes-dialog.tsx@@ -0,0 +1,37 @@+"use client";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { useUnsavedChangesGuard } from "@/contexts/unsaved-changes-context";++export function UnsavedChangesDialog() {+ const { showDialog, confirmLeave, cancelLeave } = useUnsavedChangesGuard();++ return (+ <Dialog open={showDialog} onOpenChange={(open) => !open && cancelLeave()}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle className="mb-4">Unsaved changes</DialogTitle>+ <DialogDescription className="text-left">+ You have unsaved changes that will be lost if you leave this page.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="ghost" onClick={cancelLeave} size="sm">+ Stay+ </Button>+ <Button variant="destructive" onClick={confirmLeave} size="sm">+ Leave+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/components/user-nav.tsx b/frontend/components/user-nav.tsxindex 539b8c5e4..e72f4e62a 100644--- a/frontend/components/user-nav.tsx+++ b/frontend/components/user-nav.tsx@@ -12,6 +12,7 @@ import {} from "@/components/ui/dropdown-menu";import { useAuth } from "@/contexts/auth-context";import { useIsCloudBrand } from "@/contexts/brand-context";+import { useUnsavedChangesGuard } from "@/contexts/unsaved-changes-context";import { cn } from "@/lib/utils";import ThemeButtons from "./theme-switcher-buttons";@@ -26,8 +27,22 @@ export function UserNav() {logout,version,} = useAuth();+ const { guardNavigation } = useUnsavedChangesGuard();const { theme, setTheme } = useTheme();+ const performLogout = async () => {+ if (isCloudBrand) {+ try {+ await fetch("/api/auth/logout", { method: "POST" });+ } catch {+ // Best-effort server cleanup; redirect regardless.+ }+ window.location.href = "/logout";+ return;+ }+ await logout();+ };+if (isLoading) {return <div className="h-8 w-8 rounded-full bg-muted animate-pulse" />;}@@ -131,13 +146,10 @@ export function UserNav() {<DropdownMenuSeparator className="m-0" /><buttontype="button"- onClick={async () => {- if (isCloudBrand) {- fetch("/api/auth/logout", { method: "POST" });- window.location.href = "/logout";- return;+ onClick={() => {+ if (guardNavigation("/logout", performLogout)) {+ void performLogout();}- await logout();}}className="flex items-center hover:bg-muted w-full h-9 px-3">diff --git a/frontend/contexts/unsaved-changes-context.tsx b/frontend/contexts/unsaved-changes-context.tsxnew file mode 100644index 000000000..e051398c4--- /dev/null+++ b/frontend/contexts/unsaved-changes-context.tsx@@ -0,0 +1,251 @@+"use client";++import { useRouter } from "next/navigation";+import {+ createContext,+ type ReactNode,+ use,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { getInterceptedNavigationHref } from "@/lib/navigation-events";++type NavigationAction = () => void | Promise<void>;++type PendingNavigation =+ | { type: "href"; href: string }+ | { type: "action"; action: NavigationAction }+ | { type: "history"; delta: number };++interface UnsavedChangesContextValue {+ register: (key: string, isDirty: boolean) => void;+ unregister: (key: string) => void;+ hasUnsavedChanges: boolean;+ guardNavigation: (href: string, action?: NavigationAction) => boolean;+ showDialog: boolean;+ confirmLeave: () => void;+ cancelLeave: () => void;+}++const UnsavedChangesContext = createContext<UnsavedChangesContextValue | null>(+ null,+);++export function UnsavedChangesProvider({ children }: { children: ReactNode }) {+ const router = useRouter();+ const [dirtyMap, setDirtyMap] = useState<Record<string, boolean>>({});+ const [pendingNavigation, setPendingNavigation] =+ useState<PendingNavigation | null>(null);++ const register = useCallback((key: string, isDirty: boolean) => {+ setDirtyMap((prev) => {+ if (prev[key] === isDirty) return prev;+ return { ...prev, [key]: isDirty };+ });+ }, []);++ const unregister = useCallback((key: string) => {+ setDirtyMap((prev) => {+ if (!(key in prev)) return prev;+ const next = { ...prev };+ delete next[key];+ return next;+ });+ }, []);++ const hasUnsavedChanges = Object.values(dirtyMap).some(Boolean);+ const hasUnsavedRef = useRef(hasUnsavedChanges);++ useEffect(() => {+ hasUnsavedRef.current = hasUnsavedChanges;+ }, [hasUnsavedChanges]);++ useEffect(() => {+ if (!hasUnsavedChanges) return;+ const handler = (e: BeforeUnloadEvent) => {+ e.preventDefault();+ };+ window.addEventListener("beforeunload", handler);+ return () => window.removeEventListener("beforeunload", handler);+ }, [hasUnsavedChanges]);++ useEffect(() => {+ const handler = (e: MouseEvent) => {+ if (!hasUnsavedRef.current) return;+ const anchor = (e.target as HTMLElement).closest("a");+ if (!anchor) return;+ const href = anchor.getAttribute("href");+ if (!href) return;+ const interceptedHref = getInterceptedNavigationHref({+ button: e.button,+ href,+ currentHref: window.location.href,+ target: anchor.target,+ download: anchor.hasAttribute("download"),+ metaKey: e.metaKey,+ ctrlKey: e.ctrlKey,+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ });+ if (!interceptedHref) return;++ e.preventDefault();+ e.stopPropagation();+ setPendingNavigation({ type: "href", href: interceptedHref });+ };+ document.addEventListener("click", handler, true);+ return () => document.removeEventListener("click", handler, true);+ }, []);++ const hasHistorySentinelRef = useRef(false);+ const restoringHistoryRef = useRef(false);+ const confirmedActionRef = useRef<NavigationAction | null>(null);++ useEffect(() => {+ if (hasUnsavedChanges && !hasHistorySentinelRef.current) {+ window.history.pushState(window.history.state, "", window.location.href);+ hasHistorySentinelRef.current = true;+ return;+ }++ if (!hasUnsavedChanges && hasHistorySentinelRef.current) {+ restoringHistoryRef.current = true;+ hasHistorySentinelRef.current = false;+ window.history.back();+ }+ }, [hasUnsavedChanges]);++ useEffect(() => {+ const handler = (e: PopStateEvent) => {+ if (confirmedActionRef.current) {+ e.stopImmediatePropagation();+ const action = confirmedActionRef.current;+ confirmedActionRef.current = null;+ void action();+ return;+ }++ if (restoringHistoryRef.current) {+ e.stopImmediatePropagation();+ restoringHistoryRef.current = false;+ return;+ }++ if (!hasUnsavedRef.current) return;++ e.stopImmediatePropagation();+ setPendingNavigation({ type: "history", delta: -2 });+ restoringHistoryRef.current = true;+ window.history.forward();+ };++ window.addEventListener("popstate", handler, true);+ return () => window.removeEventListener("popstate", handler, true);+ }, []);++ const guardNavigation = useCallback(+ (href: string, action?: NavigationAction): boolean => {+ if (!hasUnsavedChanges) return true;+ setPendingNavigation(+ action ? { type: "action", action } : { type: "href", href },+ );+ return false;+ },+ [hasUnsavedChanges],+ );++ const confirmLeave = useCallback(() => {+ if (!pendingNavigation) return;++ setPendingNavigation(null);+ hasUnsavedRef.current = false;++ if (pendingNavigation.type === "history") {+ hasHistorySentinelRef.current = false;+ window.history.go(pendingNavigation.delta);+ return;+ }++ const action =+ pendingNavigation.type === "action"+ ? pendingNavigation.action+ : () => router.push(pendingNavigation.href);++ if (hasHistorySentinelRef.current) {+ hasHistorySentinelRef.current = false;+ confirmedActionRef.current = action;+ window.history.back();+ return;+ }++ void action();+ }, [pendingNavigation, router]);++ const cancelLeave = useCallback(() => {+ setPendingNavigation(null);+ }, []);++ const value = useMemo<UnsavedChangesContextValue>(+ () => ({+ register,+ unregister,+ hasUnsavedChanges,+ guardNavigation,+ showDialog: pendingNavigation !== null,+ confirmLeave,+ cancelLeave,+ }),+ [+ register,+ unregister,+ hasUnsavedChanges,+ guardNavigation,+ pendingNavigation,+ confirmLeave,+ cancelLeave,+ ],+ );++ return (+ <UnsavedChangesContext.Provider value={value}>+ {children}+ </UnsavedChangesContext.Provider>+ );+}++export function useRegisterDirty(key: string, isDirty: boolean) {+ const ctx = use(UnsavedChangesContext);+ if (!ctx) {+ throw new Error(+ "useRegisterDirty must be used within UnsavedChangesProvider",+ );+ }++ const { register, unregister } = ctx;++ useEffect(() => {+ register(key, isDirty);+ }, [key, isDirty, register]);++ useEffect(() => {+ return () => unregister(key);+ }, [key, unregister]);+}++export function useUnsavedChangesGuard() {+ const ctx = use(UnsavedChangesContext);+ if (!ctx) {+ throw new Error(+ "useUnsavedChangesGuard must be used within UnsavedChangesProvider",+ );+ }+ return {+ guardNavigation: ctx.guardNavigation,+ showDialog: ctx.showDialog,+ confirmLeave: ctx.confirmLeave,+ cancelLeave: ctx.cancelLeave,+ };+}diff --git a/frontend/lib/navigation-events.test.ts b/frontend/lib/navigation-events.test.tsnew file mode 100644index 000000000..89997f318--- /dev/null+++ b/frontend/lib/navigation-events.test.ts@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { describe, it } from "node:test";+// Node's built-in TypeScript runner requires the extension; tsc resolves the same source.+// @ts-expect-error TS5097+import { getInterceptedNavigationHref } from "./navigation-events.ts";++const currentHref = "http://localhost:3000/settings/agent";++describe("getInterceptedNavigationHref", () => {+ it("intercepts an ordinary click to the settings index", () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: "/settings",+ currentHref,+ }),+ "/settings",+ );+ });++ it("intercepts an ordinary click to another settings tab", () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: "/settings/ingestion",+ currentHref,+ }),+ "/settings/ingestion",+ );+ });++ for (const modifier of [+ "metaKey",+ "ctrlKey",+ "shiftKey",+ "altKey",+ ] as const) {+ it(`preserves clicks using ${modifier}`, () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: "/settings/ingestion",+ currentHref,+ [modifier]: true,+ }),+ null,+ );+ });+ }++ it("preserves middle clicks", () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 1,+ href: "/settings/ingestion",+ currentHref,+ }),+ null,+ );+ });++ it("preserves links that open a new browsing context", () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: "/settings/ingestion",+ currentHref,+ target: "_blank",+ }),+ null,+ );+ });++ it("leaves external and same-document links to the browser", () => {+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: "https://example.com/settings",+ currentHref,+ }),+ null,+ );+ assert.equal(+ getInterceptedNavigationHref({+ button: 0,+ href: `${currentHref}#agent-card`,+ currentHref,+ }),+ null,+ );+ });+});diff --git a/frontend/lib/navigation-events.ts b/frontend/lib/navigation-events.tsnew file mode 100644index 000000000..cf66607c5--- /dev/null+++ b/frontend/lib/navigation-events.ts@@ -0,0 +1,47 @@+interface NavigationClick {+ button: number;+ href: string;+ currentHref: string;+ target?: string;+ download?: boolean;+ metaKey?: boolean;+ ctrlKey?: boolean;+ shiftKey?: boolean;+ altKey?: boolean;+}++export function getInterceptedNavigationHref({+ button,+ href,+ currentHref,+ target,+ download,+ metaKey,+ ctrlKey,+ shiftKey,+ altKey,+}: NavigationClick): string | null {+ if (+ button !== 0 ||+ metaKey ||+ ctrlKey ||+ shiftKey ||+ altKey ||+ (target && target.toLowerCase() !== "_self") ||+ download+ ) {+ return null;+ }++ const currentUrl = new URL(currentHref);+ const destinationUrl = new URL(href, currentUrl);+ if (+ destinationUrl.origin !== currentUrl.origin ||+ (destinationUrl.pathname === currentUrl.pathname &&+ destinationUrl.search === currentUrl.search)+ ) {+ return null;+ }++ return `${destinationUrl.pathname}${destinationUrl.search}${destinationUrl.hash}`;+}diff --git a/frontend/tests/core/unsaved-changes.spec.ts b/frontend/tests/core/unsaved-changes.spec.tsnew file mode 100644index 000000000..f6584ba12--- /dev/null+++ b/frontend/tests/core/unsaved-changes.spec.ts@@ -0,0 +1,55 @@+import { expect, type Page, test } from "@playwright/test";+import { navigateToApp } from "../utils/navigation";++async function makeAgentSettingsDirty(page: Page) {+ await navigateToApp(page, "/settings/agent");+ const instructions = page.getByLabel("Agent Instructions");+ await expect(instructions).toBeVisible({ timeout: 60000 });+ await instructions.fill(`${await instructions.inputValue()} unsaved`);+}++test.describe("unsaved settings navigation", () => {+ test("guards the sidebar Settings link", async ({ page }) => {+ await makeAgentSettingsDirty(page);++ await page.getByRole("link", { name: "Settings", exact: true }).click();++ await expect(+ page.getByRole("heading", { name: "Unsaved changes" }),+ ).toBeVisible();+ await expect(page).toHaveURL(/\/settings\/agent$/);+ await page.getByRole("button", { name: "Stay" }).click();+ await expect(page).toHaveURL(/\/settings\/agent$/);+ });++ test("guards browser Back navigation", async ({ page }) => {+ await page.goto("/chat");+ await makeAgentSettingsDirty(page);++ await page.goBack({ waitUntil: "commit" });++ await expect(+ page.getByRole("heading", { name: "Unsaved changes" }),+ ).toBeVisible();+ await expect(page).toHaveURL(/\/settings\/agent$/);+ await page.getByRole("button", { name: "Stay" }).click();+ });++ test("does not cancel middle clicks on settings tabs", async ({ page }) => {+ await navigateToApp(page, "/settings/agent");+ const wasNotCancelled = await page+ .getByRole("tab", { name: "Ingestion" })+ .evaluate((tab) =>+ tab.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ button: 1,+ cancelable: true,+ }),+ ),+ );++ expect(wasNotCancelled).toBe(true);+ await expect(page).toHaveURL(/\/settings\/agent$/);+ });+});