Files
botsmann/hooks/useDocumentChat.ts
T
Mao NakamotoandClaude Opus 4.8 542d558f1f refactor(hooks): adopt eslint-plugin-react-hooks v6 rules (Next 16)
Re-enables the three React-Compiler-era rules deferred in #114
(set-state-in-effect, error-boundaries, immutability) — all now ON — and
resolves every violation with a real fix or a justified, documented exception.

error-boundaries (12 → 0, real fix):
- app/blog/[slug]/page.tsx wrapped its whole render in try/catch that only
  re-threw. Removed it: notFound()/render errors now propagate to Next's
  not-found.tsx / error.tsx as intended (the catch also mislogged notFound()).

immutability (5 → 0, real fix):
- The auth pages assigned window.location.href during render. Moved each
  redirect into a useEffect (above the early returns for rules-of-hooks),
  preserving the full-page navigation while keeping render pure.
  signin, signup, forgot-password, verify-email (×2).

set-state-in-effect (13 → 0, justified inline disables):
- Every case is a legitimate effect use — external-system sync (Supabase auth,
  API loads), browser-only hydration (localStorage, client-mount), or seeding
  editable state from async-loaded data. Forcing them off-effect would add
  complexity or risk behaviour changes to auth/data code, so each carries an
  eslint-disable-next-line with a specific reason. The rule stays ON to catch
  genuinely-avoidable derived-state-in-effect in future code.

Verified: eslint . (0 problems), prettier, tsc --noEmit, next build, jest 227 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-26 12:24:46 +02:00

191 lines
5.4 KiB
TypeScript

import { useState, useEffect, useRef, useCallback, type FormEvent } from 'react';
import { conversationToasts } from '@/lib/toast';
import type { Conversation, ConversationMessage, MessageSource } from '@/types/conversation';
export interface ChatMessage {
id?: string;
role: 'user' | 'assistant';
content: string;
sources?: MessageSource[];
}
interface UseDocumentChatOptions {
selectedDocId: string | null;
}
export const useDocumentChat = ({ selectedDocId }: UseDocumentChatOptions) => {
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
const [chatInput, setChatInput] = useState('');
const [chatLoading, setChatLoading] = useState(false);
const [activeConversationId, setActiveConversationId] = useState<string | null>(null);
const [conversationRefreshTrigger, setConversationRefreshTrigger] = useState(0);
const chatEndRef = useRef<HTMLDivElement>(null);
// Scroll to bottom of chat
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [chatMessages]);
// Load conversation messages when active conversation changes
useEffect(() => {
if (!activeConversationId) {
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets messages when the active conversation clears
setChatMessages([]);
return;
}
const loadConversation = async () => {
try {
const response = await fetch(`/api/conversations/${activeConversationId}`);
const data = await response.json();
if (data.success && data.data?.conversation) {
const conversation: Conversation & { messages: ConversationMessage[] } =
data.data.conversation;
setChatMessages(
conversation.messages.map((msg) => ({
id: msg.id,
role: msg.role,
content: msg.content,
sources: msg.sources ?? undefined,
})),
);
}
} catch {
conversationToasts.loadError();
}
};
loadConversation();
}, [activeConversationId]);
const createNewConversation = useCallback(async (): Promise<string | null> => {
try {
const response = await fetch('/api/conversations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
bot_type: 'documents',
document_id: selectedDocId,
}),
});
const data = await response.json();
if (data.success && data.data?.conversation) {
setConversationRefreshTrigger((prev) => prev + 1);
return data.data.conversation.id;
}
} catch {
conversationToasts.createError();
}
return null;
}, [selectedDocId]);
const saveMessageToConversation = async (conversationId: string, message: ChatMessage) => {
try {
await fetch(`/api/conversations/${conversationId}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
role: message.role,
content: message.content,
sources: message.sources,
}),
});
} catch {
// Failed to persist message - non-critical
}
};
const handleChat = async (e: FormEvent) => {
e.preventDefault();
if (!chatInput.trim() || chatLoading) return;
const message = chatInput.trim();
setChatInput('');
// Create new conversation if needed
let convId = activeConversationId;
if (!convId) {
convId = await createNewConversation();
if (convId) {
setActiveConversationId(convId);
}
}
const userMessage: ChatMessage = { role: 'user', content: message };
setChatMessages((prev) => [...prev, userMessage]);
setChatLoading(true);
// Save user message to conversation
if (convId) {
await saveMessageToConversation(convId, userMessage);
}
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message,
documentId: selectedDocId,
}),
});
const data = await response.json();
if (data.success) {
const assistantMessage: ChatMessage = {
role: 'assistant',
content: data.response,
sources: data.sources,
};
setChatMessages((prev) => [...prev, assistantMessage]);
// Save assistant message to conversation
if (convId) {
await saveMessageToConversation(convId, assistantMessage);
setConversationRefreshTrigger((prev) => prev + 1);
}
} else {
setChatMessages((prev) => [
...prev,
{ role: 'assistant', content: `Error: ${data.error}` },
]);
}
} catch {
setChatMessages((prev) => [
...prev,
{ role: 'assistant', content: 'Failed to get response. Please try again.' },
]);
} finally {
setChatLoading(false);
}
};
const handleSelectConversation = (id: string | null) => {
setActiveConversationId(id);
if (!id) {
setChatMessages([]);
}
};
const handleNewConversation = () => {
setActiveConversationId(null);
setChatMessages([]);
};
return {
chatMessages,
chatInput,
setChatInput,
chatLoading,
chatEndRef,
activeConversationId,
conversationRefreshTrigger,
handleChat,
handleSelectConversation,
handleNewConversation,
};
};