Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions app/(dashboard)/ai-chat/[id]/chat-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,38 @@ export default function ChatClient({ id, initialMessages }: ChatClientProps) {
const [selectedModel, setSelectedModel] = useState("claude-haiku-4.5");
const [input, setInput] = useState("");
const selectedModelRef = useRef(selectedModel);

const abortControllerRef = useRef<AbortController | null>(null);

// Keep ref in sync with state
useEffect(() => {
selectedModelRef.current = selectedModel;
}, [selectedModel]);

// Create a custom transport that reads model at request time
const transport = useRef(
new DefaultChatTransport({
api: "/api/chat",
body: () => ({
chatId: id,
model: selectedModelRef.current,
}),
})
).current;
const transportRef = useRef<DefaultChatTransport | null>(null);

// Initialize transport in useEffect for better React compatibility
useEffect(() => {
if (!transportRef.current) {
transportRef.current = new DefaultChatTransport({
api: "/api/chat",
body: () => ({
chatId: id,
model: selectedModelRef.current,
}),
});
}

// Cleanup: abort any ongoing requests and clear transport
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
transportRef.current = null;
};
}, [id]);

const transport = transportRef.current;

const { messages, sendMessage, status } = useChat({
id,
Expand Down
57 changes: 47 additions & 10 deletions app/(dashboard)/ai-chat/page.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,70 @@
"use client";

import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Spinner } from "@/components/ui/shadcn-io/spinner";

export default function NewChatPage() {
const router = useRouter();
const hasCreatedChat = useRef(false);
const isCreatingRef = useRef(false);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
// Prevent double creation in development mode (React Strict Mode)
if (hasCreatedChat.current) return;
hasCreatedChat.current = true;
// Prevent race conditions with a lock pattern
if (isCreatingRef.current) return;
isCreatingRef.current = true;

const abortController = new AbortController();

// Create a new chat and redirect to it
fetch("/api/chat/new", { method: "POST" })
fetch("/api/chat/new", {
method: "POST",
signal: abortController.signal
})
.then((r) => r.json())
.then(({ id }) => router.push(`/ai-chat/${id}`))
.then(({ id }) => {
if (!abortController.signal.aborted) {
router.push(`/ai-chat/${id}`);
}
})
.catch((error) => {
console.error("Error creating new chat:", error);
if (error.name !== "AbortError") {
console.error("Error creating new chat:", error);
setError("Failed to create chat. Please try again.");
isCreatingRef.current = false;
}
});

// Cleanup function to abort ongoing request
return () => {
abortController.abort();
};
}, [router]);

return (
<div className="flex flex-col min-h-screen bg-background">
<div className="flex items-center justify-center" style={{ height: "70vh" }}>
<div className="text-center space-y-4">
<Spinner variant="ring" size={48} className="mx-auto" />
<p className="text-muted-foreground">Creating new chat...</p>
{error ? (
<>
<p className="text-destructive text-lg font-medium">{error}</p>
<button
onClick={() => {
setError(null);
isCreatingRef.current = false;
router.refresh();
}}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
Try Again
</button>
</>
) : (
<>
<Spinner variant="ring" size={48} className="mx-auto" />
<p className="text-muted-foreground">Creating new chat...</p>
</>
)}
</div>
</div>
</div>
Expand Down