chat-interface.test.tsx 12 KB

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