chat-interface.test.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
  2. import { act, screen, waitFor, within } from "@testing-library/react";
  3. import userEvent from "@testing-library/user-event";
  4. import { renderWithProviders } from "test-utils";
  5. import { addUserMessage } from "#/state/chat-slice";
  6. import { SUGGESTIONS } from "#/utils/suggestions";
  7. import * as ChatSlice from "#/state/chat-slice";
  8. import { WsClientProviderStatus } from "#/context/ws-client-provider";
  9. import { ChatInterface } from "#/components/features/chat/chat-interface";
  10. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  11. const renderChatInterface = (messages: (Message)[]) =>
  12. renderWithProviders(<ChatInterface />);
  13. describe("Empty state", () => {
  14. const { send: sendMock } = vi.hoisted(() => ({
  15. send: vi.fn(),
  16. }));
  17. const { useWsClient: useWsClientMock } = vi.hoisted(() => ({
  18. useWsClient: vi.fn(() => ({
  19. send: sendMock,
  20. status: WsClientProviderStatus.ACTIVE,
  21. isLoadingMessages: false,
  22. })),
  23. }));
  24. beforeAll(() => {
  25. vi.mock("react-router", async (importActual) => ({
  26. ...(await importActual<typeof import("react-router")>()),
  27. useRouteLoaderData: vi.fn(() => ({})),
  28. }));
  29. vi.mock("#/context/socket", async (importActual) => ({
  30. ...(await importActual<typeof import("#/context/ws-client-provider")>()),
  31. useWsClient: useWsClientMock,
  32. }));
  33. });
  34. afterEach(() => {
  35. vi.clearAllMocks();
  36. });
  37. it("should render suggestions if empty", () => {
  38. const { store } = renderWithProviders(<ChatInterface />, {
  39. preloadedState: {
  40. chat: { messages: [] },
  41. },
  42. });
  43. expect(screen.getByTestId("suggestions")).toBeInTheDocument();
  44. act(() => {
  45. store.dispatch(
  46. addUserMessage({
  47. content: "Hello",
  48. imageUrls: [],
  49. timestamp: new Date().toISOString(),
  50. pending: true,
  51. }),
  52. );
  53. });
  54. expect(screen.queryByTestId("suggestions")).not.toBeInTheDocument();
  55. });
  56. it("should render the default suggestions", () => {
  57. renderWithProviders(<ChatInterface />, {
  58. preloadedState: {
  59. chat: { messages: [] },
  60. },
  61. });
  62. const suggestions = screen.getByTestId("suggestions");
  63. const repoSuggestions = Object.keys(SUGGESTIONS.repo);
  64. // check that there are at most 4 suggestions displayed
  65. const displayedSuggestions = within(suggestions).getAllByRole("button");
  66. expect(displayedSuggestions.length).toBeLessThanOrEqual(4);
  67. // Check that each displayed suggestion is one of the repo suggestions
  68. displayedSuggestions.forEach((suggestion) => {
  69. expect(repoSuggestions).toContain(suggestion.textContent);
  70. });
  71. });
  72. it.fails(
  73. "should load the a user message to the input when selecting",
  74. async () => {
  75. // this is to test that the message is in the UI before the socket is called
  76. useWsClientMock.mockImplementation(() => ({
  77. send: sendMock,
  78. status: WsClientProviderStatus.ACTIVE,
  79. isLoadingMessages: false,
  80. }));
  81. const addUserMessageSpy = vi.spyOn(ChatSlice, "addUserMessage");
  82. const user = userEvent.setup();
  83. const { store } = renderWithProviders(<ChatInterface />, {
  84. preloadedState: {
  85. chat: { messages: [] },
  86. },
  87. });
  88. const suggestions = screen.getByTestId("suggestions");
  89. const displayedSuggestions = within(suggestions).getAllByRole("button");
  90. const input = screen.getByTestId("chat-input");
  91. await user.click(displayedSuggestions[0]);
  92. // user message loaded to input
  93. expect(addUserMessageSpy).not.toHaveBeenCalled();
  94. expect(screen.queryByTestId("suggestions")).toBeInTheDocument();
  95. expect(store.getState().chat.messages).toHaveLength(0);
  96. expect(input).toHaveValue(displayedSuggestions[0].textContent);
  97. },
  98. );
  99. it.fails(
  100. "should send the message to the socket only if the runtime is active",
  101. async () => {
  102. useWsClientMock.mockImplementation(() => ({
  103. send: sendMock,
  104. status: WsClientProviderStatus.ACTIVE,
  105. isLoadingMessages: false,
  106. }));
  107. const user = userEvent.setup();
  108. const { rerender } = renderWithProviders(<ChatInterface />, {
  109. preloadedState: {
  110. chat: { messages: [] },
  111. },
  112. });
  113. const suggestions = screen.getByTestId("suggestions");
  114. const displayedSuggestions = within(suggestions).getAllByRole("button");
  115. await user.click(displayedSuggestions[0]);
  116. expect(sendMock).not.toHaveBeenCalled();
  117. useWsClientMock.mockImplementation(() => ({
  118. send: sendMock,
  119. status: WsClientProviderStatus.ACTIVE,
  120. isLoadingMessages: false,
  121. }));
  122. rerender(<ChatInterface />);
  123. await waitFor(() =>
  124. expect(sendMock).toHaveBeenCalledWith(expect.any(String)),
  125. );
  126. },
  127. );
  128. });
  129. describe.skip("ChatInterface", () => {
  130. beforeAll(() => {
  131. // mock useScrollToBottom hook
  132. vi.mock("#/hooks/useScrollToBottom", () => ({
  133. useScrollToBottom: vi.fn(() => ({
  134. scrollDomToBottom: vi.fn(),
  135. onChatBodyScroll: vi.fn(),
  136. hitBottom: vi.fn(),
  137. })),
  138. }));
  139. });
  140. afterEach(() => {
  141. vi.clearAllMocks();
  142. });
  143. it("should render messages", () => {
  144. const messages: Message[] = [
  145. {
  146. sender: "user",
  147. content: "Hello",
  148. imageUrls: [],
  149. timestamp: new Date().toISOString(),
  150. pending: true,
  151. },
  152. {
  153. sender: "assistant",
  154. content: "Hi",
  155. imageUrls: [],
  156. timestamp: new Date().toISOString(),
  157. pending: true,
  158. },
  159. ];
  160. renderChatInterface(messages);
  161. expect(screen.getAllByTestId(/-message/)).toHaveLength(2);
  162. });
  163. it("should render a chat input", () => {
  164. const messages: Message[] = [];
  165. renderChatInterface(messages);
  166. expect(screen.getByTestId("chat-input")).toBeInTheDocument();
  167. });
  168. it.todo("should call socket send when submitting a message", async () => {
  169. const user = userEvent.setup();
  170. const messages: Message[] = [];
  171. renderChatInterface(messages);
  172. const input = screen.getByTestId("chat-input");
  173. await user.type(input, "Hello");
  174. await user.keyboard("{Enter}");
  175. // spy on send and expect to have been called
  176. });
  177. it("should render an image carousel with a message", () => {
  178. let messages: Message[] = [
  179. {
  180. sender: "assistant",
  181. content: "Here are some images",
  182. imageUrls: [],
  183. timestamp: new Date().toISOString(),
  184. pending: true,
  185. },
  186. ];
  187. const { rerender } = renderChatInterface(messages);
  188. expect(screen.queryByTestId("image-carousel")).not.toBeInTheDocument();
  189. messages = [
  190. {
  191. sender: "assistant",
  192. content: "Here are some images",
  193. imageUrls: ["image1", "image2"],
  194. timestamp: new Date().toISOString(),
  195. pending: true,
  196. },
  197. ];
  198. rerender(<ChatInterface />);
  199. const imageCarousel = screen.getByTestId("image-carousel");
  200. expect(imageCarousel).toBeInTheDocument();
  201. expect(within(imageCarousel).getAllByTestId("image-preview")).toHaveLength(
  202. 2,
  203. );
  204. });
  205. it.todo("should render confirmation buttons");
  206. it("should render a 'continue' action when there are more than 2 messages and awaiting user input", () => {
  207. const messages: Message[] = [
  208. {
  209. sender: "assistant",
  210. content: "Hello",
  211. imageUrls: [],
  212. timestamp: new Date().toISOString(),
  213. pending: true,
  214. },
  215. {
  216. sender: "user",
  217. content: "Hi",
  218. imageUrls: [],
  219. timestamp: new Date().toISOString(),
  220. pending: true,
  221. },
  222. ];
  223. const { rerender } = renderChatInterface(messages);
  224. expect(
  225. screen.queryByTestId("continue-action-button"),
  226. ).not.toBeInTheDocument();
  227. messages.push({
  228. sender: "assistant",
  229. content: "How can I help you?",
  230. imageUrls: [],
  231. timestamp: new Date().toISOString(),
  232. pending: true,
  233. });
  234. rerender(<ChatInterface />);
  235. expect(screen.getByTestId("continue-action-button")).toBeInTheDocument();
  236. });
  237. it("should render inline errors", () => {
  238. const messages: (Message)[] = [
  239. {
  240. sender: "assistant",
  241. content: "Hello",
  242. imageUrls: [],
  243. timestamp: new Date().toISOString(),
  244. pending: true,
  245. },
  246. {
  247. type: "error",
  248. content: "Something went wrong",
  249. sender: "assistant",
  250. timestamp: new Date().toISOString(),
  251. },
  252. ];
  253. renderChatInterface(messages);
  254. const error = screen.getByTestId("error-message");
  255. expect(within(error).getByText("Something went wrong")).toBeInTheDocument();
  256. });
  257. it("should render both GitHub buttons initially when ghToken is available", () => {
  258. vi.mock("react-router", async (importActual) => ({
  259. ...(await importActual<typeof import("react-router")>()),
  260. useRouteLoaderData: vi.fn(() => ({ ghToken: "test-token" })),
  261. }));
  262. const messages: Message[] = [
  263. {
  264. sender: "assistant",
  265. content: "Hello",
  266. imageUrls: [],
  267. timestamp: new Date().toISOString(),
  268. pending: true,
  269. },
  270. ];
  271. renderChatInterface(messages);
  272. const pushButton = screen.getByRole("button", { name: "Push to Branch" });
  273. const prButton = screen.getByRole("button", { name: "Push & Create PR" });
  274. expect(pushButton).toBeInTheDocument();
  275. expect(prButton).toBeInTheDocument();
  276. expect(pushButton).toHaveTextContent("Push to Branch");
  277. expect(prButton).toHaveTextContent("Push & Create PR");
  278. });
  279. it("should render only 'Push changes to PR' button after PR is created", async () => {
  280. vi.mock("react-router", async (importActual) => ({
  281. ...(await importActual<typeof import("react-router")>()),
  282. useRouteLoaderData: vi.fn(() => ({ ghToken: "test-token" })),
  283. }));
  284. const messages: Message[] = [
  285. {
  286. sender: "assistant",
  287. content: "Hello",
  288. imageUrls: [],
  289. timestamp: new Date().toISOString(),
  290. pending: true,
  291. },
  292. ];
  293. const { rerender } = renderChatInterface(messages);
  294. const user = userEvent.setup();
  295. // Click the "Push & Create PR" button
  296. const prButton = screen.getByRole("button", { name: "Push & Create PR" });
  297. await user.click(prButton);
  298. // Re-render to trigger state update
  299. rerender(<ChatInterface />);
  300. // Verify only one button is shown
  301. const pushToPrButton = screen.getByRole("button", {
  302. name: "Push changes to PR",
  303. });
  304. expect(pushToPrButton).toBeInTheDocument();
  305. expect(
  306. screen.queryByRole("button", { name: "Push to Branch" }),
  307. ).not.toBeInTheDocument();
  308. expect(
  309. screen.queryByRole("button", { name: "Push & Create PR" }),
  310. ).not.toBeInTheDocument();
  311. });
  312. it("should render feedback actions if there are more than 3 messages", () => {
  313. const messages: Message[] = [
  314. {
  315. sender: "assistant",
  316. content: "Hello",
  317. imageUrls: [],
  318. timestamp: new Date().toISOString(),
  319. pending: true,
  320. },
  321. {
  322. sender: "user",
  323. content: "Hi",
  324. imageUrls: [],
  325. timestamp: new Date().toISOString(),
  326. pending: true,
  327. },
  328. {
  329. sender: "assistant",
  330. content: "How can I help you?",
  331. imageUrls: [],
  332. timestamp: new Date().toISOString(),
  333. pending: true,
  334. },
  335. ];
  336. const { rerender } = renderChatInterface(messages);
  337. expect(screen.queryByTestId("feedback-actions")).not.toBeInTheDocument();
  338. messages.push({
  339. sender: "user",
  340. content: "I need help",
  341. imageUrls: [],
  342. timestamp: new Date().toISOString(),
  343. pending: true,
  344. });
  345. rerender(<ChatInterface />);
  346. expect(screen.getByTestId("feedback-actions")).toBeInTheDocument();
  347. });
  348. describe("feedback", () => {
  349. it.todo("should open the feedback modal when a feedback action is clicked");
  350. it.todo(
  351. "should submit feedback and hide the actions when feedback is shared",
  352. );
  353. it.todo("should render the actions once more after new messages are added");
  354. });
  355. });