-
Notifications
You must be signed in to change notification settings - Fork 18
fix: the new conversation title isn't displayed in the sidebar #1662
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
luxapientia
wants to merge
1
commit into
test
Choose a base branch
from
trongtruongpham192/myc-4598-chat-the-new-conversation-title-isnt-displayed-in-the
base: test
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import type { QueryObserverResult } from "@tanstack/react-query"; | ||
| import type { MutableRefObject } from "react"; | ||
| import { useCallback, useEffect, useRef } from "react"; | ||
| import type { Conversation } from "@/types/Chat"; | ||
|
|
||
| type RefetchConversations = () => Promise< | ||
| QueryObserverResult<Conversation[], Error> | ||
| >; | ||
|
|
||
| /** | ||
| * Refetches recent chats (and credits on successful completion) for a new thread. | ||
| * Eligible when there is no `[roomId]` param yet **or** `pendingNewThreadSidebarSyncRef` | ||
| * is true (set after `replaceState` to `/chat/:id`, when Next may still expose `roomId` | ||
| * in `useParams` and `!routeRoomId` would incorrectly disable sync). | ||
| * Keeps sync scoped to the active chat id and only latches after a successful refetch. | ||
| */ | ||
| export function useNewChatSidebarSync({ | ||
| chatId, | ||
| routeRoomId, | ||
| pendingNewThreadSidebarSyncRef, | ||
| refetchCredits, | ||
| refetchConversations, | ||
| }: { | ||
| chatId: string; | ||
| /** Dynamic `[roomId]` param when present; undefined on `/chat` new-thread flow */ | ||
| routeRoomId: string | undefined; | ||
| /** Set when the user starts a thread from `/chat` (or `?q=`); cleared after a successful sidebar refetch */ | ||
| pendingNewThreadSidebarSyncRef: MutableRefObject<boolean>; | ||
| refetchCredits: () => Promise<unknown>; | ||
| refetchConversations: RefetchConversations; | ||
| }) { | ||
| const hasSyncedRecentChatsAfterFirstAssistantRef = useRef(false); | ||
| const isRefreshingRecentChatsRef = useRef(false); | ||
| const inFlightRefreshPromiseRef = useRef<Promise<boolean> | null>(null); | ||
| const chatIdRef = useRef(chatId); | ||
| chatIdRef.current = chatId; | ||
|
|
||
| const isSidebarSyncEligible = useCallback(() => { | ||
| return ( | ||
| pendingNewThreadSidebarSyncRef.current || routeRoomId === undefined | ||
| ); | ||
| }, [pendingNewThreadSidebarSyncRef, routeRoomId]); | ||
|
|
||
| useEffect(() => { | ||
| hasSyncedRecentChatsAfterFirstAssistantRef.current = false; | ||
| isRefreshingRecentChatsRef.current = false; | ||
| inFlightRefreshPromiseRef.current = null; | ||
| }, [chatId]); | ||
|
|
||
| const refreshRecentChatsOnce = useCallback(async (): Promise<boolean> => { | ||
| if (hasSyncedRecentChatsAfterFirstAssistantRef.current) return false; | ||
|
|
||
| const existing = inFlightRefreshPromiseRef.current; | ||
| if (existing) { | ||
| return existing; | ||
| } | ||
|
|
||
| const startedForChatId = chatIdRef.current; | ||
|
|
||
| const promiseRef: { current: Promise<boolean> | null } = { current: null }; | ||
| promiseRef.current = (async (): Promise<boolean> => { | ||
| isRefreshingRecentChatsRef.current = true; | ||
| try { | ||
| const result = await refetchConversations(); | ||
| if (result.isSuccess && chatIdRef.current === startedForChatId) { | ||
| hasSyncedRecentChatsAfterFirstAssistantRef.current = true; | ||
| pendingNewThreadSidebarSyncRef.current = false; | ||
| return true; | ||
| } | ||
| return false; | ||
| } catch (error) { | ||
| console.error("Failed to refresh recent chats:", error); | ||
| return false; | ||
| } finally { | ||
| if (chatIdRef.current === startedForChatId) { | ||
| isRefreshingRecentChatsRef.current = false; | ||
| } | ||
| const leader = promiseRef.current; | ||
| if (leader && inFlightRefreshPromiseRef.current === leader) { | ||
| inFlightRefreshPromiseRef.current = null; | ||
| } | ||
| } | ||
| })(); | ||
|
|
||
| const p = promiseRef.current; | ||
| inFlightRefreshPromiseRef.current = p; | ||
| return p; | ||
| }, [refetchConversations]); | ||
|
|
||
| const onFinish = useCallback( | ||
| async ({ | ||
| isError, | ||
| isAbort, | ||
| }: { | ||
| isError: boolean; | ||
| isAbort: boolean; | ||
| }) => { | ||
| const shouldRefreshCredits = !isError && !isAbort; | ||
| const shouldRefreshRecentChats = | ||
| isSidebarSyncEligible() && | ||
| shouldRefreshCredits && | ||
| !hasSyncedRecentChatsAfterFirstAssistantRef.current; | ||
|
|
||
| await Promise.all([ | ||
| ...(shouldRefreshCredits ? [refetchCredits()] : []), | ||
| ...(shouldRefreshRecentChats | ||
| ? [ | ||
| (async () => { | ||
| let ok = await refreshRecentChatsOnce(); | ||
| if ( | ||
| !ok && | ||
| !hasSyncedRecentChatsAfterFirstAssistantRef.current | ||
| ) { | ||
| await refreshRecentChatsOnce(); | ||
| } | ||
| })(), | ||
| ] | ||
| : []), | ||
| ]); | ||
| }, | ||
| [isSidebarSyncEligible, refetchCredits, refreshRecentChatsOnce], | ||
| ); | ||
|
|
||
| const maybeRefreshOnFirstStream = useCallback( | ||
| (chatStatus: string) => { | ||
| if (!isSidebarSyncEligible()) return; | ||
| if (chatStatus !== "streaming") return; | ||
| if (hasSyncedRecentChatsAfterFirstAssistantRef.current) return; | ||
| void refreshRecentChatsOnce(); | ||
| }, | ||
| [isSidebarSyncEligible, refreshRecentChatsOnce], | ||
| ); | ||
|
|
||
| return { onFinish, maybeRefreshOnFirstStream }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ import { usePrivy } from "@privy-io/react-auth"; | |
| import { TextAttachment } from "@/types/textAttachment"; | ||
| import { formatTextAttachments } from "@/lib/chat/formatTextAttachments"; | ||
| import { useDeleteTrailingMessages } from "./useDeleteTrailingMessages"; | ||
| import { useNewChatSidebarSync } from "./useNewChatSidebarSync"; | ||
|
|
||
| // 30 days in seconds for Supabase signed URL expiry | ||
| const SIGNED_URL_EXPIRES_SECONDS = 60 * 60 * 24 * 30; | ||
|
|
@@ -48,11 +49,15 @@ export function useVercelChat({ | |
| const { selectedArtist } = useArtistProvider(); | ||
| const { selectedOrgId: organizationId } = useOrganization(); | ||
| const { roomId } = useParams(); | ||
| const routeRoomId = typeof roomId === "string" ? roomId : undefined; | ||
|
|
||
| const userId = userData?.account_id || userData?.id; // Use account_id if available, fallback to id | ||
| const artistId = selectedArtist?.account_id; | ||
| const messagesLengthRef = useRef<number>(); | ||
| const { addOptimisticConversation } = useConversationsProvider(); | ||
| /** True after starting a thread from `/chat` or `?q=` until sidebar list refetch succeeds */ | ||
| const pendingNewThreadSidebarSyncRef = useRef(false); | ||
| const { addOptimisticConversation, refetchConversations } = | ||
| useConversationsProvider(); | ||
| const { data: availableModels = [] } = useAvailableModels(); | ||
| const [input, setInput] = useState(""); | ||
| const [model, setModel] = useLocalStorage( | ||
|
|
@@ -178,6 +183,19 @@ export function useVercelChat({ | |
| [id, artistId, organizationId, accountIdOverride, model], | ||
| ); | ||
|
|
||
| useEffect(() => { | ||
| pendingNewThreadSidebarSyncRef.current = false; | ||
| }, [id]); | ||
|
|
||
| const { onFinish: onChatFinishSync, maybeRefreshOnFirstStream } = | ||
| useNewChatSidebarSync({ | ||
| chatId: id, | ||
| routeRoomId, | ||
| pendingNewThreadSidebarSyncRef, | ||
| refetchCredits, | ||
| refetchConversations, | ||
| }); | ||
|
|
||
| const { messages, status, stop, sendMessage, setMessages, regenerate } = | ||
| useChat({ | ||
| id, | ||
|
|
@@ -188,12 +206,13 @@ export function useVercelChat({ | |
| console.error("An error occurred, please try again!", e); | ||
| toast.error("An error occurred, please try again!"); | ||
| }, | ||
| onFinish: async () => { | ||
| // Update credits after AI response completes | ||
| await refetchCredits(); | ||
| }, | ||
| onFinish: onChatFinishSync, | ||
| }); | ||
|
|
||
| useEffect(() => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Custom agent: Code Structure and Size Limits for Readability and Single Responsibility
Prompt for AI agents |
||
| maybeRefreshOnFirstStream(status); | ||
| }, [status, maybeRefreshOnFirstStream]); | ||
|
|
||
| const earliestFailedUserMessageId = useMemo( | ||
| () => getEarliestFailedUserMessageId(messages), | ||
| [messages], | ||
|
|
@@ -307,6 +326,7 @@ export function useVercelChat({ | |
| handleSubmit(event); | ||
|
|
||
| if (!roomId) { | ||
| pendingNewThreadSidebarSyncRef.current = true; | ||
| // Optimistically append a temporary conversation so it appears in Recent Chats | ||
| // It will be replaced by the real conversation after the updates/refetch | ||
| addOptimisticConversation("New Chat", id, messageContent); | ||
|
|
@@ -316,6 +336,7 @@ export function useVercelChat({ | |
|
|
||
| const handleSendQueryMessages = useCallback( | ||
| async (initialMessage: UIMessage) => { | ||
| pendingNewThreadSidebarSyncRef.current = true; | ||
| silentlyUpdateUrl(); | ||
| const headers = await getHeaders(); | ||
| sendMessage(initialMessage, { body: chatRequestBody, headers }); | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.