Files
CatoandClaude Opus 5 376b94f89d refactor: one rate limiter, one auth shell, one create flow, one icon frame (#198)
* refactor(rate-limit): one limiter from limitkit, keyed on the proxy's hop

Two hand-rolled limiters lived side by side — lib/rate-limit.ts and
lib/middleware/rate-limit.ts — each with its own window maths, its own
header names and its own idea of who the caller is. Both are gone; the
decision now comes from limitkit (fleet/SHARED.md), and what stays here
is the one table of app budgets in lib/rate-limit.ts. A route names a
bucket; it does not get to invent a number.

The reason this matters beyond tidiness: both copies keyed the limit on
the FIRST hop of X-Forwarded-For. That hop is written by the client, so
any caller could mint a fresh budget per request by adding a header —
the limiter looked like it worked and enforced nothing. limitkit counts
from the right, i.e. the hop our own proxy wrote. A test now pins it:
a forged first hop must not mint a fresh bucket.

Also removed the Supabase check_rate_limit RPC path, which failed OPEN
on every error — the limiter switched itself off whenever the database
hiccupped. And 429s now carry Retry-After and X-RateLimit-* headers plus
a retryAfter field, which is what the auth forms count down.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(icons): each icon body written once

Icons.tsx repeated the same 24-box outline SVG wrapper for every icon —
a 121-line self-clone. One `Outline` frame and one `icon(paths, ...)`
builder replace it; an icon is now its path data and nothing else.

Every export and every path string is byte-identical to before, so the
rendered output does not move.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(create): one QuickCreateFlow behind /create and /personal

The two pages held the same three-step flow twice — 192 cloned lines of
state machine, header, progress indicator and step switch. They differ
only in the copy around the template picker, so that is what the pages
now pass in: /personal supplies its title block and its link out to the
professionals, /create supplies neither.

Both renders are unchanged, including that /personal's intro and outro
only appear on the picker step.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* refactor(auth): one shell, one field, one submit button for the auth screens

signup, signin, forgot-password and verify-email each carried their own
copy of the page frame, the error line, the labelled input and the
submit button — six clone pairs with signup in every one. They now share
AuthShell / AuthAlert / AuthField / AuthSubmitButton, and the per-form
error-plus-countdown state lives once in useAuthError.

One real fix falls out of it: isRateLimitError compared the error code
against 'RATE_LIMITED', but the API has always sent 'RATE_LIMIT'. The
rate-limit countdown therefore never showed. It does now.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

* chore(lint): console.info is not logging, and every disable says why

`no-console` allowed `info`, so debug lines shipped as operator output:
the blog route narrated every render to the server log at info level.
Those lines now go through lib/logger (the single logger) at the level
they actually are, and the allowance is gone — warn and error only. The
21 remaining console.log calls are all in scripts/test-db-connection.ts,
where printing to the terminal is the point.

The eslint-disable count drops 16 -> 13. Comments.tsx no longer needs one
(useSyncExternalStore is the supported way to ask "are we on the client"),
and lib/supabase.ts no longer needs its `any` — the SSG mock casts once at
the return instead. The 13 that remain each name their reason: external
avatar URLs that next/image would need a host allowlist for, and effects
that seed state from an external store.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 01:24:12 -07:00

151 lines
4.9 KiB
TypeScript

/**
* RAG Chat API
*
* POST /api/chat - Chat with documents using RAG
*
* Flow:
* 1. Search for relevant document chunks
* 2. Build context from retrieved chunks
* 3. Generate response using user's preferred LLM
*/
import { type NextRequest } from 'next/server';
import { generateLLMResponse } from '@/lib/llm-client';
import { logger } from '@/lib/logger';
import { getServiceClient } from '@/lib/supabase';
import { verifyUser } from '@/lib/api-utils';
import { jsonSuccess, jsonError, jsonUnauthorized, HTTP_STATUS } from '@/lib/api';
import { SYSTEM_PROMPTS } from '@/lib/constants';
import { enforceRateLimit } from '@/lib/rate-limit';
import {
generateEmbeddingWithTimeout,
getUserLLMSettings,
handleLLMError,
searchUserDocuments,
} from '@/lib/chat';
// Extend function timeout for model loading (Next.js route segment config)
export const maxDuration = 30;
/**
* Chat with documents using RAG
*/
export async function POST(request: NextRequest) {
const startTime = Date.now();
logger.log('[Chat API] Starting request');
try {
// Rate limit per user/IP
const limited = enforceRateLimit(request, 'chat');
if (limited) return limited;
logger.log('[Chat API] Verifying user...');
const user = await verifyUser(request);
if (!user) {
logger.log('[Chat API] User verification failed');
return jsonUnauthorized();
}
logger.log(`[Chat API] User verified: ${user.id} Time: ${Date.now() - startTime} ms`);
const body = await request.json();
const { message, documentId, contextSize = 3 } = body;
logger.log(`[Chat API] Request body parsed, message length: ${message?.length}`);
if (!message || typeof message !== 'string') {
return jsonError('Message required', 'VALIDATION_ERROR', HTTP_STATUS.BAD_REQUEST);
}
const supabase = getServiceClient();
// Get user settings for LLM provider
const { provider, apiKey, ollamaUrl } = await getUserLLMSettings(user.id);
// Check if user has any processed documents
const { count: docCount } = await supabase
.from('documents')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
.eq('status', 'ready');
if (!docCount || docCount === 0) {
logger.log('[Chat API] No documents found for user');
return jsonSuccess({
response:
"You don't have any processed documents yet. Please upload and process some documents first, then I can answer questions about them.",
sources: [],
provider,
});
}
logger.log(`[Chat API] Found ${docCount} documents. Time: ${Date.now() - startTime} ms`);
// Generate embedding for the query with timeout
logger.log('[Chat API] Generating query embedding...');
const embeddingResult = await generateEmbeddingWithTimeout(message);
if ('error' in embeddingResult) {
return embeddingResult.error;
}
// Search for relevant document chunks
logger.log('[Chat API] Searching for relevant chunks...');
const searchStartTime = Date.now();
const {
context,
sources,
chunks: relevantChunks,
} = await searchUserDocuments(supabase, embeddingResult.embedding, user.id, {
documentId,
matchCount: contextSize,
});
logger.log(
`[Chat API] Search completed in ${Date.now() - searchStartTime} ms, found ${relevantChunks.length} chunks`,
);
// Try to generate response using LLM
logger.log(`[Chat API] Calling LLM, provider: ${provider}`);
const llmStartTime = Date.now();
try {
const llmResponse = await generateLLMResponse(
[
{ role: 'system', content: SYSTEM_PROMPTS.RAG_ASSISTANT },
{
role: 'user',
content: `Context from documents:\n\n${context}\n\n---\n\nUser question: ${message}`,
},
],
{
provider,
apiKey,
ollamaUrl,
temperature: 0.7,
maxTokens: 1024,
},
);
logger.log(`[Chat API] LLM response received in ${Date.now() - llmStartTime} ms`);
logger.log(`[Chat API] Total request time: ${Date.now() - startTime} ms`);
return jsonSuccess({
response: llmResponse.content,
sources,
provider: llmResponse.provider,
model: llmResponse.model,
});
} catch (llmError) {
logger.error(`[Chat API] LLM call failed after ${Date.now() - llmStartTime} ms`);
// Build fallback sources for API key errors
const fallbackSources = sources.map((s, i) => ({
label: `**[Source ${i + 1}: ${s.document_name}]**`,
content: s.preview,
}));
const errorResponse = handleLLMError(llmError, fallbackSources);
if (errorResponse) return errorResponse;
throw llmError;
}
} catch (error) {
logger.error('[Chat API] Unhandled error:', error);
return jsonError('Internal server error', 'INTERNAL_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
}