Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor(frontend): purge WHAT-only comments across the codebase
Sergey Kozyrenkoe97b29b31f11
diff --git a/frontend/src/components/layouts/settings-layout.tsx b/frontend/src/components/layouts/settings-layout.tsxindex f4742216..55221d13 100644--- a/frontend/src/components/layouts/settings-layout.tsx+++ b/frontend/src/components/layouts/settings-layout.tsx@@ -18,7 +18,6 @@ import {SidebarTrigger,} from '@/components/ui/sidebar';-// Typesexport interface MenuItem {icon?: React.ReactNode;id: string;@@ -31,7 +30,6 @@ interface SettingsSidebarMenuItemProps {item: MenuItem;}-// Settings menu items definitionconst menuItems: readonly MenuItem[] = [{icon: <Plug className="size-4" />,@@ -53,16 +51,13 @@ const menuItems: readonly MenuItem[] = [},] as const;-// Settings header componentfunction SettingsHeader() {const location = useLocation();const params = useParams();- // Memoize title calculation for better performanceconst title = useMemo(() => {const path = location.pathname;- // Check for specific nested routesif (path === '/settings/providers/new') {return 'Create Provider';}@@ -83,7 +78,6 @@ function SettingsHeader() {return 'PentAGI API';}- // Find matching main sectionconst activeItem = menuItems.find((item) => path.startsWith(item.path));return activeItem?.title ?? 'Settings';@@ -101,7 +95,6 @@ function SettingsHeader() {);}-// Settings layout componentfunction SettingsLayout() {return (<SidebarProvider>@@ -109,7 +102,6 @@ function SettingsLayout() {<SettingsSidebar /><SidebarInset className="flex flex-1 flex-col"><SettingsHeader />- {/* Content area for nested routes */}<main className="min-h-0 flex-1 overflow-auto p-4"><Outlet /></main>@@ -119,7 +111,6 @@ function SettingsLayout() {);}-// Settings sidebar componentfunction SettingsSidebar() {return (<Sidebar collapsible="icon">@@ -161,10 +152,8 @@ function SettingsSidebar() {);}-// Individual menu item component to properly use hooksfunction SettingsSidebarMenuItem({ item }: SettingsSidebarMenuItemProps) {const location = useLocation();- // Check if current path starts with item path (for nested routes)const isActive = location.pathname.startsWith(item.path);return (diff --git a/frontend/src/components/routes/protected-route.tsx b/frontend/src/components/routes/protected-route.tsxindex 5d64ee94..67c2c70e 100644--- a/frontend/src/components/routes/protected-route.tsx+++ b/frontend/src/components/routes/protected-route.tsx@@ -8,7 +8,6 @@ function ProtectedRoute({ children }: { children: React.ReactNode }) {const location = useLocation();const { isAuthenticated, isLoading } = useUser();- // Wait for initial auth check to completeif (isLoading) {return null;}diff --git a/frontend/src/components/routes/public-route.tsx b/frontend/src/components/routes/public-route.tsxindex e9fa02bf..2b19b33d 100644--- a/frontend/src/components/routes/public-route.tsx+++ b/frontend/src/components/routes/public-route.tsx@@ -8,7 +8,6 @@ function PublicRoute({ children }: { children: React.ReactNode }) {const [searchParams] = useSearchParams();const { authInfo, isAuthenticated, isLoading } = useUser();- // Wait for initial auth check to completeif (isLoading) {return null;}diff --git a/frontend/src/components/shared/file-manager/file-manager.tsx b/frontend/src/components/shared/file-manager/file-manager.tsxindex bfc700bd..f7b217e2 100644--- a/frontend/src/components/shared/file-manager/file-manager.tsx+++ b/frontend/src/components/shared/file-manager/file-manager.tsx@@ -294,7 +294,6 @@ export function FileManager({const stableHandleOpenDirectory = onOpenDirectory ? handleOpenDirectory : undefined;- // ── roving tabindex / keyboard navigation ────────────────────────────────const [activeRowPath, setActiveRowPath] = useState<null | string>(null);const containerRef = useRef<HTMLDivElement | null>(null);diff --git a/frontend/src/components/shared/file-manager/use-file-manager-dnd.ts b/frontend/src/components/shared/file-manager/use-file-manager-dnd.tsindex 356f0da8..1146a0aa 100644--- a/frontend/src/components/shared/file-manager/use-file-manager-dnd.ts+++ b/frontend/src/components/shared/file-manager/use-file-manager-dnd.ts@@ -255,8 +255,6 @@ export function useFileManagerDnd({setDraggingPaths(new Set());}, []);- // ── per-node handlers ───────────────────────────────────────────────────────-const handleNodeDragStart = useCallback((node: FileManagerInternalNode, event: ReactDragEvent<HTMLDivElement>): void => {if (!isEnabled || node.isGroupRoot) {@@ -624,8 +622,6 @@ export function useFileManagerDnd({],);- // ── container-level handlers (root drop area) ───────────────────────────────-const handleContainerDragEnter = useCallback((event: ReactDragEvent<HTMLDivElement>): void => {if (!isEnabled || !isFmDragEvent(event)) {diff --git a/frontend/src/components/shared/markdown.tsx b/frontend/src/components/shared/markdown.tsxindex 3589f605..4d02fa14 100644--- a/frontend/src/components/shared/markdown.tsx+++ b/frontend/src/components/shared/markdown.tsx@@ -52,7 +52,6 @@ interface MarkdownProps {searchValue?: string;}-// List of all elements that should have text highlightingconst textElements = ['p','span',@@ -91,13 +90,11 @@ const textElements = ['dd',];-// Function to escape special regex charactersconst escapeRegExp = (string: string): string => {return string.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');};function Markdown({ children, className, searchValue }: MarkdownProps) {- // Memoize the escaped search value to avoid recalculating regexconst processedSearch = useMemo(() => {const trimmedSearch = searchValue?.trim();@@ -112,7 +109,6 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {};}, [searchValue]);- // Function to create highlighted text components with subtle highlightingconst createHighlightedText = useCallback((text: string) => {if (!processedSearch) {@@ -122,13 +118,11 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {const parts = text.split(processedSearch.regex);return parts.map((part, index) => {- // Use case-insensitive comparison to match the filtering logicif (part.toLowerCase() === processedSearch.trimmed.toLowerCase()) {return (<spankey={`highlight-${index}`}style={{- // Much more subtle highlighting - very pale yellow with slight borderbackgroundColor: 'rgba(255, 255, 0, 0.15)',borderRadius: '2px',boxShadow: 'inset 0 0 0 1px rgba(255, 255, 0, 0.25)',@@ -146,7 +140,6 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {[processedSearch],);- // Optimized helper function to process text nodes recursivelyconst processTextNode = useMemo(() => {const fn = (nodeChildren: any): any => {if (!processedSearch) {@@ -199,7 +192,6 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {return fn;}, [processedSearch, createHighlightedText]);- // Create a simple component renderer factory to avoid recreating functionsconst createComponentRenderer = useCallback((ComponentName: string) => {const Component = ComponentName as React.ElementType;@@ -217,17 +209,16 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {[processTextNode],);- // Memoize components to avoid recreating them on every renderconst customComponents = useMemo(() => {const components: Record<string, any> = {};if (processedSearch) {- // Create components for all text elements using the factorytextElements.forEach((element) => {components[element] = createComponentRenderer(element);});- // Don't highlight inside code blocks and preserve their content+ // Code blocks pass through untouched — highlighting injected `<span>`s into a `<code>`+ // breaks rehype-highlight's tokenization and the rendered listing.components.code = ({ children: nodeChildren, ...props }: any) => {return <code {...props}>{nodeChildren}</code>;};diff --git a/frontend/src/components/shared/monaco-terminal.tsx b/frontend/src/components/shared/monaco-terminal.tsxindex 7eb26822..08d1458a 100644--- a/frontend/src/components/shared/monaco-terminal.tsx+++ b/frontend/src/components/shared/monaco-terminal.tsx@@ -281,19 +281,15 @@ function MonacoTerminal({const searchWidgetRef = useRef<null | { findNext: () => void; findPrevious: () => void }>(null);const decorationsCollectionRef = useRef<monaco.editor.IEditorDecorationsCollection | null>(null);- // Parse ANSI codes from logs with module-level cachingconst parsedContent = useMemo(() => parseLogsWithCache(logs), [logs]);- // Memoized plain text content extractionconst content = useMemo(() => parsedContent.map((line) => line.text).join('\n'), [parsedContent]);- // Monaco editor mount handler - wrapped in useCallback for stabilityconst handleEditorDidMount: OnMount = useCallback((editor, monacoInstance) => {editorRef.current = editor;monacoRef.current = monacoInstance;setIsEditorReady(true);- // Configure editor for optimal performance and word wrappingeditor.updateOptions({automaticLayout: true,folding: false,@@ -321,7 +317,6 @@ function MonacoTerminal({wrappingStrategy: 'simple', // Use simple strategy for better performance});- // Inject ANSI decoration CSS styles once (static set of classes)const ansiStyleId = 'monaco-terminal-ansi-styles';if (!document.getElementById(ansiStyleId)) {@@ -332,7 +327,6 @@ function MonacoTerminal({document.head.appendChild(ansiStyleElement);}- // Inject padding and background stylesconst terminalStyleId = 'monaco-terminal-custom-styles';if (!document.getElementById(terminalStyleId)) {@@ -352,7 +346,6 @@ function MonacoTerminal({document.head.appendChild(terminalStyleElement);}- // Store search widget referencesearchWidgetRef.current = {findNext: () => {try {@@ -373,7 +366,6 @@ function MonacoTerminal({};}, []);- // Expose methods to parent component via refuseImperativeHandle(ref,() => ({@@ -391,10 +383,8 @@ function MonacoTerminal({[],);- // Cache for tracking which lines have been decoratedconst decoratedLinesCountRef = useRef<number>(0);- // Apply ANSI color decorations incrementallyuseEffect(() => {if (!isEditorReady || !editorRef.current || !monacoRef.current) {return;@@ -406,7 +396,6 @@ function MonacoTerminal({try {const decoratedCount = decoratedLinesCountRef.current;- // If content was cleared or reduced, reset decorationsif (parsedContent.length < decoratedCount) {if (decorationsCollectionRef.current) {decorationsCollectionRef.current.clear();@@ -415,12 +404,13 @@ function MonacoTerminal({decoratedLinesCountRef.current = 0;}- // If no new lines to decorate, skipif (parsedContent.length <= decoratedLinesCountRef.current) {return;}- // Build decorations only for new lines (incremental)+ // Incremental: only decorate the tail of `parsedContent` past `decoratedLinesCountRef`.+ // Re-applying the full set on every log append turns large terminals into a stutter+ // because Monaco re-runs the decoration delta over every line.const newDecorations: monaco.editor.IModelDeltaDecoration[] = [];for (let index = decoratedLinesCountRef.current; index < parsedContent.length; index++) {@@ -445,25 +435,20 @@ function MonacoTerminal({}}- // Apply new decorations incrementallyif (newDecorations.length) {if (decorationsCollectionRef.current) {- // Append new decorations to existing collectiondecorationsCollectionRef.current.append(newDecorations);} else {- // Create new collection if it doesn't existdecorationsCollectionRef.current = editor.createDecorationsCollection(newDecorations);}}- // Update decorated lines countdecoratedLinesCountRef.current = parsedContent.length;} catch (error: unknown) {Log.error('Monaco apply decorations failed:', error);}}, [parsedContent, isEditorReady]);- // Auto-scroll to bottom when new logs are addeduseEffect(() => {if (!isEditorReady || !editorRef.current) {return;@@ -471,13 +456,13 @@ function MonacoTerminal({const editor = editorRef.current;- // Only scroll if new logs were added (not on initial render or when logs were cleared)+ // Auto-scroll only on appends — not on the initial mount (`prev === 0`) and not when logs+ // shrink (cleared), so we don't fight a user who scrolled up before more output arrives.if (logs.length > prevLogsLengthRef.current && prevLogsLengthRef.current > 0) {try {const lineCount = editor.getModel()?.getLineCount() ?? 0;if (lineCount > 0) {- // Scroll to the last line (1 = Smooth scroll type)editor.revealLine(lineCount, 1);}} catch (error: unknown) {@@ -488,7 +473,6 @@ function MonacoTerminal({prevLogsLengthRef.current = logs.length;}, [logs, isEditorReady]);- // Handle search functionalityuseEffect(() => {if (!isEditorReady || !editorRef.current || !monacoRef.current) {return;@@ -498,10 +482,8 @@ function MonacoTerminal({if (searchValue?.trim()) {try {- // Use Monaco's built-in find functionalityconst searchText = searchValue.trim();- // Create find optionsconst findOptions = {isRegex: false,matchCase: false,@@ -510,11 +492,10 @@ function MonacoTerminal({wholeWord: false,};- // Trigger find action with the search stringeditor.trigger('monaco-terminal', 'actions.find', findOptions);- // Automatically jump to first match using requestAnimationFrame- // for better timing than arbitrary setTimeout delays+ // rAF (instead of setTimeout) lets Monaco finish mounting the find widget before+ // we issue the jump-to-first-match — fewer flaky races at log-bursty moments.requestAnimationFrame(() => {editor.trigger('monaco-terminal', 'editor.action.nextMatchFindAction', {});});@@ -522,7 +503,6 @@ function MonacoTerminal({Log.error('Monaco search failed:', error);}} else {- // Close find widget when search is clearedtry {editor.trigger('monaco-terminal', 'closeFindWidget', {});} catch (error: unknown) {@@ -531,20 +511,17 @@ function MonacoTerminal({}}, [searchValue, isEditorReady]);- // Cleanup on unmountuseEffect(() => {return () => {- // Clear decorations collectionif (decorationsCollectionRef.current) {decorationsCollectionRef.current.clear();decorationsCollectionRef.current = null;}- // Reset incremental decorations counterdecoratedLinesCountRef.current = 0;- // Note: We don't remove shared styles as they persist across instances- // parsedLogsCache uses WeakMap so it's automatically cleaned up+ // Shared <style> tags are deliberately left attached — multiple instances share them+ // and the WeakMap-backed parseLogsWithCache cleans itself up.};}, []);diff --git a/frontend/src/components/ui/input-group.tsx b/frontend/src/components/ui/input-group.tsxindex 6b4a1044..70d04372 100644--- a/frontend/src/components/ui/input-group.tsx+++ b/frontend/src/components/ui/input-group.tsx@@ -14,16 +14,13 @@ function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {'group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-2xs outline-hidden transition-[color,box-shadow]','h-9 has-[>textarea]:h-auto',- // Variants based on alignment.'[&>input]:has-[>[data-align=inline-start]]:pl-2','[&>input]:has-[>[data-align=inline-end]]:pr-2','has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col [&>input]:has-[>[data-align=block-start]]:pb-3','has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col [&>input]:has-[>[data-align=block-end]]:pt-3',- // Focus state.'has-[[data-slot=input-group-control]:focus-visible]:ring-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1',- // Error state.'has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40',className,diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsxindex 30774578..5e672f75 100644--- a/frontend/src/components/ui/input.tsx+++ b/frontend/src/components/ui/input.tsx@@ -9,7 +9,6 @@ function Input({ className, type, ...props }: InputProps) {<inputclassName={cn('border-input dark:bg-input/30 file:text-foreground placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-sm shadow-xs transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-1 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50',- // Hide spinner arrows for number inputstype === 'number' &&'[appearance:textfield] [&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none',className,diff --git a/frontend/src/components/ui/sidebar.tsx b/frontend/src/components/ui/sidebar.tsxindex efe1c335..4feefbbb 100644--- a/frontend/src/components/ui/sidebar.tsx+++ b/frontend/src/components/ui/sidebar.tsx@@ -43,7 +43,6 @@ function useSidebar() {return context;}-// Helper function to read sidebar state from cookiesconst getSidebarState = (): boolean | undefined => {if (typeof document === 'undefined') {return undefined;@@ -143,7 +142,6 @@ function Sidebar({side === 'left'? 'left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]': 'right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]',- // Adjust the padding for floating and inset variants.variant === 'floating' || variant === 'inset'? 'p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]': 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',@@ -206,7 +204,6 @@ function SidebarGroupAction({<CompclassName={cn('text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',- // Increases the hit area of the button on mobile.'after:absolute after:-inset-2 md:after:hidden','group-data-[collapsible=icon]:hidden',className,@@ -341,13 +338,11 @@ function SidebarProvider({_setOpen(openState);}- // This sets the cookie to keep the sidebar state.document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;},[setOpenProp, open],);- // Helper to toggle the sidebar.const toggleSidebar = React.useCallback(() => {return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);}, [isMobile, setOpen, setOpenMobile]);@@ -514,7 +509,6 @@ function SidebarMenuAction({<CompclassName={cn('text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',- // Increases the hit area of the button on mobile.'after:absolute after:-inset-2 md:after:hidden','peer-data-[size=sm]/menu-button:top-1','peer-data-[size=default]/menu-button:top-1.5',@@ -627,7 +621,6 @@ function SidebarMenuSkeleton({}: React.ComponentProps<'div'> & {showIcon?: boolean;}) {- // Random width between 50 to 90%.const [width] = React.useState(() => `${Math.floor(Math.random() * 40) + 50}%`);return (diff --git a/frontend/src/features/authentication/login-form.tsx b/frontend/src/features/authentication/login-form.tsxindex 7bbb2ea2..16ae3bb7 100644--- a/frontend/src/features/authentication/login-form.tsx+++ b/frontend/src/features/authentication/login-form.tsx@@ -125,7 +125,6 @@ function LoginForm({ providers, returnUrl = '/flows/new' }: LoginFormProps) {const handlePasswordChangeSuccess = () => {if (authInfo?.user) {- // Update auth info with password_change_required set to falseconst updatedAuthData = {...authInfo,user: {diff --git a/frontend/src/features/flows/agents/flow-agent.tsx b/frontend/src/features/flows/agents/flow-agent.tsxindex f0e97764..043c8d76 100644--- a/frontend/src/features/flows/agents/flow-agent.tsx+++ b/frontend/src/features/flows/agents/flow-agent.tsx@@ -17,7 +17,6 @@ interface FlowAgentProps {searchValue?: string;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -29,7 +28,6 @@ const containsSearchValue = (text: null | string | undefined, searchValue: strinfunction FlowAgent({ log, searchValue = '' }: FlowAgentProps) {const { createdAt, executor, initiator, result, subtaskId, task, taskId } = log;- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();@@ -63,13 +61,9 @@ function FlowAgent({ log, searchValue = '' }: FlowAgentProps) {}}- // Determine if we should show full task or preview- // Show full task if: search found in task OR details are manually visible OR task is shortconst shouldShowFullTask = searchChecks.hasTaskMatch || isDetailsVisible || task.length <= taskPreviewLength;const taskToShow = shouldShowFullTask ? task : `${task.slice(0, taskPreviewLength)}...`;- // Determine if we should show details toggle- // Show toggle if: result exists OR task is longer than preview lengthconst shouldShowDetailsToggle = result || task.length > taskPreviewLength;const handleCopy = useCallback(async () => {diff --git a/frontend/src/features/flows/agents/flow-agents.tsx b/frontend/src/features/flows/agents/flow-agents.tsxindex 0216b367..6951d706 100644--- a/frontend/src/features/flows/agents/flow-agents.tsx+++ b/frontend/src/features/flows/agents/flow-agents.tsx@@ -47,7 +47,6 @@ function FlowAgents() {const searchValue = form.watch('search');const filter = form.watch('filter');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -56,7 +55,6 @@ function FlowAgents() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -65,14 +63,12 @@ function FlowAgents() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({filter: {@@ -85,7 +81,6 @@ function FlowAgents() {debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Check if any filters are activeconst hasActiveFilters = useMemo(() => {const hasSearch = !!searchValue.trim();const hasTaskFilters = !!(filter?.taskIds?.length || filter?.subtaskIds?.length);@@ -93,14 +88,11 @@ function FlowAgents() {return hasSearch || hasTaskFilters;}, [searchValue, filter]);- // Memoize filtered logs to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredLogs = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();let filtered = logs || [];- // Filter by searchif (search) {filtered = filtered.filter((log) => {return (@@ -112,7 +104,6 @@ function FlowAgents() {});}- // Filter by selected tasks and subtasksif (filter?.taskIds?.length || filter?.subtaskIds?.length) {const selectedTaskIds = new Set(filter.taskIds ?? []);const selectedSubtaskIds = new Set(filter.subtaskIds ?? []);@@ -135,7 +126,6 @@ function FlowAgents() {const hasLogs = filteredLogs && filteredLogs.length > 0;- // Reset filters handlerconst handleResetFilters = () => {form.reset({filter: {diff --git a/frontend/src/features/flows/flow-form.tsx b/frontend/src/features/flows/flow-form.tsxindex f52d0414..cea0edce 100644--- a/frontend/src/features/flows/flow-form.tsx+++ b/frontend/src/features/flows/flow-form.tsx@@ -210,7 +210,6 @@ export function FlowForm({},});- // Update form values from defaultValues if user hasn't manually changed themuseEffect(() => {if (!defaultValues) {return;diff --git a/frontend/src/features/flows/flow-tabs.tsx b/frontend/src/features/flows/flow-tabs.tsxindex e910d559..e2ea4c03 100644--- a/frontend/src/features/flows/flow-tabs.tsx+++ b/frontend/src/features/flows/flow-tabs.tsx@@ -25,7 +25,6 @@ function FlowTabs({ activeTab, onTabChange }: FlowTabsProps) {const previousActiveTabRef = useRef<string>(activeTab);useEffect(() => {- // Only handle actual tab changesif (activeTab === previousActiveTabRef.current) {return;}diff --git a/frontend/src/features/flows/flow-tasks-dropdown.tsx b/frontend/src/features/flows/flow-tasks-dropdown.tsxindex cf338273..85874625 100644--- a/frontend/src/features/flows/flow-tasks-dropdown.tsx+++ b/frontend/src/features/flows/flow-tasks-dropdown.tsx@@ -35,10 +35,8 @@ function FlowTasksDropdown({ disabled, onChange, value }: FlowTasksDropdownPropsconst taskIds = useMemo(() => new Set(value?.taskIds ?? []), [value?.taskIds]);const subtaskIds = useMemo(() => new Set(value?.subtaskIds ?? []), [value?.subtaskIds]);- // Check if any filter is activeconst hasActiveFilters = taskIds.size > 0 || subtaskIds.size > 0;- // Toggle task expansionconst toggleTaskExpansion = (taskId: string) => {setExpandedTaskIds((prev) => {const newSet = new Set(prev);@@ -53,7 +51,6 @@ function FlowTasksDropdown({ disabled, onChange, value }: FlowTasksDropdownProps});};- // Toggle task selectionconst toggleTaskSelection = (taskId: string) => {if (!onChange) {return;@@ -71,7 +68,6 @@ function FlowTasksDropdown({ disabled, onChange, value }: FlowTasksDropdownProps});};- // Toggle subtask selectionconst toggleSubtaskSelection = (subtaskId: string) => {if (!onChange) {return;@@ -100,7 +96,6 @@ function FlowTasksDropdown({ disabled, onChange, value }: FlowTasksDropdownProps});};- // Clear all filtersconst clearFilters = () => {if (!onChange) {return;diff --git a/frontend/src/features/flows/messages/flow-assistant-messages.tsx b/frontend/src/features/flows/messages/flow-assistant-messages.tsxindex c21ebab6..b7fa7c71 100644--- a/frontend/src/features/flows/messages/flow-assistant-messages.tsx+++ b/frontend/src/features/flows/messages/flow-assistant-messages.tsx@@ -58,7 +58,6 @@ function AssistantsDropdown({const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);const [currentAssistant, setCurrentAssistant] = useState<AssistantFragmentFragment | null>(null);- // Get the current selected assistantconst selectedAssistant = useMemo(() => {if (!selectedAssistantId) {return null;@@ -67,12 +66,10 @@ function AssistantsDropdown({return assistants.find((assistant) => assistant.id === selectedAssistantId) || null;}, [assistants, selectedAssistantId]);- // Get the current selected assistant index (1-based, reversed)const selectedAssistantIndex = useMemo(() => {return assistants.findIndex((assistant) => assistant.id === selectedAssistantId);}, [assistants, selectedAssistantId]);- // Group assistants by status with pre-calculated indicesconst assistantsGroup = useMemo(() => {type AssistantItem = { assistant: AssistantFragmentFragment; index: number };@@ -101,13 +98,11 @@ function AssistantsDropdown({);}, [assistants]);- // Handle assistant selectionconst handleAssistantSelect = (assistantId: string) => {onAssistantSelect(assistantId);setIsOpen(false);};- // Handle delete clickconst handleDeleteClick = (assistant: AssistantFragmentFragment) => {if (isDisabled) {return;@@ -117,7 +112,6 @@ function AssistantsDropdown({setDeleteDialogOpen(true);};- // Confirm deleteconst handleConfirmDelete = () => {if (currentAssistant) {onAssistantDelete(currentAssistant.id);@@ -125,7 +119,6 @@ function AssistantsDropdown({}};- // Render assistant itemconst renderAssistantItem = (assistant: AssistantFragmentFragment, index: number) => {const isSelected = selectedAssistantId === assistant.id;const isValid = isProviderValid(assistant.provider, providers);@@ -301,7 +294,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {const [isAssistantCreating, setIsAssistantCreating] = useState(false);- // Separate state for immediate input value and debounced search valueconst [debouncedSearchValue, setDebouncedSearchValue] = useState('');const [isSubmitting, setIsSubmitting] = useState(false);const [isCanceling, setIsCanceling] = useState(false);@@ -319,7 +311,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {selectedAssistantId ?? null,);- // Get system settingsconst { settings } = useSystemSettings();const form = useForm<z.infer<typeof searchFormSchema>>({@@ -331,7 +322,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {const searchValue = form.watch('search');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -340,7 +330,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -349,21 +338,18 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({ search: '' });setDebouncedSearchValue('');debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Get the current selected assistantconst selectedAssistant = useMemo(() => {if (!selectedAssistantId || !assistants) {return null;@@ -372,18 +358,14 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {return assistants.find((assistant) => assistant.id === selectedAssistantId) || null;}, [assistants, selectedAssistantId]);- // Calculate default useAgents valueconst shouldUseAgents = useMemo(() => {- // If creating a new assistant, use system settingif (isAssistantCreating || !selectedAssistant) {return settings?.assistantUseAgents ?? false;}- // If assistant is selected and not creating new, use its useAgents settingreturn selectedAssistant.useAgents;}, [selectedAssistant, settings?.assistantUseAgents, isAssistantCreating]);- // Check if search filter is activeconst hasActiveFilters = useMemo(() => {return !!searchValue.trim();}, [searchValue]);@@ -403,14 +385,12 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {);}, [selectedAssistantLogs, debouncedSearchValue]);- // Handlers for interacting with assistantconst handleAssistantDelete = (assistantId: string) => {if (deleteAssistant) {deleteAssistant(assistantId);}};- // Message submission handlerconst handleSubmitMessage = async (values: FlowFormValues) => {if (!values.message.trim()) {return;@@ -420,14 +400,12 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {try {if (!selectedAssistantId) {- // If no assistant is selected, create a new onesetIsAssistantCreating(true);if (createAssistant) {await createAssistant(values);}} else if (submitAssistantMessage) {- // Otherwise call the existing assistantawait submitAssistantMessage(selectedAssistantId, values);}} catch (error) {@@ -439,7 +417,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {}};- // Stop assistant handlerconst handleStopAssistant = async () => {if (!selectedAssistantId || !stopAssistant) {return;@@ -457,37 +434,31 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {}};- // Handle click on Create Assistant option in dropdownconst handleAssistantCreate = () => {if (initiateAssistantCreation) {initiateAssistantCreation();}};- // Reset filters handlerconst handleResetFilters = () => {form.reset({ search: '' });setDebouncedSearchValue('');debouncedUpdateSearch.cancel();};- // Get placeholder text based on assistant statusconst placeholder = useMemo(() => {if (!flowId) {return 'Select a flow...';}- // Show creating assistant message while in creation modeif (isAssistantCreating) {return 'Creating assistant...';}- // No assistant selected - prompt to create oneif (!selectedAssistant?.status) {return 'Type a message to create a new assistant...';}- // Assistant-specific statusesswitch (selectedAssistant.status) {case StatusType.Created: {return 'Assistant is starting...';@@ -592,7 +563,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {</Empty>) : selectedAssistantId ? (filteredLogs.length > 0 ? (- // Show messages for selected assistant<div className="relative h-full overflow-y-hidden"><divclassName="flex h-full flex-col gap-4 overflow-y-auto"@@ -654,7 +624,6 @@ function FlowAssistantMessages({ className }: FlowAssistantMessagesProps) {</Empty>)) : (- // Show placeholder when no assistant is selected<Empty><EmptyHeader><EmptyMedia variant="icon">diff --git a/frontend/src/features/flows/messages/flow-automation-messages.tsx b/frontend/src/features/flows/messages/flow-automation-messages.tsxindex 56713aad..2b4fccbb 100644--- a/frontend/src/features/flows/messages/flow-automation-messages.tsx+++ b/frontend/src/features/flows/messages/flow-automation-messages.tsx@@ -37,7 +37,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {const logs = useMemo(() => flowData?.messageLogs ?? [], [flowData?.messageLogs]);- // Separate state for immediate input value and debounced search valueconst [debouncedSearchValue, setDebouncedSearchValue] = useState('');const [isSubmitting, setIsSubmitting] = useState(false);const [isCanceling, setIsCanceling] = useState(false);@@ -74,14 +73,12 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({filter: {@@ -94,7 +91,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Check if any filters are activeconst hasActiveFilters = useMemo(() => {const hasSearch = !!searchValue.trim();const hasTaskFilters = !!(filter?.taskIds?.length || filter?.subtaskIds?.length);@@ -102,14 +98,11 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {return hasSearch || hasTaskFilters;}, [searchValue, filter]);- // Memoize filtered logs to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredLogs = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();let filtered = logs || [];- // Filter by searchif (search) {filtered = filtered.filter((log) =>@@ -119,7 +112,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {);}- // Filter by selected tasks and subtasksif (filter?.taskIds?.length || filter?.subtaskIds?.length) {const selectedTaskIds = new Set(filter.taskIds ?? []);const selectedSubtaskIds = new Set(filter.subtaskIds ?? []);@@ -140,13 +132,11 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {return filtered;}, [logs, debouncedSearchValue, filter]);- // Get placeholder text based on flow statusconst placeholder = useMemo(() => {if (!flowId) {return 'Select a flow...';}- // Flow-specific statusesswitch (flowStatus) {case StatusType.Created: {return 'The flow is starting...';@@ -171,7 +161,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {}}, [flowId, flowStatus]);- // Message submission handlerconst handleSubmitMessage = async (values: FlowFormValues) => {setIsSubmitting(true);@@ -182,7 +171,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {}};- // Stop automation handlerconst handleStopAutomation = async () => {setIsCanceling(true);@@ -193,7 +181,6 @@ function FlowAutomationMessages({ className }: FlowAutomationMessagesProps) {}};- // Reset filters handlerconst handleResetFilters = () => {form.reset({filter: {diff --git a/frontend/src/features/flows/messages/flow-message.tsx b/frontend/src/features/flows/messages/flow-message.tsxindex c18c8920..c6bf100a 100644--- a/frontend/src/features/flows/messages/flow-message.tsx+++ b/frontend/src/features/flows/messages/flow-message.tsx@@ -18,7 +18,6 @@ interface FlowMessageProps {searchValue?: string;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -31,7 +30,6 @@ function FlowMessage({ log, searchValue = '' }: FlowMessageProps) {const { createdAt, message, result, resultFormat = ResultFormat.Plain, thinking, type } = log;const isReportMessage = type === MessageLogType.Report;- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();@@ -77,7 +75,6 @@ function FlowMessage({ log, searchValue = '' }: FlowMessageProps) {}}- // Use useCallback to memoize the toggle functionsconst toggleDetails = useCallback(() => {setIsDetailsVisible((prev) => !prev);}, []);@@ -95,15 +92,11 @@ function FlowMessage({ log, searchValue = '' }: FlowMessageProps) {});}, [thinking, message, result, resultFormat]);- // Determine if thinking should be shown- // Show thinking if: thinking exists AND (message is empty OR thinking is manually toggled visible)const shouldShowThinking = thinking && (!message || isThinkingVisible);- // Determine if thinking toggle button should be shown- // Show button only if thinking exists AND message is not emptyconst shouldShowThinkingToggle = thinking && message;- // Only render details content when it's visible to reduce DOM nodes+ // Gate by visibility so the (potentially heavy) details subtree isn't in the DOM when collapsed.const renderDetailsContent = () => {if (!isDetailsVisible) {return null;diff --git a/frontend/src/features/flows/screenshots/flow-screenshots.tsx b/frontend/src/features/flows/screenshots/flow-screenshots.tsxindex 1c5e251a..c8fdf86a 100644--- a/frontend/src/features/flows/screenshots/flow-screenshots.tsx+++ b/frontend/src/features/flows/screenshots/flow-screenshots.tsx@@ -38,7 +38,6 @@ function FlowScreenshots() {const searchValue = form.watch('search');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -47,7 +46,6 @@ function FlowScreenshots() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -56,22 +54,18 @@ function FlowScreenshots() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({ search: '' });setDebouncedSearchValue('');debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Memoize filtered screenshots to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredScreenshots = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();diff --git a/frontend/src/features/flows/tasks/flow-subtask.tsx b/frontend/src/features/flows/tasks/flow-subtask.tsxindex 02f07fbe..c2bc7152 100644--- a/frontend/src/features/flows/tasks/flow-subtask.tsx+++ b/frontend/src/features/flows/tasks/flow-subtask.tsx@@ -13,7 +13,6 @@ interface FlowSubtaskProps {subtask: SubtaskFragmentFragment;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -27,7 +26,6 @@ function FlowSubtask({ searchValue = '', subtask }: FlowSubtaskProps) {const [isDetailsVisible, setIsDetailsVisible] = useState(false);const hasDetails = description || result;- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();diff --git a/frontend/src/features/flows/tasks/flow-task.tsx b/frontend/src/features/flows/tasks/flow-task.tsxindex f1546e70..9deda252 100644--- a/frontend/src/features/flows/tasks/flow-task.tsx+++ b/frontend/src/features/flows/tasks/flow-task.tsx@@ -15,7 +15,6 @@ interface FlowTaskProps {task: TaskFragmentFragment;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -28,7 +27,6 @@ function FlowTask({ searchValue = '', task }: FlowTaskProps) {const { id, result, status, subtasks, title } = task;const [isDetailsVisible, setIsDetailsVisible] = useState(false);- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();@@ -62,7 +60,6 @@ function FlowTask({ searchValue = '', task }: FlowTaskProps) {const sortedSubtasks = [...(subtasks || [])].sort((a, b) => +a.id - +b.id);const hasSubtasks = subtasks && subtasks.length > 0;- // Calculate completed subtasks countconst completedSubtasksCount = useMemo(() => {if (!subtasks?.length) {return 0;@@ -71,7 +68,6 @@ function FlowTask({ searchValue = '', task }: FlowTaskProps) {return subtasks.filter((subtask) => [StatusType.Failed, StatusType.Finished].includes(subtask.status)).length;}, [subtasks]);- // Calculate progress based on completed subtasksconst progress = useMemo(() => {if (!subtasks?.length) {return 0;diff --git a/frontend/src/features/flows/tasks/flow-tasks.tsx b/frontend/src/features/flows/tasks/flow-tasks.tsxindex 60402554..5c4f9ced 100644--- a/frontend/src/features/flows/tasks/flow-tasks.tsx+++ b/frontend/src/features/flows/tasks/flow-tasks.tsx@@ -18,7 +18,6 @@ const searchFormSchema = z.object({search: z.string(),});-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -44,7 +43,6 @@ function FlowTasks() {const searchValue = form.watch('search');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -53,7 +51,6 @@ function FlowTasks() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -62,22 +59,18 @@ function FlowTasks() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({ search: '' });setDebouncedSearchValue('');debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Memoize filtered tasks to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredTasks = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();@@ -106,7 +99,6 @@ function FlowTasks() {return (<div className="flex h-full flex-col"><div className="bg-background sticky top-0 z-10 pb-4">- {/* Search Input */}<Form {...form}><div className="p-px"><FormFielddiff --git a/frontend/src/features/flows/terminal/flow-terminal.tsx b/frontend/src/features/flows/terminal/flow-terminal.tsxindex 821049f5..8e687331 100644--- a/frontend/src/features/flows/terminal/flow-terminal.tsx+++ b/frontend/src/features/flows/terminal/flow-terminal.tsx@@ -30,7 +30,6 @@ function FlowTerminal() {const { flowData, flowId } = useFlow();const terminalLogs = useMemo(() => flowData?.terminalLogs ?? [], [flowData?.terminalLogs]);- // Separate state for immediate input value and debounced search valueconst [debouncedSearchValue, setDebouncedSearchValue] = useState('');const terminalRef = useRef<null | { findNext: () => void; findPrevious: () => void }>(null);@@ -48,7 +47,6 @@ function FlowTerminal() {const searchValue = form.watch('search');const filter = form.watch('filter');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -57,7 +55,6 @@ function FlowTerminal() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -66,14 +63,12 @@ function FlowTerminal() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({filter: {diff --git a/frontend/src/features/flows/tools/flow-tool.tsx b/frontend/src/features/flows/tools/flow-tool.tsxindex 78f38b4d..d5650bf2 100644--- a/frontend/src/features/flows/tools/flow-tool.tsx+++ b/frontend/src/features/flows/tools/flow-tool.tsx@@ -14,7 +14,6 @@ interface FlowToolProps {searchValue?: string;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -26,7 +25,6 @@ const containsSearchValue = (text: null | string | undefined, searchValue: strinfunction FlowTool({ log, searchValue = '' }: FlowToolProps) {const { createdAt, engine, executor, initiator, query, result, subtaskId, taskId } = log;- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();diff --git a/frontend/src/features/flows/tools/flow-tools.tsx b/frontend/src/features/flows/tools/flow-tools.tsxindex 80234f7f..bf6b7abe 100644--- a/frontend/src/features/flows/tools/flow-tools.tsx+++ b/frontend/src/features/flows/tools/flow-tools.tsx@@ -47,7 +47,6 @@ function FlowTools() {const searchValue = form.watch('search');const filter = form.watch('filter');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -56,7 +55,6 @@ function FlowTools() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -65,14 +63,12 @@ function FlowTools() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({filter: {@@ -85,7 +81,6 @@ function FlowTools() {debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Check if any filters are activeconst hasActiveFilters = useMemo(() => {const hasSearch = !!searchValue.trim();const hasTaskFilters = !!(filter?.taskIds?.length || filter?.subtaskIds?.length);@@ -93,14 +88,11 @@ function FlowTools() {return hasSearch || hasTaskFilters;}, [searchValue, filter]);- // Memoize filtered logs to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredLogs = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();let filtered = logs || [];- // Filter by searchif (search) {filtered = filtered.filter((log) => {return (@@ -113,7 +105,6 @@ function FlowTools() {});}- // Filter by selected tasks and subtasksif (filter?.taskIds?.length || filter?.subtaskIds?.length) {const selectedTaskIds = new Set(filter.taskIds ?? []);const selectedSubtaskIds = new Set(filter.subtaskIds ?? []);@@ -136,7 +127,6 @@ function FlowTools() {const hasLogs = filteredLogs && filteredLogs.length > 0;- // Reset filters handlerconst handleResetFilters = () => {form.reset({filter: {diff --git a/frontend/src/features/flows/vector-stores/flow-vector-store.tsx b/frontend/src/features/flows/vector-stores/flow-vector-store.tsxindex 5a81acb4..f84cd79f 100644--- a/frontend/src/features/flows/vector-stores/flow-vector-store.tsx+++ b/frontend/src/features/flows/vector-stores/flow-vector-store.tsx@@ -58,7 +58,6 @@ interface FlowVectorStoreProps {searchValue?: string;}-// Helper function to check if text contains search value (case-insensitive)const containsSearchValue = (text: null | string | undefined, searchValue: string): boolean => {if (!text || !searchValue.trim()) {return false;@@ -70,7 +69,6 @@ const containsSearchValue = (text: null | string | undefined, searchValue: strinfunction FlowVectorStore({ log, searchValue = '' }: FlowVectorStoreProps) {const { action, createdAt, executor, initiator, query, result, subtaskId, taskId } = log;- // Memoize search checks to avoid recalculating on every renderconst searchChecks = useMemo(() => {const trimmedSearch = searchValue.trim();diff --git a/frontend/src/features/flows/vector-stores/flow-vector-stores.tsx b/frontend/src/features/flows/vector-stores/flow-vector-stores.tsxindex 1fddf4d5..349be872 100644--- a/frontend/src/features/flows/vector-stores/flow-vector-stores.tsx+++ b/frontend/src/features/flows/vector-stores/flow-vector-stores.tsx@@ -47,7 +47,6 @@ function FlowVectorStores() {const searchValue = form.watch('search');const filter = form.watch('filter');- // Create debounced function to update search valueconst debouncedUpdateSearch = useMemo(() =>debounce((value: string) => {@@ -56,7 +55,6 @@ function FlowVectorStores() {[],);- // Update debounced search value when input value changesuseEffect(() => {debouncedUpdateSearch(searchValue);@@ -65,14 +63,12 @@ function FlowVectorStores() {};}, [searchValue, debouncedUpdateSearch]);- // Cleanup debounced function on unmountuseEffect(() => {return () => {debouncedUpdateSearch.cancel();};}, [debouncedUpdateSearch]);- // Clear search when flow changes to prevent stale search stateuseEffect(() => {form.reset({filter: {@@ -85,7 +81,6 @@ function FlowVectorStores() {debouncedUpdateSearch.cancel();}, [flowId, form, debouncedUpdateSearch]);- // Check if any filters are activeconst hasActiveFilters = useMemo(() => {const hasSearch = !!searchValue.trim();const hasTaskFilters = !!(filter?.taskIds?.length || filter?.subtaskIds?.length);@@ -93,14 +88,11 @@ function FlowVectorStores() {return hasSearch || hasTaskFilters;}, [searchValue, filter]);- // Memoize filtered logs to avoid recomputing on every render- // Use debouncedSearchValue for filtering to improve performanceconst filteredLogs = useMemo(() => {const search = debouncedSearchValue.toLowerCase().trim();let filtered = logs || [];- // Filter by searchif (search) {filtered = filtered.filter((log) => {return (@@ -114,7 +106,6 @@ function FlowVectorStores() {});}- // Filter by selected tasks and subtasksif (filter?.taskIds?.length || filter?.subtaskIds?.length) {const selectedTaskIds = new Set(filter.taskIds ?? []);const selectedSubtaskIds = new Set(filter.subtaskIds ?? []);@@ -137,7 +128,6 @@ function FlowVectorStores() {const hasLogs = filteredLogs && filteredLogs.length > 0;- // Reset filters handlerconst handleResetFilters = () => {form.reset({filter: {diff --git a/frontend/src/features/knowledges/knowledge-form.tsx b/frontend/src/features/knowledges/knowledge-form.tsxindex abf4cb96..3bf6d41a 100644--- a/frontend/src/features/knowledges/knowledge-form.tsx+++ b/frontend/src/features/knowledges/knowledge-form.tsx@@ -24,10 +24,6 @@ import { useUser } from '@/providers/user-provider';import { KnowledgeFormLayoutDesktop, KnowledgeFormLayoutMobile } from './knowledge-form-layout';import { KnowledgeHeader } from './knowledge-header';-// ----------------------------------------------------------------------------// Schema, types, pure helpers-// ----------------------------------------------------------------------------// Length limits mirror the REST validation tags on the Go side// (`backend/pkg/server/models/knowledge.go`). The GraphQL layer itself does// not enforce them, so without these the user could submit a payload that@@ -179,10 +175,6 @@ export const formValuesToUpdateInput = (values: FormValues, dirty: DirtyFlags):return input;};-// ----------------------------------------------------------------------------// Form component-// ----------------------------------------------------------------------------export interface SubmitResult {document?: KnowledgeDocumentFragmentFragment;redirectTo?: string;diff --git a/frontend/src/features/resources/resources-constants.ts b/frontend/src/features/resources/resources-constants.tsindex 6f3de6df..56b1ad68 100644--- a/frontend/src/features/resources/resources-constants.ts+++ b/frontend/src/features/resources/resources-constants.ts@@ -1,13 +1,9 @@-// ── REST API paths ──────────────────────────────────────────────────────────-export const RESOURCES_API_PATH = '/resources/';export const RESOURCES_MKDIR_API_PATH = '/resources/mkdir';export const RESOURCES_MOVE_API_PATH = '/resources/move';export const RESOURCES_COPY_API_PATH = '/resources/copy';export const RESOURCES_DOWNLOAD_API_PATH = '/resources/download';-// ── UI constants ────────────────────────────────────────────────────────────-export const SEARCH_DEBOUNCE_MS = 300;// ── Upload limits (mirror backend's `pkg/resources/resources.go`) ───────────diff --git a/frontend/src/hooks/use-breakpoint.ts b/frontend/src/hooks/use-breakpoint.tsindex ce887ea6..90251076 100644--- a/frontend/src/hooks/use-breakpoint.ts+++ b/frontend/src/hooks/use-breakpoint.ts@@ -36,7 +36,6 @@ export function useBreakpoint() {const prevWidthRef = useRef<number>(typeof window !== 'undefined' ? window.innerWidth : 0);const breakpointRef = useRef<BreakpointName>(breakpoint);- // Move state update logic outside of useEffectconst updateBreakpointState = useCallback((newBreakpoint: BreakpointName) => {if (breakpointRef.current !== newBreakpoint) {breakpointRef.current = newBreakpoint;diff --git a/frontend/src/hooks/use-flow-tab-detection.ts b/frontend/src/hooks/use-flow-tab-detection.tsindex 534e1f16..0847906f 100644--- a/frontend/src/hooks/use-flow-tab-detection.ts+++ b/frontend/src/hooks/use-flow-tab-detection.ts@@ -18,19 +18,16 @@ export function useFlowTabDetection() {const [manualTab, setManualTab] = useState<null | string>(null);const resolvedTab = useMemo(() => {- // If user manually selected a tab, use itif (manualTab) {return manualTab;}- // Check URL parameterconst tabParam = searchParams.get('tab');if (tabParam && CENTRAL_TAB_VALUES.includes(tabParam)) {return tabParam;}- // Auto-detect: switch to assistant tab if flow is loaded and messageLogs are emptyif (!isLoading && !flowData?.messageLogs?.length) {return 'assistant';}diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.tsindex f630a073..55c484c1 100644--- a/frontend/src/lib/apollo.ts+++ b/frontend/src/lib/apollo.ts@@ -12,8 +12,6 @@ import type { AssistantLogFragmentFragment } from '@/graphql/types';import { Log } from '@/lib/log';import { baseUrl } from '@/models/api';-// --- Constants ----const GRAPHQL_ENDPOINT = `${baseUrl}/graphql`;const ASSISTANT_LOG_TYPENAME = 'AssistantLog';const MAX_RETRY_DELAY_MS = 30_000;@@ -21,8 +19,6 @@ const STREAMING_CACHE_MAX_ENTRIES = 500;const STREAMING_CACHE_TTL_MS = 1000 * 60 * 5;const STREAMING_THROTTLE_MS = 50;-// --- Types ----type StreamingLogEntry = {message: null | string;result: null | string;@@ -31,8 +27,6 @@ type StreamingLogEntry = {type SubscriptionAction = 'add' | 'create' | 'delete' | 'update';-// --- Pure utilities ----const EMPTY_LOG_ENTRY: StreamingLogEntry = { message: null, result: null, thinking: null };const concatStrings = (existing: null | string | undefined, incoming: null | string | undefined): null | string => {@@ -69,8 +63,6 @@ const isSubscriptionOperation = ({ query }: Operation): boolean => {return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';};-// --- Link helpers ----const createInterceptLink = (transform: (result: FetchResult, operation: Operation) => FetchResult): ApolloLink =>new ApolloLink((operation: Operation, forward) =>@@ -85,8 +77,6 @@ const createInterceptLink = (transform: (result: FetchResult, operation: Operati}),);-// --- Subscription → cache configuration ----const subscriptionToCacheFieldMap: Record<string, string> = {agentLogAdded: 'agentLogs',apiTokenCreated: 'apiTokens',@@ -126,8 +116,6 @@ const subscriptionToCacheFieldMap: Record<string, string> = {vectorStoreLogAdded: 'vectorStoreLogs',};-// --- Cache variant matching ----const matchesCacheVariant = (storeFieldName: string,cacheField: string,@@ -158,8 +146,6 @@ const matchesCacheVariant = (}};-// --- Cache action strategies ----type CacheActionApplier = (existingArray: readonly Reference[],newRef: Reference,@@ -248,8 +234,6 @@ const updateCacheForSubscription = (}};-// --- Link factories ----const createStreamingLink = (): ApolloLink => {const streamingLogs = new LRUCache<string, StreamingLogEntry>({max: STREAMING_CACHE_MAX_ENTRIES,@@ -385,14 +369,10 @@ const createSubscriptionCacheLink = (cacheInstance: InMemoryCache): ApolloLink =return result;});-// --- Cache merge policy ----const replaceWithIncoming = {merge: (_existing: unknown, incoming: unknown) => incoming,};-// --- Client factory ----const createApolloClient = () => {const httpLink = createHttpLink({credentials: 'include',@@ -409,12 +389,10 @@ const createApolloClient = () => {error: (error) => {Log.error('GraphQL WebSocket error:', error);- // Check if error is authorization-relatedif (error && typeof error === 'object') {const errorMessage = 'message' in error ? String(error.message) : '';const errorString = errorMessage.toLowerCase();- // Detect 403/401 errors or auth-related messagesif (errorString.includes('403') ||errorString.includes('401') ||@@ -451,7 +429,6 @@ const createApolloClient = () => {path,});- // Check for authorization errors in GraphQL responsesconst errorCode = extensions?.code as string | undefined;if (@@ -470,7 +447,6 @@ const createApolloClient = () => {if (networkError) {Log.error(`[Network Error] ${networkError.message}`, networkError);- // Check for HTTP 401/403 errorsif ('statusCode' in networkError) {const statusCode = (networkError as { statusCode?: number }).statusCode;diff --git a/frontend/src/lib/axios.ts b/frontend/src/lib/axios.tsindex cf496cd2..24d3af96 100644--- a/frontend/src/lib/axios.ts+++ b/frontend/src/lib/axios.ts@@ -41,8 +41,6 @@ export interface ApiSuccessResponse<T> {status: 'success';}-// ── shared instance ──────────────────────────────────────────────────────────-/*** Central axios instance for all REST calls in the app.*@@ -180,8 +178,6 @@ export const api = {axios.put<T, ApiResponse<T>, B>(url, body, config),};-// ── helpers ──────────────────────────────────────────────────────────────────-export const isApiSuccess = <T>(response: ApiResponse<T>): response is ApiSuccessResponse<T> =>response.status === 'success';diff --git a/frontend/src/lib/clipboard.ts b/frontend/src/lib/clipboard.tsindex ee7d1ea7..de0bc934 100644--- a/frontend/src/lib/clipboard.ts+++ b/frontend/src/lib/clipboard.ts@@ -26,7 +26,6 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =let isResolved = false;const cleanup = () => {- // Clear timeouts if they existif (timeoutId) {clearTimeout(timeoutId);timeoutId = null;@@ -37,23 +36,22 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =safetyTimeoutId = null;}- // Dispose terminalif (hiddenTerminal) {try {hiddenTerminal.dispose();} catch {- // Ignore disposal errors+ // xterm's dispose can throw if the addon graph is mid-update; swallow it+ // because cleanup runs from finalizers we don't want to abort.}hiddenTerminal = null;}- // Remove DOM elementif (hiddenDiv && hiddenDiv.parentNode) {try {hiddenDiv.remove();} catch {- // Ignore removal errors+ // see above}hiddenDiv = null;@@ -69,7 +67,6 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =};try {- // Create a hidden terminal instancehiddenTerminal = new XTerminal({cols: 120,convertEol: true,@@ -77,7 +74,6 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =rows: 50,});- // Create a hidden div to mount the terminalhiddenDiv = document.createElement('div');hiddenDiv.style.position = 'absolute';hiddenDiv.style.left = '-9999px';@@ -85,17 +81,14 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =hiddenDiv.style.visibility = 'hidden';document.body.append(hiddenDiv);- // Open terminal and write contenthiddenTerminal.open(hiddenDiv);-- // Write the terminal contenthiddenTerminal.write(terminalContent);- // Small delay to ensure content is processed+ // Tiny delay lets xterm finish its render pipeline so `buffer.active` reflects the write.timeoutId = setTimeout(() => {try {if (isResolved) {- return; // Already resolved/rejected+ return;}if (!hiddenTerminal) {@@ -104,7 +97,6 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =return;}- // Extract clean text from terminal bufferlet cleanText = '';const buffer = hiddenTerminal.buffer.active;@@ -114,8 +106,9 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =if (line) {const lineText = line.translateToString(true).trimEnd();+ // Skip leading empty lines but keep blank lines once we have content+ // so paragraph spacing inside the output survives the round-trip.if (lineText || cleanText) {- // Include empty lines only if we have contentcleanText += `${lineText}\n`;}}@@ -123,12 +116,10 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =safeResolve(`\`\`\`bash\n${cleanText.trimEnd()}\n\`\`\``);} catch {- // Fallback to original contentsafeResolve(terminalContent);}}, 100);- // Add timeout safety net (10 seconds max)safetyTimeoutId = setTimeout(() => {if (!isResolved) {console.warn('Terminal text extraction timed out, falling back to original content');@@ -136,7 +127,6 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =}}, 1000);} catch {- // Fallback to original content on any initialization errorsafeResolve(terminalContent);}});@@ -149,17 +139,14 @@ export const formatMessageForClipboard = async (messageData: CopyableMessage): Pconst { message, result, resultFormat = ResultFormat.Plain, thinking } = messageData;let content = '';- // Add thinking if presentif (thinking && thinking.trim()) {content += `<details>\n<summary>Thinking</summary>\n\n${thinking.trim()}\n\n</details>\n\n`;}- // Add main messageif (message && message.trim()) {content += message.trim();}- // Add result if presentif (result && result.trim()) {if (content) {content += '\n\n';@@ -167,12 +154,10 @@ export const formatMessageForClipboard = async (messageData: CopyableMessage): Plet resultContent = result.trim();- // Handle terminal format specially to get clean textif (resultFormat === ResultFormat.Terminal) {try {resultContent = await getCleanTerminalText(result);} catch {- // Fallback to original resultresultContent = result.trim();}}diff --git a/frontend/src/lib/report/report-pdf.tsx b/frontend/src/lib/report/report-pdf.tsxindex 74f06b3d..c08ef130 100644--- a/frontend/src/lib/report/report-pdf.tsx+++ b/frontend/src/lib/report/report-pdf.tsx@@ -71,7 +71,6 @@ const splitByCJK = (text: string): TextSegment[] => {return segments.length > 0 ? segments : [{ isCJK: false, text }];};-// PDF styles for @react-pdf/renderer - Enhanced beautiful stylesconst pdfStyles = StyleSheet.create({bold: {fontWeight: 'bold',@@ -193,7 +192,7 @@ const pdfStyles = StyleSheet.create({},});-// Map of emoji to text replacements for PDF rendering+// @react-pdf/renderer has spotty emoji glyph support — substitute readable text tags instead.const emojiMap: Record<string, string> = {'⏳': '[WAIT]','⚠️': '[WARN]',@@ -212,7 +211,6 @@ const emojiMap: Record<string, string> = {'🚀': '[START]',};-// Replace emojis with text equivalents for PDFconst replaceEmojis = (text: string): string => {let result = text;@@ -223,7 +221,6 @@ const replaceEmojis = (text: string): string => {return result;};-// Inline token types for rich text formattinginterface InlineToken {bold?: boolean;code?: boolean;@@ -233,7 +230,6 @@ interface InlineToken {type: 'text';}-// Parsed content interface with support for inline formattinginterface ParsedContent {content?: string;inlineTokens?: InlineToken[];@@ -243,12 +239,10 @@ interface ParsedContent {type: string;}-// Parse inline markdown formatting (bold, italic, code, links)const parseInlineTokens = (text: string): InlineToken[] => {const tokens: InlineToken[] = [];const inlineTokens = marked.lexer(text, { breaks: false });- // If lexer returns a paragraph token, use its tokens propertyconst firstToken = inlineTokens[0];if (firstToken && firstToken.type === 'paragraph' && 'tokens' in firstToken) {@@ -304,7 +298,6 @@ const parseInlineTokens = (text: string): InlineToken[] => {}default: {- // For other inline types, try to extract textif ('text' in token) {tokens.push({text: replaceEmojis(String(token.text || '')),@@ -315,7 +308,6 @@ const parseInlineTokens = (text: string): InlineToken[] => {}});} else {- // Fallback: return plain texttokens.push({text: replaceEmojis(text),type: 'text',@@ -325,7 +317,6 @@ const parseInlineTokens = (text: string): InlineToken[] => {return tokens;};-// Parse markdown using marked library and convert tokensconst parseMarkdownTokens = (markdown: string): ParsedContent[] => {const tokens = marked.lexer(markdown);const result: ParsedContent[] = [];@@ -377,12 +368,10 @@ const parseMarkdownTokens = (markdown: string): ParsedContent[] => {}case 'space': {- // Skip empty linesbreak;}default: {- // For other types, try to extract text if availableif ('text' in token && typeof token.text === 'string') {result.push({inlineTokens: parseInlineTokens(token.text),@@ -398,7 +387,11 @@ const parseMarkdownTokens = (markdown: string): ParsedContent[] => {return result;};-// Render a raw text string, splitting CJK segments to switch font family+/**+ * Splits CJK segments out so each chunk renders with the matching font family —+ * Noto Sans for Latin/Cyrillic, Noto Sans SC for CJK. CJK fonts have no true italic+ * variant, so italic is dropped for those segments.+ */const renderTextWithCJK = (text: string,baseFamily: string,@@ -410,13 +403,11 @@ const renderTextWithCJK = (const segments = splitByCJK(text);if (segments.length === 1 && !segments[0]?.isCJK) {- // Fast path: no CJK — return plain string so the parent Text handles itreturn text;}return segments.map((seg, idx) => {const family = seg.isCJK ? (bold ? 'NotoSansSC' : 'NotoSansSC') : bold ? boldFamily : baseFamily;- // CJK fonts have no true italic; skip italic for CJK segmentsconst style: Record<string, string> = { fontFamily: family };if (bold && !seg.isCJK) {@@ -438,12 +429,10 @@ const renderTextWithCJK = (});};-// Helper function to render inline tokens with formattingconst renderInlineTokens = (tokens: InlineToken[], keyPrefix: string) => {return tokens.map((token, idx) => {const textContent = token.text;- // Collect all applicable stylesconst appliedStyles = [];if (token.code) {@@ -462,7 +451,6 @@ const renderInlineTokens = (tokens: InlineToken[], keyPrefix: string) => {appliedStyles.push(pdfStyles.link);}- // If we have any styles, wrap in Text component with CJK-aware renderingif (appliedStyles.length > 0) {const isBold = !!token.bold;const isItalic = !!token.italic;@@ -488,7 +476,6 @@ const renderInlineTokens = (tokens: InlineToken[], keyPrefix: string) => {);}- // Plain text: render with CJK-aware font split (returns string if no CJK)const rendered = renderTextWithCJK(textContent, 'NotoSans', 'NotoSans', `${keyPrefix}-inline-${idx}`);if (typeof rendered === 'string') {@@ -499,7 +486,6 @@ const renderInlineTokens = (tokens: InlineToken[], keyPrefix: string) => {});};-// Render parsed markdown as React PDF componentsconst renderPDFContent = (parsed: ParsedContent[]) => {const elements = parsed.map((item, index) => {@@ -606,7 +592,6 @@ const renderPDFContent = (parsed: ParsedContent[]) => {return elements;};-// PDF Document componentfunction PDFReportDocument({ content }: { content: string }) {const parsed = parseMarkdownTokens(content);const elements = renderPDFContent(parsed);@@ -623,13 +608,11 @@ function PDFReportDocument({ content }: { content: string }) {);}-// Main function to generate PDF from markdownexport const generatePDFFromMarkdownNew = async (content: string, fileName: string): Promise<void> => {try {const doc = <PDFReportDocument content={content} />;const blob = await pdf(doc).toBlob();- // Downloadconst url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;@@ -645,7 +628,6 @@ export const generatePDFFromMarkdownNew = async (content: string, fileName: stri}};-// Generate PDF as blobexport const generatePDFBlobNew = async (content: string): Promise<Blob> => {try {const doc = <PDFReportDocument content={content} />;diff --git a/frontend/src/lib/report/report.ts b/frontend/src/lib/report/report.tsindex 2b56ba3f..6a6fdfdd 100644--- a/frontend/src/lib/report/report.ts+++ b/frontend/src/lib/report/report.ts@@ -5,7 +5,6 @@ import type { FlowFragmentFragment, TaskFragmentFragment } from '@/graphql/typesimport { StatusType } from '@/graphql/types';import { Log } from '@/lib/log';-// Helper function to get emoji for statusconst getStatusEmoji = (status: StatusType): string => {switch (status) {case StatusType.Created: {@@ -34,29 +33,25 @@ const getStatusEmoji = (status: StatusType): string => {}};-// Helper function to shift markdown headers by specified levelsconst shiftMarkdownHeaders = (text: string, shiftBy: number): string => {return text.replaceAll(/^(#{1,6})\s+(.+)$/gm, (match, hashes, content) => {const currentLevel = hashes.length;- const newLevel = Math.min(currentLevel + shiftBy, 6); // Max level is 6+ const newLevel = Math.min(currentLevel + shiftBy, 6);const newHashes = '#'.repeat(newLevel);return `${newHashes} ${content}`;});};-// Helper function to create anchor link from text using the same algorithm as rehype-slugconst createAnchor = (text: string): string => {const slugger = new GithubSlugger();return slugger.slug(text);};-// Helper function to generate table of contentsconst generateTableOfContents = (tasks: TaskFragmentFragment[], flow?: FlowFragmentFragment | null): string => {let toc = '';- // Add flow header as H1 if flow data is availableif (flow) {const flowEmoji = getStatusEmoji(flow.status);toc = `# ${flowEmoji} ${flow.id}. ${flow.title}\n\n`;@@ -71,19 +66,18 @@ const generateTableOfContents = (tasks: TaskFragmentFragment[], flow?: FlowFragmsortedTasks.forEach((task) => {const taskEmoji = getStatusEmoji(task.status);const taskTitle = `${taskEmoji} ${task.id}. ${task.title}`;- // Create anchor from the same text that will be used in the heading (including emoji)+ // Anchor must be generated from the exact heading text (emoji included) — rehype-slug+ // computes the same slug from the rendered <h3>, so any mismatch breaks the link.const taskAnchor = createAnchor(`${taskEmoji} ${task.id}. ${task.title}`);toc += `- [${taskTitle}](#${taskAnchor})\n`;- // Add subtasks to TOC (removed input headers from TOC)if (task.subtasks && task.subtasks.length > 0) {const sortedSubtasks = [...task.subtasks].sort((a, b) => +a.id - +b.id);sortedSubtasks.forEach((subtask) => {const subtaskEmoji = getStatusEmoji(subtask.status);const subtaskTitle = `${subtaskEmoji} ${subtask.id}. ${subtask.title}`;- // Create anchor from the same text that will be used in the heading (including emoji)const subtaskAnchor = createAnchor(`${subtaskEmoji} ${subtask.id}. ${subtask.title}`);toc += ` - [${subtaskTitle}](#${subtaskAnchor})\n`;});@@ -93,7 +87,6 @@ const generateTableOfContents = (tasks: TaskFragmentFragment[], flow?: FlowFragmreturn `${toc}\n---\n\n`;};-// Helper function to generate report contentexport const generateReport = (tasks: TaskFragmentFragment[], flow?: FlowFragmentFragment | null): string => {if (!tasks || tasks.length === 0) {if (flow) {@@ -107,26 +100,23 @@ export const generateReport = (tasks: TaskFragmentFragment[], flow?: FlowFragmenconst sortedTasks = [...tasks].sort((a, b) => +a.id - +b.id);- // Generate table of contents with flow headerlet report = generateTableOfContents(tasks, flow);sortedTasks.forEach((task, taskIndex) => {- // Add task title with status emoji and ID (now H3 since H1 is flow, H2 is TOC)const taskEmoji = getStatusEmoji(task.status);report += `### ${taskEmoji} ${task.id}. ${task.title}\n\n`;- // Add task input with shifted headers (shift by 3 levels: H1→H4, H2→H5, etc.)+ // Shift the task's own input headings down by 3 so they slot below the H3 task title+ // (H1→H4, H2→H5, etc.) — keeps the report's outline consistent across sections.if (task.input?.trim()) {const shiftedInput = shiftMarkdownHeaders(task.input, 3);report += `${shiftedInput}\n\n`;}- // Add separator and task result if not emptyif (task.result?.trim()) {report += `---\n\n${task.result}\n\n`;}- // Add subtasks (now H4 since tasks are H3)if (task.subtasks && task.subtasks.length > 0) {const sortedSubtasks = [...task.subtasks].sort((a, b) => +a.id - +b.id);@@ -134,19 +124,16 @@ export const generateReport = (tasks: TaskFragmentFragment[], flow?: FlowFragmenconst subtaskEmoji = getStatusEmoji(subtask.status);report += `#### ${subtaskEmoji} ${subtask.id}. ${subtask.title}\n\n`;- // Add subtask descriptionif (subtask.description?.trim()) {report += `${subtask.description}\n\n`;}- // Add subtask result with separator if not emptyif (subtask.result?.trim()) {report += `---\n\n${subtask.result}\n\n`;}});}- // Add separator between tasks (except for the last one)if (taskIndex < sortedTasks.length - 1) {report += '---\n\n';}@@ -158,18 +145,12 @@ export const generateReport = (tasks: TaskFragmentFragment[], flow?: FlowFragmenexport const generateFileName = (flow: FlowFragmentFragment): string => {const flowId = flow.id;const flowTitle = flow.title- // Replace any invalid file name characters and whitespace with underscore.replaceAll(/[^\w\s.-]/g, '_')- // Replace spaces, non-breaking spaces, and line breaks with underscore.replaceAll(/[\s\u2000-\u200B]+/g, '_')- // Convert to lowercase.toLowerCase()- // Trim to 150 characters.slice(0, 150)- // Remove trailing underscores.replace(/_+$/, '');- // DATETIME in format YYYYMMDDHHMMSSconst now = new Date();const year = now.getFullYear();const month = String(now.getMonth() + 1).padStart(2, '0');@@ -183,27 +164,20 @@ export const generateFileName = (flow: FlowFragmentFragment): string => {return `report_flow_${flowId}_${flowTitle}_${datetime}`;};-// Helper function to download text content as fileexport const downloadTextFile = (content: string, fileName: string, mimeType = 'text/plain'): void => {try {- // Create blob with contentconst blob = new Blob([content], { type: mimeType });-- // Create temporary URLconst url = URL.createObjectURL(blob);- // Create temporary download linkconst link = document.createElement('a');link.href = url;link.download = fileName;link.style.display = 'none';- // Add to DOM, click, and removedocument.body.append(link);link.click();link.remove();- // Clean up URLURL.revokeObjectURL(url);} catch (error) {Log.error('Failed to download file:', error);@@ -211,7 +185,6 @@ export const downloadTextFile = (content: string, fileName: string, mimeType = '}};-// Helper function to copy text to clipboardexport const copyToClipboard = async (text: string): Promise<boolean> => {try {await navigator.clipboard.writeText(text);diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.tsindex 0693e1f3..25d5ff70 100644--- a/frontend/src/lib/utils/auth.ts+++ b/frontend/src/lib/utils/auth.ts@@ -4,7 +4,6 @@* @returns URL parameter string (empty string or ?returnUrl=...)*/export const getReturnUrlParam = (currentPath: string): string => {- // Don't save default route as return URLif (currentPath === '/flows/new' || currentPath === '/login') {return '';}@@ -24,7 +23,6 @@ export const getSafeReturnUrl = (returnUrl: null | string, fallback: string): stconst trimmed = returnUrl.trim();- // Allow only relative paths: must start with single slash, not //if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {return trimmed;}diff --git a/frontend/src/pages/flows/flow.tsx b/frontend/src/pages/flows/flow.tsxindex d85c0674..b7a91481 100644--- a/frontend/src/pages/flows/flow.tsx+++ b/frontend/src/pages/flows/flow.tsx@@ -107,7 +107,6 @@ function Flow() {const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);const [renameFlowMutation, { loading: isRenameLoading }] = useRenameFlowMutation();- // Redirect to flows list if there's an error loading flow data or flow not founduseEffect(() => {if (flowError || (!isFlowLoading && !flowData?.flow)) {navigate('/flows', { replace: true });@@ -181,10 +180,8 @@ function Flow() {}}, [flow, deleteFlow, navigate]);- // Desktop: side panel defaults to 'terminal'const [desktopTabsTab, setDesktopTabsTab] = useState<string>('terminal');- // Mobile: use the same auto-detection logic as FlowCentralTabsconst { handleTabChange: handleMobileTabChange, resolvedTab: mobileAutoTab } = useFlowTabDetection();const activeTabsTab = isDesktop ? desktopTabsTab : mobileAutoTab;@@ -438,10 +435,8 @@ function FlowReportDropdown() {const flow = flowData?.flow;const tasks = flowData?.tasks ?? [];- // Check if flow is available for report generationconst isReportDisabled = !flow || !flowId;- // Report export handlersconst handleCopyToClipboard = async () => {if (isReportDisabled) {return;@@ -464,14 +459,11 @@ function FlowReportDropdown() {}try {- // Generate report contentconst reportContent = generateReport(tasks, flow);- // Generate file nameconst baseFileName = generateFileName(flow);const fileName = `${baseFileName}.md`;- // Download filedownloadTextFile(reportContent, fileName, 'text/markdown; charset=UTF-8');} catch (error) {Log.error('Failed to download markdown report:', error);@@ -483,7 +475,6 @@ function FlowReportDropdown() {return;}- // Open new tab (not popup) with report page and download flagconst url = `/flows/${flowId}/report?download=true&silent=true`;window.open(url, '_blank');};@@ -493,7 +484,6 @@ function FlowReportDropdown() {return;}- // Open new tab with report page for web viewingconst url = `/flows/${flowId}/report`;window.open(url, '_blank');};diff --git a/frontend/src/pages/flows/flows.tsx b/frontend/src/pages/flows/flows.tsxindex 3f270235..a4b7dad8 100644--- a/frontend/src/pages/flows/flows.tsx+++ b/frontend/src/pages/flows/flows.tsx@@ -605,7 +605,6 @@ function Flows() {);}- // Check if flows list is emptyif (flows.length === 0) {return (<>diff --git a/frontend/src/pages/flows/new-flow.tsx b/frontend/src/pages/flows/new-flow.tsxindex bc5f10ee..b8d1de28 100644--- a/frontend/src/pages/flows/new-flow.tsx+++ b/frontend/src/pages/flows/new-flow.tsx@@ -21,7 +21,6 @@ function NewFlow() {const [isLoading, setIsLoading] = useState(false);const [flowType, setFlowType] = useState<'assistant' | 'automation'>('automation');- // Calculate default useAgents value (only for assistant type)const shouldUseAgents = useMemo(() => {return settings?.assistantUseAgents ?? false;}, [settings?.assistantUseAgents]);@@ -37,7 +36,6 @@ function NewFlow() {const flowId = flowType === 'automation' ? await createFlow(values) : await createFlowWithAssistant(values);if (flowId) {- // Navigate to the new flow page with tab parameternavigate(`/flows/${flowId}?tab=${flowType}`);}} finally {diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex a1eaeb09..3a16cc24 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -12,7 +12,6 @@ function Login() {const { authInfo, isLoading } = useUser();const authProviders = authInfo?.providers || [];- // Extract the return URL from either location state or query parametersconst returnUrl = getSafeReturnUrl((location.state?.from as string) || searchParams.get('returnUrl'), '/flows/new');return (diff --git a/frontend/src/pages/oauth-result.tsx b/frontend/src/pages/oauth-result.tsxindex 89ff5537..4e081c06 100644--- a/frontend/src/pages/oauth-result.tsx+++ b/frontend/src/pages/oauth-result.tsx@@ -7,11 +7,9 @@ function OAuthResult() {const messageRef = useRef(statusMessage);const prevMessageRef = useRef(statusMessage);- // Success delay is short, error delay is longer to allow readingconst successDelay = 2000;const errorDelay = 5000;- // Synchronize state with ref without problematic dependenciesuseLayoutEffect(() => {if (prevMessageRef.current !== messageRef.current) {setStatusMessage(messageRef.current);@@ -24,7 +22,6 @@ function OAuthResult() {const status = params.get('status');const error = params.get('error');- // This is used to track all timeouts that need to be cleared on cleanuplet redirectTimer: NodeJS.Timeout | null = null;let cleanupTimer: NodeJS.Timeout | null = null;let closeTimer: NodeJS.Timeout | null = null;@@ -33,7 +30,6 @@ function OAuthResult() {messageRef.current = message;};- // Handle window close safelyconst handleClose = (delay: number) => {closeTimer = setTimeout(() => {try {@@ -46,7 +42,6 @@ function OAuthResult() {}, delay);};- // Handle redirection if neededconst handleRedirect = (url: string, delay: number) => {redirectTimer = setTimeout(() => {try {@@ -56,7 +51,6 @@ function OAuthResult() {}}, delay);- // Ensure redirect timer gets cleaned upcleanupTimer = setTimeout(() => {if (redirectTimer) {clearTimeout(redirectTimer);@@ -76,7 +70,6 @@ function OAuthResult() {window.location.origin,);- // Success handlingupdateMessage('Authentication complete, closing window...');handleClose(successDelay);} catch (e) {@@ -85,15 +78,12 @@ function OAuthResult() {handleClose(errorDelay);}} else {- // If no opener, redirect to loginupdateMessage('Authentication window opened directly. Redirecting to login page...');handleRedirect('/login', errorDelay / 2);handleClose(errorDelay);}- // Cleanup function for useEffectreturn () => {- // Explicitly clear all timeoutsif (redirectTimer) {clearTimeout(redirectTimer);}diff --git a/frontend/src/pages/settings/settings-prompt.tsx b/frontend/src/pages/settings/settings-prompt.tsxindex 1ebd6b12..43d57855 100644--- a/frontend/src/pages/settings/settings-prompt.tsx+++ b/frontend/src/pages/settings/settings-prompt.tsx@@ -39,7 +39,6 @@ import {import { formatPromptId } from '@/lib/route-titles/format-prompt-id';import { cn } from '@/lib/utils';-// Form schemas for each tabconst systemFormSchema = z.object({template: z.string().min(1, 'System template is required'),});@@ -56,7 +55,6 @@ interface BaseTextareaProps {placeholder?: string;}-// Universal field components using useControllerinterface ControllerProps {control: any;disabled?: boolean;@@ -95,7 +93,6 @@ function FormTextareaItem({ className, control, disabled, label, name, placehold);}-// Helper function to extract used variables from templateconst getUsedVariables = (template: string | undefined): Set<string> => {const usedVariables = new Set<string>();@@ -117,7 +114,6 @@ const getUsedVariables = (template: string | undefined): Set<string> => {return usedVariables;};-// Variables Componentinterface VariablesProps {currentTemplate: string;onVariableClick: (variable: string) => void;@@ -128,14 +124,12 @@ function SettingsPrompt() {const { promptId } = useParams<{ promptId: string }>();const navigate = useNavigate();- // GraphQL queries and mutationsconst { data, error, loading } = useSettingsPromptsQuery();const [createPrompt, { error: createError, loading: isCreateLoading }] = useCreatePromptMutation();const [updatePrompt, { error: updateError, loading: isUpdateLoading }] = useUpdatePromptMutation();const [deletePrompt, { error: deleteError, loading: isDeleteLoading }] = useDeletePromptMutation();const [validatePrompt, { error: validateError, loading: isValidateLoading }] = useValidatePromptMutation();- // Local state managementconst [submitError, setSubmitError] = useState<null | string>(null);const [activeTab, setActiveTab] = useState<'human' | 'system'>('system');const [resetDialogOpen, setResetDialogOpen] = useState(false);@@ -149,7 +143,6 @@ function SettingsPrompt() {const isLoading = isCreateLoading || isUpdateLoading || isDeleteLoading || isValidateLoading;- // Helper function to handle variable insertion/selectionconst handleVariableClick = (variable: string, field: any, formId: string) => {const textarea = document.querySelector(`#${formId} textarea`) as HTMLTextAreaElement;@@ -157,16 +150,13 @@ function SettingsPrompt() {const currentValue = field.value || '';const variablePattern = `{{.${variable}}}`;- // Check if variable is already usedconst variableIndex = currentValue.indexOf(variablePattern);if (variableIndex !== -1) {- // Variable exists - select it and scroll to ittextarea.focus();textarea.setSelectionRange(variableIndex, variableIndex + variablePattern.length);- // Scroll to center the selection- const lineHeight = 20; // Approximate line height+ const lineHeight = 20;const textBeforeSelection = currentValue.slice(0, Math.max(0, variableIndex));const linesBeforeSelection = textBeforeSelection.split('\n').length - 1;const selectionTop = linesBeforeSelection * lineHeight;@@ -175,14 +165,13 @@ function SettingsPrompt() {textarea.scrollTop = scrollTop;} else {- // Variable doesn't exist - insert it at cursor position (no scrolling)const start = textarea.selectionStart;const end = textarea.selectionEnd;const newValue =currentValue.slice(0, Math.max(0, start)) + variablePattern + currentValue.slice(Math.max(0, end));field.onChange(newValue);- // Focus and set cursor position after the inserted variable (no scrolling)+ // preventScroll: avoid yanking the user away from where they were typing.setTimeout(() => {textarea.focus({ preventScroll: true });textarea.setSelectionRange(start + variablePattern.length, start + variablePattern.length);@@ -191,7 +180,6 @@ function SettingsPrompt() {}};- // Handle reset to default promptconst handleReset = () => {setResetDialogOpen(true);};@@ -209,14 +197,12 @@ function SettingsPrompt() {refetchQueries: ['settingsPrompts'],variables: { promptId: promptInfo.userSystemPrompt.id },});- // Reset form to default valuesystemForm.setValue('template', promptInfo.defaultSystemTemplate);} else if (activeTab === 'human' && promptInfo.userHumanPrompt) {await deletePrompt({refetchQueries: ['settingsPrompts'],variables: { promptId: promptInfo.userHumanPrompt.id },});- // Reset form to default valuehumanForm.setValue('template', promptInfo.defaultHumanTemplate);}@@ -228,7 +214,6 @@ function SettingsPrompt() {}};- // Handle validate promptconst handleValidate = async () => {if (!promptInfo) {return;@@ -272,7 +257,6 @@ function SettingsPrompt() {}};- // Form instances for each tabconst systemForm = useForm<SystemFormData>({defaultValues: {template: '',@@ -287,16 +271,13 @@ function SettingsPrompt() {resolver: zodResolver(humanFormSchema),});- // Reactive dirty state across both formsconst { isDirty: isSystemDirty } = useFormState({ control: systemForm.control });const { isDirty: isHumanDirty } = useFormState({ control: humanForm.control });const isDirty = isSystemDirty || isHumanDirty;- // Watch form values to detect used variablesconst systemTemplate = systemForm.watch('template');const humanTemplate = humanForm.watch('template');- // Determine prompt type and get prompt data// eslint-disable-next-line react-hooks/preserve-manual-memoization -- branching reads from data.settingsPrompts that the compiler can't statically prove stableconst promptInfo = useMemo(() => {if (!promptId || !data?.settingsPrompts) {@@ -311,11 +292,9 @@ function SettingsPrompt() {const { agents, tools } = defaultPrompts;- // Check if it's an agent promptconst agentData = agents?.[promptId as keyof typeof agents] as AgentPrompt | AgentPrompts | undefined;if (agentData) {- // Check if we have user-defined system or human promptsconst userSystemPrompt = userDefined?.find((p) => p.type === agentData.system.type);const userHumanPrompt = userDefined?.find((p) => p.type === (agentData as AgentPrompts)?.human?.type);@@ -333,7 +312,6 @@ function SettingsPrompt() {};}- // Check if it's a tool promptconst toolData = tools?.[promptId as keyof typeof tools] as DefaultPrompt | undefined;if (toolData) {@@ -356,7 +334,6 @@ function SettingsPrompt() {return null;}, [promptId, data?.settingsPrompts]);- // Compute variables data based on active tab and prompt infoconst variablesData = useMemo(() => {if (!promptInfo) {return null;@@ -382,7 +359,6 @@ function SettingsPrompt() {return { currentTemplate, formId, variables };}, [promptInfo, activeTab, systemTemplate, humanTemplate]);- // Handle variable click with useCallback for better performanceconst handleVariableClickCallback = useCallback((variable: string) => {if (!variablesData) {@@ -404,7 +380,6 @@ function SettingsPrompt() {[activeTab, systemTemplate, humanTemplate, variablesData, systemForm, humanForm],);- // Fill forms with current prompt data when availableuseEffect(() => {if (promptInfo) {systemForm.reset({@@ -417,7 +392,8 @@ function SettingsPrompt() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [promptInfo]);- // Push a blocker entry when form is dirty to manage browser back+ // Push a synthetic history entry while the form is dirty so a browser-back can be intercepted+ // by popstate below — react-router's blocker doesn't cover the native back gesture.useEffect(() => {if (isDirty && !hasPushedBlockerStateRef.current) {window.history.pushState({ __pentagiBlock__: true }, '');@@ -425,7 +401,6 @@ function SettingsPrompt() {}}, [isDirty]);- // Intercept browser back to show confirmation dialoguseEffect(() => {const handlePopState = () => {if (!isDirty) {@@ -480,7 +455,6 @@ function SettingsPrompt() {setIsLeaveDialogOpen(open);};- // Form submission handlersconst handleSystemSubmit = async (formData: SystemFormData) => {if (!promptInfo) {return;@@ -488,7 +462,7 @@ function SettingsPrompt() {const isUpdate = !!promptInfo.userSystemPrompt;- // For creation, check if the template is identical to the default+ // Submitting an unchanged template would create a no-op userDefined row that masks the default.if (!isUpdate && formData.template === promptInfo.defaultSystemTemplate) {return;}@@ -496,7 +470,6 @@ function SettingsPrompt() {try {setSubmitError(null);- // Get the real type from datalet promptType: PromptType;if (promptInfo.type === 'agent') {@@ -508,7 +481,6 @@ function SettingsPrompt() {}if (isUpdate) {- // Update existing user-defined promptawait updatePrompt({refetchQueries: ['settingsPrompts'],variables: {@@ -517,7 +489,6 @@ function SettingsPrompt() {},});} else {- // Create new user-defined promptawait createPrompt({refetchQueries: ['settingsPrompts'],variables: {@@ -539,7 +510,7 @@ function SettingsPrompt() {const isUpdate = !!promptInfo.userHumanPrompt;- // For creation, check if the template is identical to the default+ // Submitting an unchanged template would create a no-op userDefined row that masks the default.if (!isUpdate && formData.template === promptInfo.defaultHumanTemplate) {return;}@@ -547,7 +518,6 @@ function SettingsPrompt() {try {setSubmitError(null);- // Get the real human prompt type from dataconst agentData = promptInfo.data as AgentPrompts;const humanPromptType = agentData.human?.type;@@ -558,7 +528,6 @@ function SettingsPrompt() {}if (isUpdate) {- // Update existing user-defined promptawait updatePrompt({refetchQueries: ['settingsPrompts'],variables: {@@ -567,7 +536,6 @@ function SettingsPrompt() {},});} else {- // Create new user-defined promptawait createPrompt({refetchQueries: ['settingsPrompts'],variables: {@@ -582,7 +550,6 @@ function SettingsPrompt() {}};- // Loading stateif (loading) {return (<>@@ -595,7 +562,6 @@ function SettingsPrompt() {);}- // Error stateif (error) {return (<>@@ -608,7 +574,6 @@ function SettingsPrompt() {);}- // Prompt not found stateif (!promptInfo) {return (<>@@ -623,11 +588,10 @@ function SettingsPrompt() {);}- // Templates for diff based on active tabconst currentTemplate = activeTab === 'system' ? systemTemplate : humanTemplate;const defaultTemplate = activeTab === 'system' ? promptInfo.defaultSystemTemplate : promptInfo.defaultHumanTemplate;- // Styles for ReactDiffViewer aligned with shadcn (Tailwind CSS vars)+ // ReactDiffViewer styles aligned with shadcn — uses Tailwind CSS vars rather than hard-coded colors.const diffStyles = {content: {fontFamily:diff --git a/frontend/src/pages/settings/settings-prompts.tsx b/frontend/src/pages/settings/settings-prompts.tsxindex 29fb140a..6b36e1df 100644--- a/frontend/src/pages/settings/settings-prompts.tsx+++ b/frontend/src/pages/settings/settings-prompts.tsx@@ -36,24 +36,24 @@ import {import { StatusCard } from '@/components/ui/status-card';import { useDeletePromptMutation, useSettingsPromptsQuery } from '@/graphql/types';import { usePageStorageKeys } from '@/hooks/use-page-storage-keys';-// Types for table data+type AgentPromptTableData = {- displayName: string; // Formatted display name+ displayName: string;hasHuman: boolean;hasSystem: boolean;humanStatus: 'Custom' | 'Default' | 'N/A';humanTemplate?: string;- humanType?: PromptType; // Type for human prompt lookup- name: string; // Original key (camelCase)+ humanType?: PromptType;+ name: string;systemStatus: 'Custom' | 'Default' | 'N/A';systemTemplate: string;- systemType?: PromptType; // Type for system prompt lookup+ systemType?: PromptType;};type ToolPromptTableData = {- displayName: string; // Formatted display name- name: string; // Original key (camelCase)- promptType?: PromptType; // Type for prompt lookup+ displayName: string;+ name: string;+ promptType?: PromptType;status: 'Custom' | 'Default' | 'N/A';template: string;};@@ -67,7 +67,6 @@ function SettingsPrompts() {// slots even though the page mounts two tables.const { table: tableStorageBase } = usePageStorageKeys();- // Reset dialog statesconst [resetDialogOpen, setResetDialogOpen] = useState(false);const [resetOperation, setResetOperation] = useState<null | {displayName: string;@@ -75,7 +74,7 @@ function SettingsPrompts() {type: 'all' | 'human' | 'system' | 'tool';}>(null);- // Three-way sorting handler: null -> asc -> desc -> null+ // Three-way sorting: null → asc → desc → null.const handleColumnSort = (column: {clearSorting: () => void;getIsSorted: () => 'asc' | 'desc' | false;@@ -92,12 +91,10 @@ function SettingsPrompts() {}};- // Handler for editing any prompt (agent or tool)const handlePromptEdit = (promptName: string) => {navigate(`/settings/prompts/${promptName}`);};- // Reset dialog handlersconst handleResetDialogOpen = (type: 'all' | 'human' | 'system' | 'tool',promptName: string,@@ -119,11 +116,9 @@ function SettingsPrompts() {const userDefined = data.settingsPrompts.userDefined || [];if (type === 'tool') {- // Handle tool prompt resetconst toolPrompt = tools?.[promptName as keyof typeof tools];if (toolPrompt?.type) {- // Find the user-defined prompt with matching typeconst userPrompt = userDefined.find((p) => p.type === toolPrompt.type);if (userPrompt) {@@ -134,7 +129,6 @@ function SettingsPrompts() {}}} else {- // Handle agent prompt resetconst agentPrompts = agents?.[promptName as keyof typeof agents] as AgentPrompts;if (agentPrompts) {@@ -191,7 +185,6 @@ function SettingsPrompts() {}};- // Helper function to check if reset is available for specific prompt typeconst canResetPrompt = (promptName: string, resetType: 'all' | 'human' | 'system' | 'tool'): boolean => {if (!data?.settingsPrompts?.default || !data?.settingsPrompts?.userDefined) {return false;@@ -237,7 +230,6 @@ function SettingsPrompts() {return false;};- // Transform agents data for tableconst getAgentPromptsData = (): AgentPromptTableData[] => {if (!data?.settingsPrompts?.default?.agents) {return [];@@ -247,12 +239,10 @@ function SettingsPrompts() {const userDefined = data.settingsPrompts.userDefined || [];const agentEntries: AgentPromptTableData[] = [];- // Helper function to format agent nameconst formatName = (key: string): string => {return key.replaceAll(/([A-Z])/g, ' $1').replace(/^./, (str) => str.toUpperCase());};- // Process each agentObject.entries(agents).forEach(([key, prompts]) => {if (key === '__typename') {return;@@ -261,7 +251,6 @@ function SettingsPrompts() {const systemType = (prompts as AgentPrompt | AgentPrompts)?.system?.type;const humanType = (prompts as AgentPrompts)?.human?.type;- // Check if user has custom promptsconst hasCustomSystem = userDefined.some((p) => p.type === systemType);const hasCustomHuman = humanType ? userDefined.some((p) => p.type === humanType) : false;@@ -288,7 +277,6 @@ function SettingsPrompts() {return agentEntries.sort((a, b) => a.name.localeCompare(b.name));};- // Transform tools data for tableconst getToolPromptsData = (): ToolPromptTableData[] => {if (!data?.settingsPrompts?.default?.tools) {return [];@@ -298,12 +286,10 @@ function SettingsPrompts() {const userDefined = data.settingsPrompts.userDefined || [];const toolEntries: ToolPromptTableData[] = [];- // Helper function to format tool nameconst formatName = (key: string): string => {return key.replaceAll(/([A-Z])/g, ' $1').replace(/^./, (str) => str.toUpperCase());};- // Process each toolObject.entries(tools).forEach(([key, prompt]) => {if (key === '__typename') {return;@@ -326,7 +312,6 @@ function SettingsPrompts() {return toolEntries.sort((a, b) => a.name.localeCompare(b.name));};- // Agent prompts table columnsconst agentColumns: ColumnDef<AgentPromptTableData>[] = [{accessorKey: 'displayName',@@ -499,7 +484,6 @@ function SettingsPrompts() {},];- // Tool prompts table columnsconst toolColumns: ColumnDef<ToolPromptTableData>[] = [{accessorKey: 'displayName',@@ -609,15 +593,12 @@ function SettingsPrompts() {},];- // Render sub-component for agent promptsconst renderAgentSubComponent = ({ row }: { row: any }) => {const agent = row.original as AgentPromptTableData;- // Find userDefined prompts for this agent typeconst userSystemPrompt = data?.settingsPrompts?.userDefined?.find((p) => p.type === agent.systemType);const userHumanPrompt = data?.settingsPrompts?.userDefined?.find((p) => p.type === agent.humanType);- // Use userDefined templates if available, otherwise use defaultconst systemTemplate = userSystemPrompt?.template || agent.systemTemplate;const humanTemplate = userHumanPrompt?.template || agent.humanTemplate;@@ -671,14 +652,11 @@ function SettingsPrompts() {);};- // Render sub-component for tool promptsconst renderToolSubComponent = ({ row }: { row: any }) => {const tool = row.original as ToolPromptTableData;- // Find userDefined prompt for this tool typeconst userToolPrompt = data?.settingsPrompts?.userDefined?.find((p) => p.type === tool.promptType);- // Use userDefined template if available, otherwise use defaultconst template = userToolPrompt?.template || tool.template;return (@@ -841,7 +819,6 @@ function SettingsPrompts() {<div className="flex flex-col gap-6"><SettingsPromptsHeader />- {/* Agent Prompts Section */}{agentPrompts.length > 0 && (<div className="flex flex-col gap-2"><div className="flex items-center gap-2">@@ -862,7 +839,6 @@ function SettingsPrompts() {</div>)}- {/* Tool Prompts Section */}{toolPrompts.length > 0 && (<div className="flex flex-col gap-2"><div className="flex items-center gap-2">diff --git a/frontend/src/pages/settings/settings-provider.tsx b/frontend/src/pages/settings/settings-provider.tsxindex fd385c72..07eaf8f7 100644--- a/frontend/src/pages/settings/settings-provider.tsx+++ b/frontend/src/pages/settings/settings-provider.tsx@@ -57,7 +57,6 @@ interface BaseInputProps {placeholder?: string;}-// Universal field components using useControllerinterface ControllerProps {control: any;disabled?: boolean;@@ -123,7 +122,6 @@ function FormComboboxItem({const [isOpen, setIsOpen] = useState(false);const [search, setSearch] = useState('');- // Filter options based on searchconst filteredOptions = options.filter((option) => option?.toLowerCase().includes(search?.toLowerCase()));const displayValue = field.value ?? '';@@ -316,12 +314,10 @@ function FormModelComboboxItem({const [isOpen, setIsOpen] = useState(false);const [search, setSearch] = useState('');- // Filter options based on searchconst filteredOptions = options.filter((option) => option.name?.toLowerCase().includes(search?.toLowerCase()));const displayValue = field.value ?? '';- // Format price for displayconst formatPrice = (price?: null | { cacheRead: number; cacheWrite: number; input: number; output: number },): string => {@@ -335,7 +331,6 @@ function FormModelComboboxItem({const basePrice = `$${formatValue(price.input)}/$${formatValue(price.output)}`;- // Add cache prices if availableconst hasCachePrices = (price.cacheRead && price.cacheRead > 0) || (price.cacheWrite && price.cacheWrite > 0);if (hasCachePrices) {@@ -460,7 +455,6 @@ function FormModelComboboxItem({);}-// Define agent configuration schemaconst agentConfigSchema = z.object({frequencyPenalty: z.preprocess(@@ -537,7 +531,6 @@ const agentConfigSchema = z}).optional();-// Define form schemaconst formSchema = z.object({agents: z.record(z.string(), agentConfigSchema).optional(),name: z.preprocess(@@ -547,15 +540,12 @@ const formSchema = z.object({type: z.preprocess((value) => value || '', z.string().min(1, 'Provider type is required')),});-// Type for agents field in formtype FormAgents = FormData['agents'];type FormData = z.infer<typeof formSchema>;-// Convert camelCase key to display name (e.g., 'simpleJson' -> 'Simple Json')const getName = (key: string): string => key.replaceAll(/([A-Z])/g, ' $1').replace(/^./, (item) => item.toUpperCase());-// Helper function to convert string to ReasoningEffort enumconst getReasoningEffort = (effort: null | string | undefined): null | ReasoningEffort => {if (!effort) {return null;@@ -580,7 +570,6 @@ const getReasoningEffort = (effort: null | string | undefined): null | Reasoning}};-// Helper function to convert form data to GraphQL inputconst transformFormToGraphQL = (formData: FormData,): {@@ -596,7 +585,7 @@ const transformFormToGraphQL = (maxLength: data?.maxLength ?? null,maxTokens: data?.maxTokens ?? null,minLength: data?.minLength ?? null,- model: data!.model, // After filter, data and model are guaranteed to exist+ model: data!.model,presencePenalty: data?.presencePenalty ?? null,price:data?.price &&@@ -633,7 +622,6 @@ const transformFormToGraphQL = (};};-// Helper function to recursively remove __typename from objectsconst normalizeGraphQLData = (obj: unknown): unknown => {if (obj === null || obj === undefined) {return obj;@@ -660,13 +648,11 @@ interface TestResultsDialogProps {results: any;}-// Component to render test results dialogfunction TestResultsDialog({ handleOpenChange, isOpen, results }: TestResultsDialogProps) {if (!results) {return null;}- // Transform results object to array, removing __typenameconst agentResults = Object.entries(results).filter(([key]) => key !== '__typename').map(([agentType, agentData]: [string, any]) => ({@@ -786,7 +772,6 @@ function TestResultsDialog({ handleOpenChange, isOpen, results }: TestResultsDia);}-// Static mapping of agent keys to GraphQL enum typesconst agentTypesMap: Record<string, AgentConfigType> = {adviser: AgentConfigType.Adviser,assistant: AgentConfigType.Assistant,@@ -803,7 +788,6 @@ const agentTypesMap: Record<string, AgentConfigType> = {simpleJson: AgentConfigType.SimpleJson,};-// Helper function to extract agent types from agents objectconst extractAgentTypes = (agents: unknown): null | string[] => {if (!agents || typeof agents !== 'object') {return null;@@ -853,7 +837,8 @@ function SettingsProvider() {const { isDirty } = useFormState({ control });- // Maintain a blocker state at the top of history when form is dirty+ // Push a synthetic history entry while the form is dirty so a browser-back can be intercepted+ // by popstate below — react-router's blocker doesn't cover the native back gesture.useEffect(() => {if (isDirty && !hasPushedBlockerStateRef.current) {window.history.pushState({ __pentagiBlock__: true }, '');@@ -861,7 +846,6 @@ function SettingsProvider() {}}, [isDirty]);- // Intercept browser back using popstate when form is dirtyuseEffect(() => {const handlePopState = () => {if (!isDirty) {@@ -869,16 +853,14 @@ function SettingsProvider() {}if (allowBrowserLeaveRef.current) {- // Allow single leave without blockingallowBrowserLeaveRef.current = false;return;}- // User navigated back off the blocker entry to the previous one; go forward to staysetPendingBrowserBack(true);setIsLeaveDialogOpen(true);- // Return to the blocker entry+ // Restore the blocker entry so the user stays on the page until they confirm.window.history.forward();};@@ -889,13 +871,10 @@ function SettingsProvider() {};}, [isDirty]);- // Watch selected typeconst selectedType = useWatch({ control, name: 'type' });- // Watch provider name for delete confirmation dialogconst providerName = useWatch({ control, name: 'name' });- // Read query parameters for form initialization (stable)const formQueryParams = useMemo(() => ({id: searchParams.get('id'),@@ -904,37 +883,29 @@ function SettingsProvider() {[searchParams],);- // Get dynamic agent types from dataconst getAgentTypes = () => {- // Try to get agents from specific sources in priority orderconst agentsSource =- // For new providers, use default provider for selected type(isNew &&selectedType &&data?.settingsProviders?.default?.[selectedType as keyof typeof data.settingsProviders.default]?.agents) ||- // For existing providers, use current provider's agents(!isNew &&providerId &&data?.settingsProviders?.userDefined?.find((p: Provider) => p.id == providerId)?.agents) ||- // Fallback to any available default provider(data?.settingsProviders?.default &&Object.values(data.settingsProviders.default).find((provider) => provider?.agents)?.agents) ||null;- // Extract and return agent types, or fallback to hardcoded listreturn extractAgentTypes(agentsSource) ?? Object.keys(agentTypesMap);};const agentTypes = getAgentTypes();- // Get available models filtered by selected provider typeconst availableModels = useMemo(() => {if (!data?.settingsProviders?.models || !selectedType) {return [];}- // Filter models by selected provider typeconst { models } = data.settingsProviders;const providerModels = models[selectedType as keyof typeof models];@@ -955,11 +926,10 @@ function SettingsProvider() {: null,thinking: model.thinking,}))- .filter((model) => model.name) // Remove any models without names+ .filter((model) => model.name).sort((a, b) => a.name.localeCompare(b.name));}, [data, selectedType]);- // Fill agents when provider type is selected (only for new providers)useEffect(() => {if (!isNew || !selectedType || !data?.settingsProviders?.default || availableModels.length === 0) {return;@@ -973,14 +943,9 @@ function SettingsProvider() {Object.entries(defaultProvider.agents).filter(([key]) => key !== '__typename').map(([key, data]) => {- // const agent = Object.fromEntries(- // Object.entries(data).filter(([key]) => key !== '__typename'),- // ) as AgentConfigInput;const agent = { ...data };- // Check if the model from defaultProvider exists in availableModelsif (agent.model && !availableModels.find((m) => m.name === agent.model)) {- // Use first available model if default model not foundagent.model = availableModels[0]?.name || agent.model;}@@ -993,10 +958,8 @@ function SettingsProvider() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [availableModels, data, isNew, selectedType]);- // Update query parameter when type changes (only for new providers)useEffect(() => {if (!isNew) {- // Clear query parameters for existing providersif (searchParams.size > 0) {setSearchParams({});}@@ -1004,21 +967,18 @@ function SettingsProvider() {return;}- // Don't update query params if we're copying from existing providerconst queryId = searchParams.get('id');if (queryId) {return;}- // Don't update query params on initial load if we're reading from query paramsconst queryType = searchParams.get('type');if (!selectedType && queryType) {return;}- // Update query parameter based on selected typesetSearchParams((prev) => {const params = new URLSearchParams(prev);@@ -1030,9 +990,8 @@ function SettingsProvider() {return params;});- }, [selectedType, setSearchParams, isNew, searchParams]); // Include searchParams since we read from it+ }, [selectedType, setSearchParams, isNew, searchParams]);- // Fill form with data when availableuseEffect(() => {if (!data?.settingsProviders) {return;@@ -1041,11 +1000,9 @@ function SettingsProvider() {const providers = data.settingsProviders;if (isNew || !providerId) {- // For new provider, start with empty form but check for type query parameterconst queryType = formQueryParams.type ?? undefined;const queryId = formQueryParams.id;- // If we have an id in query params, copy from existing providerif (queryId && data?.settingsProviders?.userDefined) {const sourceProvider = data.settingsProviders.userDefined.find((p: Provider) => p.id == queryId);@@ -1071,8 +1028,8 @@ function SettingsProvider() {});}- // Default new provider form - but only if selectedType is not set- // to avoid conflicts with agent filling useEffect+ // Bail out of the empty-form reset when `selectedType` is set — the agent-filling+ // effect above is the source of truth in that case and would fight us.if (!selectedType) {reset({agents: {},@@ -1103,8 +1060,7 @@ function SettingsProvider() {}, [data, formQueryParams, isNew, providerId, selectedType]);const handleSubmit = async () => {- // Get all form data including disabled fields- // Note: getValues() excludes disabled fields, watch() includes them+ // watch() — not getValues() — because disabled fields must be included in the payload.const formData = watch();try {@@ -1113,13 +1069,11 @@ function SettingsProvider() {const mutationData = transformFormToGraphQL(formData);if (isNew) {- // Create new providerawait createProvider({refetchQueries: ['settingsProviders'],variables: mutationData,});} else {- // Update existing providerawait updateProvider({refetchQueries: ['settingsProviders'],variables: {@@ -1129,7 +1083,6 @@ function SettingsProvider() {});}- // Navigate back to providers list on successnavigate('/settings/providers');} catch (error) {console.error('Submit error:', error);@@ -1158,7 +1111,6 @@ function SettingsProvider() {variables: { providerId },});- // Navigate back to providers list on successnavigate('/settings/providers');} catch (error) {console.error('Delete error:', error);@@ -1166,26 +1118,21 @@ function SettingsProvider() {}};- // Test entire provider (all agents)const handleTest = async () => {- // Trigger form validationconst isValid = await trigger();if (!isValid) {const { errors } = formState;- // Helper function to format field names for displayconst formatFieldName = (fieldPath: string): string => {return fieldPath.split('.').map((part) => {- // Capitalize first letter and add spaces before uppercase lettersreturn part.charAt(0).toUpperCase() + part.slice(1).replaceAll(/([A-Z])/g, ' $1');}).join(' → ');};- // Show validation errors to userconst errorMessages = Object.entries(errors).map(([field, error]: [string, any]) => {if (error?.message) {@@ -1193,7 +1140,6 @@ function SettingsProvider() {}if (error && typeof error === 'object') {- // Handle nested errors (like agents.simple.model)return Object.entries(error).map(([subField, subError]: [string, any]) => {if (subError?.message) {@@ -1232,7 +1178,6 @@ function SettingsProvider() {try {setSubmitError(null);- // Get form data and transform it - including disabled fieldsconst formData = watch();const { agents, type } = transformFormToGraphQL(formData);const result = await testProvider({@@ -1250,9 +1195,7 @@ function SettingsProvider() {}};- // Test a single agent (uses testAgent where supported, otherwise falls back to filtered provider test)const handleTestAgent = async (agentKey: string) => {- // Validate only fields for this agent and general required fieldsconst isValid = await trigger();if (!isValid) {@@ -1308,7 +1251,7 @@ function SettingsProvider() {try {setSubmitError(null);setCurrentAgentKey(agentKey);- // Note: getValues() excludes disabled fields, watch() includes them+ // watch() — not getValues() — because disabled fields must be included in the payload.const formData = watch();const { agents, type } = transformFormToGraphQL(formData);@@ -1343,7 +1286,7 @@ function SettingsProvider() {if (pendingBrowserBack) {allowBrowserLeaveRef.current = true;setPendingBrowserBack(false);- // Skip the blocker entry and go to the real previous page+ // Step over the synthetic blocker entry into the actual previous page.window.history.go(-2);return;diff --git a/frontend/src/pages/settings/settings-providers.tsx b/frontend/src/pages/settings/settings-providers.tsxindex a51a01bc..db4bd498 100644--- a/frontend/src/pages/settings/settings-providers.tsx+++ b/frontend/src/pages/settings/settings-providers.tsx@@ -267,11 +267,9 @@ function SettingsProviders() {return <div className="text-muted-foreground p-4 text-sm">No agent configuration available</div>;}- // Convert camelCase key to display name (e.g., 'simpleJson' -> 'Simple Json')const getName = (key: string): string =>key.replaceAll(/([A-Z])/g, ' $1').replace(/^./, (item) => item.toUpperCase());- // Recursively extract all fields from an object, flattening nested objectsconst getFields = (obj: any, prefix = ''): { label: string; value: boolean | number | string }[] => {if (!obj || typeof obj !== 'object') {return [];@@ -288,7 +286,6 @@ function SettingsProviders() {});};- // Dynamically create agent types from object keysconst agentTypes = Object.entries(agents).filter(([key]) => key !== '__typename').map(([key, data]) => ({@@ -304,7 +301,6 @@ function SettingsProviders() {<hr className="border-muted-foreground/20 my-4" /><div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-5">{agentTypes.map(({ data, key, name }) => {- // Get all fields from data, including nested objectsconst fields = data ? getFields(data) : [];return (@@ -384,7 +380,6 @@ function SettingsProviders() {const providers = data?.settingsProviders?.userDefined || [];- // Check if providers list is emptyif (providers.length === 0) {return (<div className="flex flex-col gap-4">diff --git a/frontend/src/pages/templates/template.tsx b/frontend/src/pages/templates/template.tsxindex 4b35139c..24706a23 100644--- a/frontend/src/pages/templates/template.tsx+++ b/frontend/src/pages/templates/template.tsx@@ -270,7 +270,6 @@ function Template() {stopEdit: handleTemplateRenameCancel,} = useInlineEdit({ resetKey: templateId });- // Fetch template data when editingconst { data: templateData, loading: isLoadingTemplate } = useFlowTemplateQuery({skip: isNew || !templateId,variables: templateId && !isNew ? { templateId } : undefined,@@ -284,7 +283,6 @@ function Template() {const { control, formState, getValues, handleSubmit: handleFormSubmit, reset, setValue } = form;- // Load template data into form when query completesuseEffect(() => {if (isNew || !templateData?.flowTemplate) {return;@@ -294,7 +292,6 @@ function Template() {reset({ text, title }, { keepDefaultValues: false });}, [templateData, isNew, reset]);- // Check if form has unsaved changesconst hasUnsavedChanges = formState.isDirty;const templateName = templateData?.flowTemplate?.title ?? null;@@ -655,7 +652,6 @@ function Template() {[isMobile, isAsideOpen, asideContent],);- // Show loading spinner when fetching template dataif (!isNew && isLoadingTemplate) {return (<>@@ -667,7 +663,6 @@ function Template() {);}- // Handle template not foundif (!isNew && !isLoadingTemplate && !templateData?.flowTemplate) {return (<>diff --git a/frontend/src/providers/favorites-provider.tsx b/frontend/src/providers/favorites-provider.tsxindex db7b362e..53f506be 100644--- a/frontend/src/providers/favorites-provider.tsx+++ b/frontend/src/providers/favorites-provider.tsx@@ -39,27 +39,20 @@ const FAVORITES_STORAGE_KEY = 'favorites';export function FavoritesProvider({ children }: FavoritesProviderProps) {const { authInfo, isAuthenticated } = useUser();- // Only fetch user preferences if user is authenticated and not a guest- // authInfo must exist and type must be 'user' or 'api' (not 'guest' and not null/undefined)- // Also check isAuthenticated() to ensure session is validconst shouldFetchPreferences = Boolean(authInfo && authInfo.type !== 'guest' && isAuthenticated());- // GraphQL query for user preferencesconst { data: userPreferencesData, loading: isLoadingPreferences } = useSettingsUserQuery({fetchPolicy: 'cache-and-network',skip: !shouldFetchPreferences,});- // GraphQL mutationsconst [addFavoriteFlowMutation] = useAddFavoriteFlowMutation();const [deleteFavoriteFlowMutation] = useDeleteFavoriteFlowMutation();- // GraphQL subscription (only for authenticated users)useSettingsUserUpdatedSubscription({skip: !shouldFetchPreferences,});- // Get favorite flow IDs from GraphQL as numbersconst actualFavoriteFlowIds = useMemo(() => {const ids = userPreferencesData?.settingsUser?.favoriteFlows ?? [];@@ -80,7 +73,6 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {},);- // Migration: sync localStorage favorites to backend on first loaduseEffect(() => {const migrateLocalStorageFavorites = async () => {try {@@ -96,7 +88,6 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {return;}- // Get current user's favorites from localStorageconst userIds = Object.keys(parsed);if (userIds.length === 0) {@@ -116,15 +107,12 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {const localFavorites = parsed[userId]?.flows ?? [];if (localFavorites.length === 0) {- // No local favorites to migratelocalStorage.removeItem(FAVORITES_STORAGE_KEY);return;}- // Migrate each favorite to backendfor (const flow of localFavorites) {- // Check if already in backendif (!favoriteFlowIds.includes(flow.id)) {try {await addFavoriteFlowMutation({@@ -136,7 +124,6 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {}}- // Clear localStorage after successful migrationlocalStorage.removeItem(FAVORITES_STORAGE_KEY);Log.info('Successfully migrated favorites from localStorage to backend');} catch (error) {@@ -144,8 +131,6 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {}};- // Only run migration if we have loaded preferences and localStorage data exists- // and user is authenticated (not a guest)if (!isLoadingPreferences && userPreferencesData && shouldFetchPreferences) {migrateLocalStorageFavorites();}diff --git a/frontend/src/providers/flow-provider.tsx b/frontend/src/providers/flow-provider.tsxindex 45898aef..a3f27a3e 100644--- a/frontend/src/providers/flow-provider.tsx+++ b/frontend/src/providers/flow-provider.tsx@@ -95,20 +95,16 @@ export function FlowProvider({ children }: FlowProviderProps) {const explicitSelection = selectedAssistantIds[flowId];- // If there's an explicit selection (including null for "no selection")if (explicitSelection !== undefined) {- // If explicitly set to null, return nullif (explicitSelection === null) {return null;}- // If the selected assistant still exists in the list, return itif (assistants.some((assistant) => assistant.id === explicitSelection)) {return explicitSelection;}}- // Otherwise, auto-select the first assistantreturn assistants?.[0]?.id ?? null;}, [flowId, selectedAssistantIds, assistants]);@@ -119,15 +115,13 @@ export function FlowProvider({ children }: FlowProviderProps) {variables: { assistantId: selectedAssistantId ?? '', flowId: flowId ?? '' },});- // Subscriptions — skip until the initial flow query has loaded- // to ensure cache fields exist before subscription data arrives+ // Skip subscriptions until the initial flow query has loaded so cache fields exist+ // before subscription deltas arrive.const subscriptionVariables = useMemo(() => ({ flowId: flowId || '' }), [flowId]);const subscriptionSkip = !flowId || isLoading;- // Global flow subscription - updates flow status (e.g., when stopped/finished)useFlowUpdatedSubscription();- // Flow-specific subscriptions that depend on the selected flowuseTaskCreatedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });useTaskUpdatedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });useScreenshotAddedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });@@ -138,7 +132,6 @@ export function FlowProvider({ children }: FlowProviderProps) {useSearchLogAddedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });useVectorStoreLogAddedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });- // Assistant-specific subscriptionsuseAssistantCreatedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });useAssistantUpdatedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });useAssistantDeletedSubscription({ skip: subscriptionSkip, variables: subscriptionVariables });@@ -167,7 +160,6 @@ export function FlowProvider({ children }: FlowProviderProps) {selectAssistant(null);}, [flowId, selectAssistant]);- // Mutationsconst [putUserInput] = usePutUserInputMutation();const [stopFlowMutation] = useStopFlowMutation();const [createAssistantMutation] = useCreateAssistantMutation();@@ -177,7 +169,6 @@ export function FlowProvider({ children }: FlowProviderProps) {const flowStatus = useMemo(() => flowData?.flow?.status, [flowData?.flow?.status]);- // Show toast notification when flow loading error occurs.// A single Postgres "no rows in result set" surfaces here every time a sibling// query/subscription retries against an invalid flow id; without a stable// toast id Sonner would stack 8 copies of the same message before the page@@ -304,7 +295,6 @@ export function FlowProvider({ children }: FlowProviderProps) {useAgents,},});- // Cache will be automatically updated via subscriptions} catch (error) {const description =error instanceof Error ? error.message : 'An error occurred while calling assistant';@@ -330,7 +320,6 @@ export function FlowProvider({ children }: FlowProviderProps) {flowId,},});- // Cache will be automatically updated via mutation policy and subscriptions} catch (error) {const description =error instanceof Error ? error.message : 'An error occurred while stopping assistant';diff --git a/frontend/src/providers/flows-provider.tsx b/frontend/src/providers/flows-provider.tsxindex 0ad36d4d..acc6b3db 100644--- a/frontend/src/providers/flows-provider.tsx+++ b/frontend/src/providers/flows-provider.tsx@@ -37,7 +37,6 @@ interface FlowsProviderProps {}export function FlowsProvider({ children }: FlowsProviderProps) {- // Query for flows listconst {data: flowsData,error: flowsError,@@ -54,7 +53,6 @@ export function FlowsProvider({ children }: FlowsProviderProps) {useFlowDeletedSubscription();useFlowUpdatedSubscription();- // Show toast notification when flows loading error occursuseEffect(() => {if (flowsError) {toast.error('Error loading flows', {@@ -64,7 +62,6 @@ export function FlowsProvider({ children }: FlowsProviderProps) {}}, [flowsError]);- // Mutationsconst [createFlowMutation] = useCreateFlowMutation();const [createAssistantMutation] = useCreateAssistantMutation();const [deleteFlowMutation] = useDeleteFlowMutation();@@ -206,7 +203,6 @@ export function FlowsProvider({ children }: FlowsProviderProps) {await finishFlowMutation({variables: { flowId },});- // Cache will be automatically updated via mutation policy and flowUpdated subscriptiontoast.success('Flow finished successfully', {description: flowDescription,diff --git a/frontend/src/providers/providers-provider.tsx b/frontend/src/providers/providers-provider.tsxindex 7e1d012f..1f03874c 100644--- a/frontend/src/providers/providers-provider.tsx+++ b/frontend/src/providers/providers-provider.tsx@@ -27,21 +27,17 @@ export function ProvidersProvider({ children }: ProvidersProviderProps) {skip: !isAuthenticated(),});- // Create sorted providers list to ensure consistent orderconst providers = sortProviders(providersData?.providers || []);- // Store selected provider name instead of the provider objectconst [selectedProviderName, setSelectedProviderName] = useState<null | string>(() => {return localStorage.getItem(SELECTED_PROVIDER_KEY);});- // Compute selected provider from providers list and selected nameconst selectedProvider = useMemo(() => {if (providers.length === 0) {return null;}- // Try to find saved providerif (selectedProviderName) {const savedProvider = findProviderByName(selectedProviderName, providers);@@ -50,11 +46,9 @@ export function ProvidersProvider({ children }: ProvidersProviderProps) {}}- // If no saved provider or not found, return first providerreturn providers[0] ?? null;}, [providers, selectedProviderName]);- // Save to localStorage when selected provider changesuseEffect(() => {if (selectedProvider) {localStorage.setItem(SELECTED_PROVIDER_KEY, selectedProvider.name);diff --git a/frontend/src/providers/sidebar-flows-provider.tsx b/frontend/src/providers/sidebar-flows-provider.tsxindex b3815e7d..2a766e9d 100644--- a/frontend/src/providers/sidebar-flows-provider.tsx+++ b/frontend/src/providers/sidebar-flows-provider.tsx@@ -17,7 +17,6 @@ interface SidebarFlowsProviderProps {}export function SidebarFlowsProvider({ children }: SidebarFlowsProviderProps) {- // Single query for sidebar flows with cache-first policy// Subscriptions are handled by FlowsProvider in FlowsLayoutconst { data: flowsData } = useFlowsQuery({fetchPolicy: 'cache-first',diff --git a/frontend/src/providers/system-settings-provider.tsx b/frontend/src/providers/system-settings-provider.tsxindex 5db2579c..7cd60d51 100644--- a/frontend/src/providers/system-settings-provider.tsx+++ b/frontend/src/providers/system-settings-provider.tsx@@ -17,7 +17,6 @@ const SystemSettingsContext = createContext<SettingsContextType | undefined>(undexport function SystemSettingsProvider({ children }: { children: ReactNode }) {const { isAuthenticated } = useUser();- // Load settings via GraphQL query only when user is authenticatedconst { data: settingsData, loading } = useSettingsQuery({skip: !isAuthenticated(),});diff --git a/frontend/src/providers/templates-provider.tsx b/frontend/src/providers/templates-provider.tsxindex ee4aa7fc..34eaf236 100644--- a/frontend/src/providers/templates-provider.tsx+++ b/frontend/src/providers/templates-provider.tsx@@ -42,18 +42,15 @@ export function TemplatesProvider({ children }: TemplatesProviderProps) {const shouldFetchTemplates = Boolean(authInfo && authInfo.type !== 'guest' && isAuthenticated());- // GraphQL query for templatesconst { data: templatesData, loading: isLoadingTemplates } = useFlowTemplatesQuery({fetchPolicy: 'cache-and-network',skip: !shouldFetchTemplates,});- // GraphQL mutationsconst [createTemplateMutation] = useCreateFlowTemplateMutation();const [updateTemplateMutation] = useUpdateFlowTemplateMutation();const [deleteTemplateMutation] = useDeleteFlowTemplateMutation();- // GraphQL subscriptions (only for authenticated users)useFlowTemplateCreatedSubscription({skip: !shouldFetchTemplates,});@@ -66,7 +63,6 @@ export function TemplatesProvider({ children }: TemplatesProviderProps) {skip: !shouldFetchTemplates,});- // Convert GraphQL templates to Template interfaceconst templates = useMemo(() => {const rawTemplates = templatesData?.flowTemplates ?? [];diff --git a/frontend/src/providers/theme-provider.tsx b/frontend/src/providers/theme-provider.tsxindex 548e3c84..8bbd819b 100644--- a/frontend/src/providers/theme-provider.tsx+++ b/frontend/src/providers/theme-provider.tsx@@ -33,7 +33,6 @@ export function ThemeProvider({const [theme, setTheme] = useState<Theme>(() => {const storedTheme = localStorage.getItem(storageKey);- // If no stored theme, use system (default)if (!storedTheme) {return 'system';}@@ -60,10 +59,8 @@ export function ThemeProvider({const value = {setTheme: (theme: Theme) => {if (theme === 'system') {- // Remove from localStorage when system is selectedlocalStorage.removeItem(storageKey);} else {- // Store only light or dark themeslocalStorage.setItem(storageKey, theme);}diff --git a/frontend/src/providers/user-provider.tsx b/frontend/src/providers/user-provider.tsxindex ee6df25b..73ae640e 100644--- a/frontend/src/providers/user-provider.tsx+++ b/frontend/src/providers/user-provider.tsx@@ -45,7 +45,6 @@ export function UserProvider({ children }: { children: ReactNode }) {const [authInfo, setAuthInfo] = useState<AuthInfo | null>(null);const [isLoading, setIsLoading] = useState(true);- // Load auth data from localStorage on mount, then load from API if neededuseEffect(() => {const initializeAuth = async () => {let shouldFetchFromApi = false;@@ -59,7 +58,7 @@ export function UserProvider({ children }: { children: ReactNode }) {if (parsedAuthInfo) {setAuthInfo(parsedAuthInfo);- // For guest users, always fetch fresh data from API to get updated OAuth providers+ // Guests need a fresh /info to pick up updated OAuth providers list.if (parsedAuthInfo.type === 'guest') {shouldFetchFromApi = true;} else {@@ -72,27 +71,23 @@ export function UserProvider({ children }: { children: ReactNode }) {shouldFetchFromApi = true;}} catch {- // If parsing fails, clear invalid datalocalStorage.removeItem(AUTH_STORAGE_KEY);shouldFetchFromApi = true;}- // Load from API for guests or when localStorage is emptyif (shouldFetchFromApi) {try {const info = await api.get<AuthInfo>('/info');if (info?.status === 'success' && info.data) {- // Set authInfo even for guest (contains providers list)setAuthInfo(info.data);- // Update localStorage with fresh guest dataif (info.data.type === 'guest') {localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(info.data));}}} catch {- // ignore+ // swallow: /info is non-critical here, the rest of the app will retry on demand} finally {setIsLoading(false);}@@ -104,7 +99,6 @@ export function UserProvider({ children }: { children: ReactNode }) {const setAuth = useCallback((newAuthInfo: AuthInfo) => {setAuthInfo(newAuthInfo);- // Persist to localStoragelocalStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(newAuthInfo));}, []);@@ -138,7 +132,6 @@ export function UserProvider({ children }: { children: ReactNode }) {}}, [setAuth, clearAuth]);- // Refresh auth info when on login page to get fresh OAuth providers listuseEffect(() => {if (location.pathname === '/login' && !isLoading) {// eslint-disable-next-line react-hooks/set-state-in-effect -- refreshAuthInfo's setState runs after an async fetch, not synchronously@@ -176,7 +169,7 @@ export function UserProvider({ children }: { children: ReactNode }) {return { error: errorMessage, success: false };}- // After login, backend set cookie, so we need to get fresh auth info+ // Backend sets the session cookie on /auth/login — fetch /info to materialize the user.const infoResponse = await api.get<AuthInfo>('/info');if (infoResponse?.status !== 'success' || !infoResponse.data) {@@ -186,17 +179,14 @@ export function UserProvider({ children }: { children: ReactNode }) {return { error: errorMessage, success: false };}- // Save auth infosetAuth(infoResponse.data);- // Check if password change is required for local usersif (infoResponse.data.user?.type === 'local' && infoResponse.data.user.password_change_required) {toast.warning('Password change required');return { passwordChangeRequired: true, success: true };}- // toast.success('Successfully logged in');return { success: true };} catch {const errorMessage = 'Login failed. Please try again.';@@ -298,13 +288,11 @@ export function UserProvider({ children }: { children: ReactNode }) {if (info?.status === 'success' && info.data?.type === 'user') {setAuth(info.data);cleanup();- // toast.success('Successfully logged in');resolve({ success: true });return;}} catch (error) {- // In case of error, fall through to common handling belowconsole.error('Error during OAuth result handling:', error);}}@@ -324,17 +312,14 @@ export function UserProvider({ children }: { children: ReactNode }) {[setAuth],);- // Update auth state on route changesuseEffect(() => {const updateAuth = async () => {- // Skip for public routesconst publicRoutes = ['/login', '/oauth/result'];if (publicRoutes.includes(location.pathname)) {return;}- // Check if user is authenticatedif (!isAuthenticated()) {return;}@@ -366,7 +351,6 @@ export function UserProvider({ children }: { children: ReactNode }) {// eslint-disable-next-line react-hooks/exhaustive-deps}, [location.pathname]);- // Listen for auth refresh events from Apollo ClientuseEffect(() => {const handleAuthRefresh = () => {refreshAuthInfo();