Files
Momento/memento-note/hooks/use-auto-tagging.ts
Sepehr Ramezani 1c659ce42f fix: comprehensive security, consistency, and dead code cleanup
Security:
- Add auth + file type/size validation to upload API
- Add admin auth to /api/admin/ endpoints
- Add SSRF protection to scrape action
- Whitelist fields in PUT /api/notes/[id] to prevent mass assignment
- Protect /lab, /agents, /chat, /canvas, /notebooks routes in middleware

AI provider fixes:
- Add deepseek/openrouter to factory ProviderType (was silently falling back to ollama)
- Fix title-suggestion.service.ts to use factory instead of hardcoded OpenAI
- Fix getAIProvider→getChatProvider in memory-echo, notebook-summary, agent-executor
- Fix getAIProvider→getTagsProvider in notebook-suggestion, title-suggestions, transform-markdown

Functional bugs:
- Fix ALLOW_REGISTRATION AND→OR logic
- Fix note-editor.tsx passing stale props to useAutoTagging instead of local state
- Fix stale Note.embedding type (migrated to NoteEmbedding table)
- Remove hardcoded SQLite path from prisma.ts

Frontend:
- Add AbortController to useAutoTagging and useTitleSuggestions hooks
- Add error rollback to optimistic UI in note-inline-editor
- Remove stale closure over notebookId/language in useAutoTagging

Cleanup:
- Rename docker-compose from keepnotes→memento
- Remove unused unstable_cache import from config.ts
- Remove dead useUndoRedo hook
- Fix TagSuggestion type (add isNewLabel, reasoning)
- Remove dead AIConfig/AIProviderType types
- Fix ghost-tags unused isEmpty var and as any cast
- Fix note-editor titleSuggestions typed as any[]

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-04-21 22:22:02 +02:00

106 lines
3.1 KiB
TypeScript

import { useLanguage } from '@/lib/i18n'
import { useState, useEffect, useRef, useCallback } from 'react';
import { useDebounce } from './use-debounce';
import { TagSuggestion } from '@/lib/ai/types';
interface UseAutoTaggingProps {
content: string;
notebookId?: string | null;
enabled?: boolean;
}
export function useAutoTagging({ content, notebookId, enabled = true }: UseAutoTaggingProps) {
const { language } = useLanguage();
const [suggestions, setSuggestions] = useState<TagSuggestion[]>([]);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [error, setError] = useState<string | null>(null);
// Debounce content by 1.5s
const debouncedContent = useDebounce(content, 1500);
// Track previous notebookId to detect when note is moved to a notebook
const previousNotebookId = useRef<string | null | undefined>(notebookId);
// AbortController for cancelling in-flight requests
const abortRef = useRef<AbortController | null>(null);
const analyzeContent = useCallback(async (contentToAnalyze: string, currentNotebookId?: string | null, currentLanguage?: string) => {
if (!contentToAnalyze || contentToAnalyze.length < 10) {
setSuggestions([]);
return;
}
// Cancel previous request
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setIsAnalyzing(true);
setError(null);
try {
const response = await fetch('/api/ai/tags', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: contentToAnalyze,
notebookId: currentNotebookId || undefined,
language: currentLanguage || document.documentElement.lang || 'en',
}),
signal: controller.signal,
});
if (controller.signal.aborted) return;
if (!response.ok) {
throw new Error('Error during analysis');
}
const data = await response.json();
setSuggestions(data.tags || []);
} catch (err: any) {
if (err.name === 'AbortError') return;
setError('Failed to generate suggestions');
} finally {
if (!controller.signal.aborted) {
setIsAnalyzing(false);
}
}
}, []);
// Trigger on content change
useEffect(() => {
if (!enabled) {
setSuggestions([]);
return;
}
analyzeContent(debouncedContent, notebookId, language);
}, [debouncedContent, enabled, notebookId, language, analyzeContent]);
// Trigger when notebookId changes from null/undefined to a value
useEffect(() => {
if (!enabled) return;
const prev = previousNotebookId.current;
previousNotebookId.current = notebookId;
const wasMovedToNotebook = (prev === null || prev === undefined) && notebookId;
if (wasMovedToNotebook && content && content.length >= 10) {
analyzeContent(content, notebookId, language);
}
}, [notebookId, content, enabled, language, analyzeContent]);
// Cleanup on unmount
useEffect(() => {
return () => { abortRef.current?.abort(); };
}, []);
return {
suggestions,
isAnalyzing,
error,
clearSuggestions: () => setSuggestions([]),
};
}