@@ -7,6 +7,13 @@ import { eq, asc } from "drizzle-orm";
77 import { streamAssistantResponse } from "@/src/lib/ollama/chat";
88 import { debug } from "@/src/lib/debug";
99
10+/**
11+ * Type guard to validate MaxPromptLength values.
12+ */
13+function isValidMaxPromptLength(value: unknown): value is MaxPromptLength {
14+ return value === null || value === "none" || value === 1024 || value === 4096;
15+}
16+
1017 export async function POST(request: Request) {
1118 const { message, threadId: threadIdRaw } = await request.json();
1219 const signal = request.signal;
@@ -34,8 +41,11 @@ export async function POST(request: Request) {
3441 // Use thread-specific settings (stored in thread table)
3542 const threadModel = thread[0].model;
3643 // Note: null from database means "none" (no limit), which OllamaChat handles correctly
37- const threadMaxPromptLength: MaxPromptLength =
38- thread[0].maxPromptLength === null ? null : (thread[0].maxPromptLength as MaxPromptLength);
44+ // Validate maxPromptLength before use to prevent runtime errors from invalid database values
45+ const rawMaxPromptLength = thread[0].maxPromptLength;
46+ const threadMaxPromptLength: MaxPromptLength = isValidMaxPromptLength(rawMaxPromptLength)
47+ ? rawMaxPromptLength
48+ : null;
3949
4050 // 2. Fetch previous messages from thread
4151 const previousMessages = await db