feat(ai): implement intelligent auto-tagging system

- Added multi-provider AI infrastructure (OpenAI/Ollama)
- Implemented real-time tag suggestions with debounced analysis
- Created AI diagnostics and database maintenance tools in Settings
- Added automated garbage collection for orphan labels
- Refined UX with deterministic color hashing and interactive ghost tags
This commit is contained in:
2026-01-08 22:59:52 +01:00
parent 6f4d758e5c
commit 3c4b9d6176
27 changed files with 1336 additions and 138 deletions

View File

@@ -170,6 +170,39 @@ export async function createNote(data: {
}
}
// Helper to cleanup orphan labels
async function cleanupOrphanLabels(userId: string, candidateLabels: string[]) {
if (!candidateLabels || candidateLabels.length === 0) return
for (const labelName of candidateLabels) {
// Check if label is used in any other note
// Note: We search for the label name within the JSON string array
// This is a rough check but effective for JSON arrays like ["Label1","Label2"]
const count = await prisma.note.count({
where: {
userId,
labels: {
contains: `"${labelName}"`
}
}
})
if (count === 0) {
console.log(`Cleaning up orphan label: ${labelName}`)
try {
await prisma.label.deleteMany({
where: {
userId,
name: labelName
}
})
} catch (e) {
console.error(`Failed to delete orphan label ${labelName}:`, e)
}
}
}
}
// Update a note
export async function updateNote(id: string, data: {
title?: string | null
@@ -189,6 +222,14 @@ export async function updateNote(id: string, data: {
if (!session?.user?.id) throw new Error('Unauthorized');
try {
// Get old note state to compare labels
const oldNote = await prisma.note.findUnique({
where: { id, userId: session.user.id },
select: { labels: true }
})
const oldLabels: string[] = oldNote?.labels ? JSON.parse(oldNote.labels) : []
// Stringify JSON fields if they exist
const updateData: any = { ...data }
if ('checkItems' in data) {
@@ -213,6 +254,15 @@ export async function updateNote(id: string, data: {
data: updateData
})
// Cleanup orphan labels if labels changed
if (data.labels && oldLabels.length > 0) {
const removedLabels = oldLabels.filter(l => !data.labels?.includes(l))
if (removedLabels.length > 0) {
// Execute async without awaiting to not block response
cleanupOrphanLabels(session.user.id, removedLabels)
}
}
revalidatePath('/')
return parseNote(note)
} catch (error) {
@@ -227,6 +277,13 @@ export async function deleteNote(id: string) {
if (!session?.user?.id) throw new Error('Unauthorized');
try {
// Get labels before delete
const note = await prisma.note.findUnique({
where: { id, userId: session.user.id },
select: { labels: true }
})
const labels: string[] = note?.labels ? JSON.parse(note.labels) : []
await prisma.note.delete({
where: {
id,
@@ -234,6 +291,11 @@ export async function deleteNote(id: string) {
}
})
// Cleanup potential orphans
if (labels.length > 0) {
cleanupOrphanLabels(session.user.id, labels)
}
revalidatePath('/')
return { success: true }
} catch (error) {
@@ -344,6 +406,61 @@ export async function reorderNotes(draggedId: string, targetId: string) {
}
}
// Public action to manually trigger cleanup
export async function cleanupAllOrphans() {
const session = await auth();
if (!session?.user?.id) throw new Error('Unauthorized');
const userId = session.user.id;
let deletedCount = 0;
try {
// 1. Get all labels defined in Label table
const allDefinedLabels = await prisma.label.findMany({
where: { userId },
select: { id: true, name: true }
})
// 2. Get all used labels from Notes (fetch only labels column)
const allNotes = await prisma.note.findMany({
where: { userId },
select: { labels: true }
})
// 3. Build a Set of all used label names
const usedLabelsSet = new Set<string>();
allNotes.forEach(note => {
if (note.labels) {
try {
const parsedLabels: string[] = JSON.parse(note.labels);
if (Array.isArray(parsedLabels)) {
parsedLabels.forEach(l => usedLabelsSet.add(l.toLowerCase())); // Normalize to lowercase for comparison
}
} catch (e) {
// Ignore parse errors
}
}
});
// 4. Identify orphans
const orphans = allDefinedLabels.filter(label => !usedLabelsSet.has(label.name.toLowerCase()));
// 5. Delete orphans
for (const orphan of orphans) {
console.log(`Deleting orphan label: ${orphan.name}`);
await prisma.label.delete({ where: { id: orphan.id } });
deletedCount++;
}
revalidatePath('/')
return { success: true, count: deletedCount }
} catch (error) {
console.error('Error cleaning up orphans:', error)
throw new Error('Failed to cleanup database')
}
}
// Update full order of notes
export async function updateFullOrder(ids: string[]) {
const session = await auth();