File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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" ) ,
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments