Skip to content
Open
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
26 changes: 21 additions & 5 deletions app/(chat)/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@ import {
saveChat,
saveMessages,
updateChatLastContextById,
updateChatTitleById,
} from "@/lib/db/queries";
import type { DBMessage } from "@/lib/db/schema";
import { ChatSDKError } from "@/lib/errors";
import type { ChatMessage } from "@/lib/types";
import type { AppUsage } from "@/lib/usage";
import { convertToUIMessages, generateUUID } from "@/lib/utils";
import { convertToUIMessages, generateUUID, getTextFromMessage } from "@/lib/utils";
import { generateTitleFromUserMessage } from "../../actions";
import { type PostRequestBody, postRequestBodySchema } from "./schema";

Expand Down Expand Up @@ -135,16 +136,31 @@ export async function POST(request: Request) {
// Only fetch messages if chat already exists
messagesFromDb = await getMessagesByChatId({ id });
} else {
const title = await generateTitleFromUserMessage({
message,
});
// Generate temporary title immediately (non-blocking)
const messageText = getTextFromMessage(message);
const temporaryTitle = messageText.length > 60
? `${messageText.slice(0, 60).trim()}...`
: messageText || "New Chat";

await saveChat({
id,
userId: session.user.id,
title,
title: temporaryTitle,
visibility: selectedVisibilityType,
});

// Generate real title asynchronously in the background
// Don't await - let it run in parallel
generateTitleFromUserMessage({ message })
.then((realTitle) => {
updateChatTitleById({ chatId: id, title: realTitle }).catch((err) => {
console.warn("Failed to update chat title", id, err);
});
})
.catch((err) => {
console.warn("Failed to generate chat title", id, err);
});

// New chat - no need to fetch messages, it's empty
}

Expand Down
18 changes: 18 additions & 0 deletions lib/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,24 @@ export async function updateChatLastContextById({
}
}

export async function updateChatTitleById({
chatId,
title,
}: {
chatId: string;
title: string;
}) {
try {
return await db
.update(chat)
.set({ title })
.where(eq(chat.id, chatId));
} catch (error) {
console.warn("Failed to update title for chat", chatId, error);
return;
}
}

export async function getMessageCountByUserId({
id,
differenceInHours,
Expand Down