File size: 35,523 Bytes
fd2c364 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 | import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";
import {
fireEvent,
render,
screen,
waitFor,
within,
} from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderWithProviders, useParamsMock } from "test-utils";
import { SUGGESTIONS } from "#/utils/suggestions";
import { ChatInterface } from "#/components/features/chat/chat-interface";
import {
useConversationId,
useOptionalConversationId,
} from "#/hooks/use-conversation-id";
import { useErrorMessageStore } from "#/stores/error-message-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { useConfig } from "#/hooks/query/use-config";
import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files";
import {
SecurityRisk,
type ActionEvent,
type MessageEvent,
} from "#/types/agent-server/core";
import { useEventStore } from "#/stores/use-event-store";
import { useAgentState } from "#/hooks/use-agent-state";
import { useLoadOlderEvents } from "#/hooks/use-load-older-events";
import { useTaskPolling } from "#/hooks/query/use-task-polling";
import { AgentState } from "#/types/agent-state";
import { useConversationStore } from "#/stores/conversation-store";
import { useGoalStore } from "#/stores/goal-store";
import { act } from "@testing-library/react";
const mockSend = vi.fn();
vi.mock("#/hooks/use-send-message", () => ({
useSendMessage: () => ({ send: mockSend }),
}));
vi.mock("#/hooks/query/use-config");
vi.mock("#/hooks/mutation/use-unified-upload-files");
// Treat the LLM as configured by default so the "not configured" gate/banner
// stays inert for these tests (its own behavior is covered elsewhere).
vi.mock("#/hooks/use-llm-configured", () => ({
useLlmConfigured: () => ({ isConfigured: true, isLoading: false }),
}));
vi.mock("#/hooks/use-conversation-id", () => ({
useConversationId: vi.fn(),
useOptionalConversationId: vi.fn(),
}));
vi.mock("#/hooks/use-user-providers", () => ({
useUserProviders: () => ({
providers: [],
}),
}));
vi.mock("#/hooks/use-conversation-name-context-menu", () => ({
useConversationNameContextMenu: () => ({
isOpen: false,
contextMenuRef: { current: null },
handleContextMenu: vi.fn(),
handleClose: vi.fn(),
handleRename: vi.fn(),
handleDelete: vi.fn(),
}),
}));
vi.mock("#/hooks/use-load-older-events", () => ({
useLoadOlderEvents: vi.fn(),
}));
vi.mock("#/hooks/query/use-task-polling", () => ({
useTaskPolling: vi.fn(),
}));
vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: vi.fn(() => ({
curAgentState: AgentState.AWAITING_USER_INPUT,
})),
usePlanningAgentState: vi.fn(() => ({
localPlanningConversationId: null,
curPlanningAgentState: AgentState.AWAITING_USER_INPUT,
isPlanningAgentRunning: false,
})),
}));
const trackInitialQuerySubmittedMock = vi.fn();
const trackUserMessageSentMock = vi.fn();
vi.mock("#/hooks/use-tracking", () => ({
useTracking: () => ({
trackInitialQuerySubmitted: trackInitialQuerySubmittedMock,
trackUserMessageSent: trackUserMessageSentMock,
}),
}));
// Helper function to render with Router context
const renderChatInterfaceWithRouter = () =>
renderWithProviders(
<MemoryRouter>
<ChatInterface />
</MemoryRouter>,
);
// Helper function to render with QueryClientProvider and Router (for newer tests)
const renderWithQueryClient = (
ui: React.ReactElement,
queryClient: QueryClient,
route = "/test-conversation-id",
) =>
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[route]}>
<Routes>
<Route path="/:conversationId" element={ui} />
<Route path="/" element={ui} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
beforeEach(() => {
useParamsMock.mockReturnValue({ conversationId: "test-conversation-id" });
vi.mocked(useConversationId).mockReturnValue({
conversationId: "test-conversation-id",
});
vi.mocked(useOptionalConversationId).mockReturnValue({
conversationId: "test-conversation-id",
});
vi.mocked(useTaskPolling).mockReturnValue({
isTask: false,
taskId: null,
conversationId: "test-conversation-id",
task: undefined,
taskStatus: undefined,
taskDetail: undefined,
taskError: null,
isLoadingTask: false,
repositoryInfo: {
selectedRepository: undefined,
selectedBranch: undefined,
gitProvider: undefined,
},
});
// Default: pagination disabled (hasMore=false) so unrelated tests don't
// accidentally trigger loadOlder via the on-mount auto-trigger effect.
// Tests that exercise pagination override this.
vi.mocked(useLoadOlderEvents).mockReturnValue({
isLoading: false,
hasMore: false,
loadOlder: vi.fn().mockResolvedValue(undefined),
});
});
describe("ChatInterface - Chat Suggestions", () => {
// Create a new QueryClient for each test
let queryClient: QueryClient;
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
vi.mocked(useTaskPolling).mockReturnValue({
isTask: false,
taskId: null,
conversationId: "test-conversation-id",
task: undefined,
taskStatus: undefined,
taskDetail: undefined,
taskError: null,
isLoadingTask: false,
repositoryInfo: {
selectedRepository: undefined,
selectedBranch: undefined,
gitProvider: undefined,
},
});
useOptimisticUserMessageStore.setState({
pendingMessages: [],
});
useErrorMessageStore.setState({
errorMessage: null,
});
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi
.fn()
.mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
isLoading: false,
});
});
test("should hide chat suggestions when there is a user message", () => {
const mockUserEvent: MessageEvent = {
id: "msg-1",
timestamp: "2025-07-01T00:00:00Z",
source: "user",
llm_message: {
role: "user",
content: [{ type: "text", text: "Hello" }],
},
activated_skills: [],
extended_content: [],
};
useEventStore.setState({
events: [mockUserEvent],
eventIds: new Set(["msg-1"]),
uiEvents: [mockUserEvent],
});
renderWithQueryClient(<ChatInterface />, queryClient);
// Check if ChatSuggestions is not rendered with user events
expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
});
test("should hide chat suggestions when there is an optimistic user message", () => {
useOptimisticUserMessageStore.getState().enqueuePendingMessage({
conversationId: "test-conversation-id",
text: "Optimistic message",
});
renderWithQueryClient(<ChatInterface />, queryClient);
// Check if ChatSuggestions is not rendered with optimistic user message
expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
});
test("should hide chat suggestions while a cloud start task is provisioning", () => {
vi.mocked(useTaskPolling).mockReturnValue({
isTask: true,
taskId: "abc",
conversationId: null,
task: undefined,
taskStatus: "WORKING",
taskDetail: undefined,
taskError: null,
isLoadingTask: false,
repositoryInfo: {
selectedRepository: undefined,
selectedBranch: undefined,
gitProvider: undefined,
},
});
renderWithQueryClient(<ChatInterface />, queryClient, "/task-abc");
expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
});
test("should hide chat suggestions on a task route even when the task is READY", () => {
vi.mocked(useTaskPolling).mockReturnValue({
isTask: true,
taskId: "abc",
conversationId: null,
task: undefined,
taskStatus: "READY",
taskDetail: undefined,
taskError: null,
isLoadingTask: false,
repositoryInfo: {
selectedRepository: undefined,
selectedBranch: undefined,
gitProvider: undefined,
},
});
renderWithQueryClient(<ChatInterface />, queryClient, "/task-abc");
expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
});
});
describe("ChatInterface - Empty state", () => {
it.todo("should render suggestions if empty");
it("should render the default suggestions", () => {
renderChatInterfaceWithRouter();
const suggestions = screen.getByTestId("chat-suggestions");
const repoSuggestions = Object.keys(SUGGESTIONS.repo);
// check that there are at most 4 suggestions displayed
const displayedSuggestions = within(suggestions).getAllByRole("button");
expect(displayedSuggestions.length).toBeLessThanOrEqual(4);
// Check that each displayed suggestion is one of the repo suggestions
displayedSuggestions.forEach((suggestion) => {
expect(repoSuggestions).toContain(suggestion.textContent);
});
});
});
describe("ChatInterface - Scroll-up loads older events", () => {
let queryClient: QueryClient;
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useErrorMessageStore.setState({ errorMessage: null });
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi.fn(),
isLoading: false,
});
});
afterEach(() => {
useEventStore.setState({
events: [],
eventIds: new Set(),
uiEvents: [],
});
vi.clearAllMocks();
});
// Helper: install a controllable mock of useLoadOlderEvents and seed the
// store with one renderable user message so the chat mounts a scroll area.
const setupPaginationTest = () => {
const loadOlder = vi.fn().mockResolvedValue(undefined);
vi.mocked(useLoadOlderEvents).mockReturnValue({
isLoading: false,
hasMore: true,
loadOlder,
});
const seedEvent: MessageEvent = {
id: "msg-seed",
timestamp: "2025-07-01T00:00:00Z",
source: "user",
llm_message: {
role: "user",
content: [{ type: "text", text: "Existing message" }],
},
activated_skills: [],
extended_content: [],
};
useEventStore.setState({
events: [seedEvent],
eventIds: new Set(["msg-seed"]),
uiEvents: [seedEvent],
});
return loadOlder;
};
// The auto-scroll-to-bottom hook schedules a rAF that does
// `dom.scrollTop = dom.scrollHeight`, which clobbers any value we set
// here before the test's event fires. Pin `scrollTop` as a stable
// getter so those assignments are no-ops.
const setScrollMetrics = (
el: HTMLElement,
metrics: { scrollTop: number; scrollHeight: number; clientHeight: number },
) => {
Object.defineProperty(el, "scrollTop", {
configurable: true,
get: () => metrics.scrollTop,
set: () => {
/* swallow assignments from auto-scroll-to-bottom */
},
});
Object.defineProperty(el, "scrollHeight", {
configurable: true,
writable: true,
value: metrics.scrollHeight,
});
Object.defineProperty(el, "clientHeight", {
configurable: true,
writable: true,
value: metrics.clientHeight,
});
};
it("calls loadOlder when the user scrolls near the top", async () => {
const loadOlder = setupPaginationTest();
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
// Pretend the user just scrolled near the top of an overflowing list.
setScrollMetrics(scrollContainer!, {
scrollTop: 0,
scrollHeight: 5000,
clientHeight: 800,
});
// Drop any on-mount auto-trigger so we exclusively assert the scroll path.
await new Promise((r) => {
setTimeout(r, 0);
});
loadOlder.mockClear();
fireEvent.scroll(scrollContainer!);
await new Promise((r) => {
setTimeout(r, 0);
});
expect(loadOlder).toHaveBeenCalledTimes(1);
});
it("auto-loads older events when the chat content does not overflow the viewport", async () => {
// No overflow ⇒ no scrollbar ⇒ user can't trigger loadOlder by
// scrolling. The component must auto-trigger via useEffect.
const loadOlder = setupPaginationTest();
renderWithQueryClient(<ChatInterface />, queryClient);
// Allow the on-mount auto-trigger useEffect to fire.
await new Promise((r) => {
setTimeout(r, 0);
});
expect(loadOlder).toHaveBeenCalled();
});
it("loads older events when the user wheels up while pinned at scrollTop=0", async () => {
// Overscroll-at-top: scrollTop is already 0 so the browser does not
// dispatch a scroll event. Wheel handler must catch this.
const loadOlder = setupPaginationTest();
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
// Plenty of scrollable content overhead so the no-overflow branch
// doesn't claim the call — we want to exercise the wheel path.
setScrollMetrics(scrollContainer!, {
scrollTop: 0,
scrollHeight: 10000,
clientHeight: 800,
});
// Let any on-mount auto-trigger settle.
await new Promise((r) => {
setTimeout(r, 0);
});
loadOlder.mockClear();
// User is pinned at the top and wheels upward — no scroll event
// would fire here in a real browser.
fireEvent.wheel(scrollContainer!, { deltaY: -100 });
await new Promise((r) => {
setTimeout(r, 0);
});
expect(loadOlder).toHaveBeenCalledTimes(1);
});
it("shows an error banner if loading older events fails", async () => {
// This test exercises the real useLoadOlderEvents (so a rejected
// searchEvents propagates through to the chat's error banner).
// Override the global mock with the actual implementation.
const actualLoadOlderModule = await vi.importActual<
typeof import("#/hooks/use-load-older-events")
>("#/hooks/use-load-older-events");
vi.mocked(useLoadOlderEvents).mockImplementation(
actualLoadOlderModule.useLoadOlderEvents,
);
const seedEvent: MessageEvent = {
id: "msg-seed",
timestamp: "2025-07-01T00:00:00Z",
source: "user",
llm_message: {
role: "user",
content: [{ type: "text", text: "Existing message" }],
},
activated_skills: [],
extended_content: [],
};
useEventStore.setState({
events: [seedEvent],
eventIds: new Set(["msg-seed"]),
uiEvents: [seedEvent],
});
const useUserConversationModule =
await import("#/hooks/query/use-user-conversation");
vi.spyOn(useUserConversationModule, "useUserConversation").mockReturnValue({
data: {
conversation_id: "test-conversation-id",
conversation_url: "https://example.com",
session_api_key: "k",
conversation_version: "V1",
},
isLoading: false,
isPending: false,
isError: false,
error: null,
refetch: vi.fn(),
} as unknown as ReturnType<
typeof useUserConversationModule.useUserConversation
>);
const eventServiceModule =
await import("#/api/event-service/event-service.api");
vi.spyOn(eventServiceModule.default, "searchEvents").mockRejectedValue(
new Error("Older events request failed"),
);
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
Object.defineProperty(scrollContainer!, "scrollTop", {
configurable: true,
writable: true,
value: 0,
});
Object.defineProperty(scrollContainer!, "scrollHeight", {
configurable: true,
writable: true,
value: 5000,
});
scrollContainer!.dispatchEvent(new Event("scroll", { bubbles: true }));
expect(
await screen.findByText("Older events request failed"),
).toBeInTheDocument();
});
it("renders renderable agent events even when the loaded window has no user message (so the user has something to scroll up from)", () => {
// Simulate the lazy-loaded "50 most recent" window landing in the
// store with only agent / environment events — the original user
// prompt is older than this window.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const agentAction: any = {
id: "act-1",
timestamp: "2025-07-01T00:00:10Z",
source: "agent",
kind: "ActionEvent",
action: {
kind: "ExecuteBashAction",
command: "ls",
},
tool_name: "terminal",
tool_call_id: "call-1",
tool_call: {
id: "call-1",
name: "terminal",
arguments: { command: "ls" },
},
llm_response_id: "resp-1",
thought: [],
reasoning_content: "",
thinking_blocks: [],
};
useEventStore.setState({
events: [agentAction],
eventIds: new Set(["act-1"]),
uiEvents: [agentAction],
});
renderWithQueryClient(<ChatInterface />, queryClient);
// The scroll container exists (so the user can scroll up to load older).
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
// ChatSuggestions should NOT take over the chat area when agent
// actions are present in the loaded window.
expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
// The Messages list should be rendered (the bug was that it was
// gated on `conversationUserEventsExist` and stayed hidden here,
// leaving a blank chat with nothing to scroll).
expect(scrollContainer!.children.length).toBeGreaterThan(0);
});
});
describe("ChatInterface - Pending message queue", () => {
let queryClient: QueryClient;
beforeEach(() => {
mockSend.mockReset();
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useErrorMessageStore.setState({ errorMessage: null });
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi
.fn()
.mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
isLoading: false,
});
useEventStore.setState({
events: [],
eventIds: new Set(),
uiEvents: [],
});
});
afterEach(() => {
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
});
function submitMessage(text: string) {
// The chat input is a contenteditable div; the conversation store exposes
// `submittedMessage` which CustomChatInput watches and forwards to the
// ChatInterface's `onSubmit` handler. Driving that store directly is the
// most reliable way to simulate "the user pressed send" in jsdom.
act(() => {
useConversationStore.setState({ submittedMessage: text });
});
}
function renderInterface() {
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/test-conversation-id"]}>
<Routes>
<Route path=":conversationId" element={<ChatInterface />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
it("shows the message in 'sending' state immediately when submitted", async () => {
let resolveSend: ((value: unknown) => void) | undefined;
mockSend.mockImplementation(
() =>
new Promise((resolve) => {
resolveSend = resolve;
}),
);
renderInterface();
submitMessage("hello world");
const pendingMessage = await screen.findByTestId("user-message");
expect(pendingMessage).toHaveTextContent("hello world");
expect(pendingMessage).toHaveAttribute("data-pending-status", "sending");
expect(screen.getByTestId("chat-message-sending")).toBeInTheDocument();
expect(screen.queryByTestId("chat-message-retry")).not.toBeInTheDocument();
resolveSend?.({ queued: false });
});
it("flips the message to 'error' with a retry link when send rejects", async () => {
mockSend.mockRejectedValue(new Error("network down"));
renderInterface();
submitMessage("hello");
await waitFor(() => {
expect(screen.getByTestId("user-message")).toHaveAttribute(
"data-pending-status",
"error",
);
});
expect(screen.getByTestId("chat-message-error")).toBeInTheDocument();
expect(screen.getByTestId("chat-message-retry")).toBeInTheDocument();
});
it("queues multiple submitted messages, each with its own pending entry", async () => {
mockSend.mockResolvedValue({ queued: false });
renderInterface();
submitMessage("first");
submitMessage("second");
await waitFor(() => {
expect(screen.getAllByTestId("user-message")).toHaveLength(2);
});
const messages = screen.getAllByTestId("user-message");
expect(messages[0]).toHaveTextContent("first");
expect(messages[1]).toHaveTextContent("second");
});
});
describe("ChatInterface - Auto-scroll on submit (issue #817)", () => {
let queryClient: QueryClient;
beforeEach(() => {
mockSend.mockReset();
mockSend.mockResolvedValue({ queued: false });
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useErrorMessageStore.setState({ errorMessage: null });
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi
.fn()
.mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
isLoading: false,
});
useEventStore.setState({
events: [],
eventIds: new Set(),
uiEvents: [],
});
});
afterEach(() => {
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
});
it("scrolls to bottom when a new prompt is submitted while the user is scrolled up", async () => {
// Arrange: render and grab the chat scroll container.
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/test-conversation-id"]}>
<Routes>
<Route path=":conversationId" element={<ChatInterface />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
// Let the mount-time auto-scroll rAF (which re-arms autoScroll=true)
// run and settle BEFORE the scroll-up sim. Otherwise that rAF would
// fire later and undo the autoScroll=false precondition for the bug.
await new Promise((r) => {
setTimeout(r, 0);
});
// Capture every scrollTop write so we can detect the rAF inside
// scrollDomToBottom landing `dom.scrollTop = dom.scrollHeight`.
const scrollWrites: number[] = [];
let scrollTopRead = 200;
Object.defineProperty(scrollContainer!, "scrollTop", {
configurable: true,
get: () => scrollTopRead,
set: (value: number) => {
scrollWrites.push(value);
},
});
Object.defineProperty(scrollContainer!, "scrollHeight", {
configurable: true,
writable: true,
value: 10000,
});
Object.defineProperty(scrollContainer!, "clientHeight", {
configurable: true,
writable: true,
value: 800,
});
// Simulate the user scrolling up: first event seeds prev=200, the
// second event at scrollTop=50 is detected as scrolling up and flips
// the hook's `autoScroll` to false (the precondition for the bug).
fireEvent.scroll(scrollContainer!);
scrollTopRead = 50;
fireEvent.scroll(scrollContainer!);
scrollWrites.length = 0;
// Act: submit a new prompt (same path InteractiveChatBox uses).
act(() => {
useConversationStore.setState({ submittedMessage: "hello" });
});
// Assert: scrollDomToBottom landed scrollHeight onto scrollTop even
// though autoScroll was off. Without the fix the auto-scroll effect
// would skip the call and `scrollWrites` would stay empty.
await waitFor(() => {
expect(scrollWrites).toContain(10000);
});
});
it("follows the live goal banner into view when an active goal advances", async () => {
vi.mocked(useOptionalConversationId).mockReturnValue({
conversationId: "test-conversation-id",
});
useGoalStore.setState({ statusByConversation: {} });
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/test-conversation-id"]}>
<Routes>
<Route path=":conversationId" element={<ChatInterface />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
const scrollContainer = document.querySelector(
"[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
// Let the mount-time auto-scroll settle; the user stays pinned to the
// bottom (autoScroll=true) since we never simulate a scroll-up.
await new Promise((r) => {
setTimeout(r, 0);
});
const scrollWrites: number[] = [];
Object.defineProperty(scrollContainer!, "scrollTop", {
configurable: true,
get: () => 9200,
set: (value: number) => {
scrollWrites.push(value);
},
});
Object.defineProperty(scrollContainer!, "scrollHeight", {
configurable: true,
writable: true,
value: 10000,
});
Object.defineProperty(scrollContainer!, "clientHeight", {
configurable: true,
writable: true,
value: 800,
});
scrollWrites.length = 0;
// Act: an in-progress goal advances — a store update only, with no change
// to `renderableEvents` (in-progress goal events are filtered out).
act(() => {
useGoalStore.getState().setStatus("test-conversation-id", {
active: true,
status: "running",
iteration: 1,
max_iterations: 10,
objective: "make pytest pass",
verdict: { score: 0.5, complete: false, missing: "needs tests" },
});
});
// Assert: the bottom-following effect scrolled the banner into view.
// Without wiring the active goal status into that effect, scrollWrites
// would stay empty.
await waitFor(() => {
expect(scrollWrites).toContain(10000);
});
});
});
describe("ChatInterface - Status Indicator", () => {
it("shows the unresolved terminal action while the agent is running", () => {
const terminalAction: ActionEvent = {
id: "action-running-terminal",
timestamp: "2026-07-27T18:00:00Z",
source: "agent",
thought: [],
thinking_blocks: [],
action: {
kind: "TerminalAction",
command: "git status",
is_input: false,
timeout: null,
reset: false,
},
tool_name: "terminal",
tool_call_id: "tool-running-terminal",
tool_call: {
id: "tool-running-terminal",
type: "function",
function: {
name: "terminal",
arguments: '{"command":"git status"}',
},
},
llm_response_id: "response-running-terminal",
security_risk: SecurityRisk.LOW,
};
useEventStore.setState({
events: [terminalAction],
eventIds: new Set([terminalAction.id]),
uiEvents: [terminalAction],
});
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.RUNNING,
});
renderChatInterfaceWithRouter();
const chip = screen.getByTestId("live-activity-chip");
expect(chip).toHaveTextContent("ACTION_MESSAGE$RUN");
expect(chip.parentElement).toHaveClass("inset-x-9");
});
it("hides the live activity chip when the agent is no longer running", () => {
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.PAUSED,
});
renderChatInterfaceWithRouter();
expect(screen.queryByTestId("live-activity-chip")).not.toBeInTheDocument();
});
it("should render ChatStatusIndicator when agent is not awaiting user input / conversation is NOT ready", () => {
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.LOADING,
});
renderChatInterfaceWithRouter();
expect(screen.getByTestId("chat-status-indicator")).toBeInTheDocument();
});
it("should NOT render ChatStatusIndicator when agent is awaiting user input / conversation is ready", () => {
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.AWAITING_USER_INPUT,
});
renderChatInterfaceWithRouter();
expect(
screen.queryByTestId("chat-status-indicator"),
).not.toBeInTheDocument();
});
});
describe("ChatInterface - Tracking", () => {
let queryClient: QueryClient;
beforeEach(() => {
vi.clearAllMocks();
mockSend.mockResolvedValue({ queued: false });
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useErrorMessageStore.setState({ errorMessage: null });
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi
.fn()
.mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
isLoading: false,
});
useEventStore.setState({ events: [], eventIds: new Set(), uiEvents: [] });
});
function renderInterface() {
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/test-conversation-id"]}>
<Routes>
<Route path=":conversationId" element={<ChatInterface />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
it("calls trackInitialQuerySubmitted when the first message is sent (empty conversation)", async () => {
renderInterface();
act(() => {
useConversationStore.setState({ submittedMessage: "my first task" });
});
await waitFor(() => {
expect(trackInitialQuerySubmittedMock).toHaveBeenCalledWith(
expect.objectContaining({
queryCharacterLength: "my first task".length,
}),
);
});
});
it("calls trackUserMessageSent when a follow-up message is sent (non-empty conversation)", async () => {
// totalEvents = uiEvents.filter(shouldRenderAgentServerEvent).length.
// A MessageEvent (has llm_message.role + content) passes that filter,
// so seeding uiEvents with one makes totalEvents = 1.
useEventStore.setState({
events: [],
eventIds: new Set(),
uiEvents: [
{
id: "e1",
source: "user",
llm_message: { role: "user", content: "prior message" },
} as never,
],
});
renderInterface();
act(() => {
useConversationStore.setState({ submittedMessage: "follow-up" });
});
await waitFor(() => {
expect(trackUserMessageSentMock).toHaveBeenCalledWith(
expect.objectContaining({
currentMessageLength: "follow-up".length,
}),
);
});
expect(trackInitialQuerySubmittedMock).not.toHaveBeenCalled();
});
});
describe("ChatInterface - Build plan keyboard shortcut", () => {
let queryClient: QueryClient;
const BUILD_PROMPT =
"Execute the plan based on the .agents_tmp/PLAN.md file.";
beforeEach(() => {
vi.clearAllMocks();
mockSend.mockResolvedValue({ queued: false });
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
useOptimisticUserMessageStore.setState({ pendingMessages: [] });
useErrorMessageStore.setState({ errorMessage: null });
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
mutateAsync: vi
.fn()
.mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
isLoading: false,
});
useEventStore.setState({ events: [], eventIds: new Set(), uiEvents: [] });
});
function renderInterface() {
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/test-conversation-id"]}>
<Routes>
<Route path=":conversationId" element={<ChatInterface />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
const pressBuildShortcut = () => {
fireEvent.keyDown(document, { key: "Enter", metaKey: true });
fireEvent.keyDown(document, { key: "Enter", ctrlKey: true });
};
const sentBuildPrompt = () =>
mockSend.mock.calls.some(([message]) =>
JSON.stringify(message).includes(BUILD_PROMPT),
);
it("does not send the build prompt in code mode", () => {
act(() => {
useConversationStore.setState({
conversationMode: "code",
planContent: null,
});
});
renderInterface();
pressBuildShortcut();
expect(sentBuildPrompt()).toBe(false);
});
it("does not send the build prompt in code mode when a plan exists", () => {
act(() => {
useConversationStore.setState({
conversationMode: "code",
planContent: "# Plan\n\n- step one",
});
});
renderInterface();
pressBuildShortcut();
expect(sentBuildPrompt()).toBe(false);
});
it("does not send the build prompt in plan mode when no plan exists", () => {
act(() => {
useConversationStore.setState({
conversationMode: "plan",
planContent: null,
});
});
renderInterface();
pressBuildShortcut();
expect(sentBuildPrompt()).toBe(false);
});
it("sends the build prompt in plan mode when a plan exists", async () => {
act(() => {
useConversationStore.setState({
conversationMode: "plan",
planContent: "# Plan\n\n- step one",
});
});
renderInterface();
fireEvent.keyDown(document, { key: "Enter", metaKey: true });
await waitFor(() => {
expect(sentBuildPrompt()).toBe(true);
});
});
});
|