-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix: unconditional hook calls in ChatProfiles and FeedbackButtons #2912
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
EyalAmitay
wants to merge
3
commits into
Chainlit:main
Choose a base branch
from
EyalAmitay:fix/react-300-hooks-order
base: main
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.
+200
−17
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
f3a820d
fix: move hooks above early returns in ChatProfiles and FeedbackButtons
EyalAmitay 3d425bc
test(frontend): add regression tests for hooks-order fix in ChatProfi…
EyalAmitay 11161d6
test(frontend): fix hook-error regex to match React's exact invariant…
EyalAmitay 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
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
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,87 @@ | ||
| import { render } from '@testing-library/react'; | ||
| import { createContext } from 'react'; | ||
| import { RecoilRoot } from 'recoil'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import ChatProfiles from '@/components/header/ChatProfiles'; | ||
|
|
||
| let mockConfig: any = undefined; | ||
| const setChatProfileMock = vi.fn(); | ||
| const clearMock = vi.fn(); | ||
|
|
||
| vi.mock('@chainlit/react-client', () => ({ | ||
| useConfig: () => ({ config: mockConfig }), | ||
| useChatSession: () => ({ | ||
| chatProfile: undefined, | ||
| setChatProfile: setChatProfileMock | ||
| }), | ||
| useChatMessages: () => ({ firstInteraction: undefined }), | ||
| useChatInteract: () => ({ clear: clearMock }), | ||
| ChainlitContext: createContext({ buildEndpoint: (p: string) => p }) | ||
| })); | ||
|
|
||
| vi.mock('@/components/Markdown', () => ({ | ||
| Markdown: ({ children }: any) => <div>{children}</div> | ||
| })); | ||
|
|
||
| vi.mock('@/components/header/NewChat', () => ({ | ||
| NewChatDialog: () => null | ||
| })); | ||
|
|
||
| const wrapper = ({ children }: { children: React.ReactNode }) => ( | ||
| <RecoilRoot>{children}</RecoilRoot> | ||
| ); | ||
|
|
||
| describe('ChatProfiles', () => { | ||
| let consoleErrorSpy: ReturnType<typeof vi.spyOn>; | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| mockConfig = undefined; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| consoleErrorSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it('does not violate the Rules of Hooks when config is cleared between renders', () => { | ||
| // Reproduces the React invariant 300/310 caused by hooks placed below | ||
| // the early `return null`. `useConfig` clears `config` to undefined when | ||
| // the chat profile changes, so `config?.chatProfiles?.length` flips | ||
| // between truthy and falsy across consecutive renders. If any hooks live | ||
| // below the guard, the hook count differs between renders and React | ||
| // throws "Rendered fewer/more hooks than during the previous render". | ||
| const twoProfiles = { | ||
| chatProfiles: [ | ||
| { name: 'GPT-3.5', markdown_description: 'a', icon: '' }, | ||
| { name: 'GPT-4', markdown_description: 'b', icon: '' } | ||
| ], | ||
| features: {} | ||
| }; | ||
|
|
||
| // Render 1: config populated -> dropdown renders. | ||
| mockConfig = twoProfiles; | ||
| const { rerender } = render(<ChatProfiles />, { wrapper }); | ||
|
|
||
| // Render 2: config cleared (mirrors useConfig's setConfig(undefined) | ||
| // when chatProfile changes). The early-return path now activates. | ||
| mockConfig = undefined; | ||
| rerender(<ChatProfiles />); | ||
|
|
||
| // Render 3: config returns -> dropdown renders again. | ||
| mockConfig = twoProfiles; | ||
| rerender(<ChatProfiles />); | ||
|
|
||
| const hooksOrderError = consoleErrorSpy.mock.calls | ||
| .map((call) => String(call[0])) | ||
| .find( | ||
| (msg) => | ||
| /Rendered (fewer|more) hooks than during the previous render/.test( | ||
| msg | ||
| ) || /change in the order of Hooks/.test(msg) | ||
| ); | ||
|
|
||
| expect(hooksOrderError).toBeUndefined(); | ||
| }); | ||
| }); |
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,93 @@ | ||
| import { MessageContext } from '@/contexts/MessageContext'; | ||
| import { render } from '@testing-library/react'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { IStep } from '@chainlit/react-client'; | ||
|
|
||
| import { FeedbackButtons } from '@/components/chat/Messages/Message/Buttons/FeedbackButtons'; | ||
|
|
||
| import { IMessageContext } from '@/types/messageContext'; | ||
|
|
||
| vi.mock('recoil', async () => { | ||
| const actual = await vi.importActual<typeof import('recoil')>('recoil'); | ||
| return { | ||
| ...actual, | ||
| useRecoilValue: () => undefined | ||
| }; | ||
| }); | ||
|
|
||
| vi.mock('@chainlit/react-client', () => ({ | ||
| useChatSession: () => ({ idToResume: undefined }), | ||
| firstUserInteraction: { __mock: 'firstUserInteraction' } | ||
| })); | ||
|
|
||
| vi.mock('@/components/i18n/Translator', () => ({ | ||
| __esModule: true, | ||
| useTranslation: () => ({ t: (key: string) => key }), | ||
| default: ({ path }: { path: string }) => <span>{path}</span> | ||
| })); | ||
|
|
||
| const baseContext: IMessageContext = { | ||
| cot: 'hidden', | ||
| editable: false, | ||
| loading: false, | ||
| showFeedbackButtons: true, | ||
| uiName: '', | ||
| onError: () => undefined | ||
| }; | ||
|
|
||
| const message: IStep = { | ||
| id: 'step_1', | ||
| type: 'assistant_message', | ||
| name: 'Assistant', | ||
| output: 'hello', | ||
| createdAt: Date.now(), | ||
| streaming: false | ||
| }; | ||
|
|
||
| describe('FeedbackButtons', () => { | ||
| let consoleErrorSpy: ReturnType<typeof vi.spyOn>; | ||
|
|
||
| beforeEach(() => { | ||
| consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| consoleErrorSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it('does not violate the Rules of Hooks when showFeedbackButtons flips between renders', () => { | ||
| // Reproduces the React invariant 300/310 caused by hooks placed below | ||
| // the `if (!showFeedbackButtons) return null` guard. `showFeedbackButtons` | ||
| // is derived from `!!config?.dataPersistence`, so when `useConfig` clears | ||
| // `config` to undefined during a chat-profile switch, the guard flips. | ||
| // Hooks below the guard are then skipped and React detects a hook-count | ||
| // mismatch on the next render. | ||
| const tree = (ctx: IMessageContext) => ( | ||
| <MessageContext.Provider value={ctx}> | ||
| <FeedbackButtons message={message} /> | ||
| </MessageContext.Provider> | ||
| ); | ||
|
|
||
| // Render 1: showFeedbackButtons=true -> buttons render, all hooks invoked. | ||
| const { rerender } = render(tree(baseContext)); | ||
|
|
||
| // Render 2: showFeedbackButtons=false (mirrors config-clear flipping | ||
| // dataPersistence to undefined). Early-return path activates. | ||
| rerender(tree({ ...baseContext, showFeedbackButtons: false })); | ||
|
|
||
| // Render 3: showFeedbackButtons=true again -> buttons render again. | ||
| rerender(tree(baseContext)); | ||
|
|
||
| const hooksOrderError = consoleErrorSpy.mock.calls | ||
| .map((call) => String(call[0])) | ||
| .find( | ||
| (msg) => | ||
| /Rendered (fewer|more) hooks than during the previous render/.test( | ||
| msg | ||
| ) || /change in the order of Hooks/.test(msg) | ||
| ); | ||
|
|
||
| expect(hooksOrderError).toBeUndefined(); | ||
| }); | ||
| }); | ||
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.