Skip to content

Commit aedcbe8

Browse files
committed
fix(chat): verify thread existence in backend to prevent fk violations and gracefully reset route state on client loading failures
1 parent 0417dde commit aedcbe8

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

apps/website/src/app/api/chat/route.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,27 @@ export async function POST(req: Request) {
3838
const question = lastUserMessage?.content || "";
3939

4040
let threadId = body.threadId;
41-
if (!threadId) {
41+
let threadExists = false;
42+
43+
if (threadId) {
44+
const [existingThread] = await db
45+
.select({ id: chatThreads.id })
46+
.from(chatThreads)
47+
.where(
48+
and(
49+
eq(chatThreads.id, threadId),
50+
eq(chatThreads.userId, user.id),
51+
eq(chatThreads.workspaceId, workspaceId),
52+
),
53+
)
54+
.limit(1);
55+
56+
if (existingThread) {
57+
threadExists = true;
58+
}
59+
}
60+
61+
if (!threadId || !threadExists) {
4262
threadId = newId("thr");
4363
await db.insert(chatThreads).values({
4464
id: threadId,
@@ -49,6 +69,7 @@ export async function POST(req: Request) {
4969
});
5070
}
5171

72+
5273
// Persist user message to DB
5374
await db.insert(chatMessages).values({
5475
id: newId("msg"),

apps/website/src/components/chat/chat-page.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,15 @@ export function ChatPage() {
125125
router.replace(`/dashboard/chat?threadId=${threadId}`);
126126
}
127127
}
128-
} catch {
129-
toast.error("Failed to load thread details.");
128+
} catch (err) {
129+
console.error("Failed to load thread:", err);
130+
toast.error("Conversation not found or failed to load.");
131+
setActiveThreadId(null);
132+
setMessages([]);
133+
router.replace("/dashboard/chat");
130134
}
135+
136+
131137
}, [router, setMessages, stop]);
132138

133139
// Sync thread when URL params change

0 commit comments

Comments
 (0)