Elffuss BraidHub

kikocis/continue public

Merge pull request #5866 from continuedev/dallin/auto-apply-fix

Expand Edit Tool tests, fix auto-apply duplicate responses
Changeset6ae8fdd230bd31761d83405803a0f2f435fa482a169f6e158cf2f8d561dcb295
AuthorDallin Romney <dallinromney@gmail.com> · 2025-06-26 15:59 -07:00
CommitterGitHub <noreply@github.com> · 2025-06-26 15:59 -07:00
Parents04e94bf72239, b4865f2e59c8

Browse the files at this changeset

22 files changed

modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +15 −13
@@ -11,8 +11,10 @@
1111 import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest";
1212 import { useWebviewListener } from "../../../hooks/useWebviewListener";
1313 import { useAppSelector } from "../../../redux/hooks";
14-import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall";
15-import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
14+import {
15+ selectApplyStateByStreamId,
16+ selectApplyStateByToolCallId,
17+} from "../../../redux/slices/sessionSlice";
1618 import { getFontSize } from "../../../util";
1719 import Spinner from "../../gui/Spinner";
1820 import { isTerminalCodeBlock } from "../utils";
@@ -54,6 +56,7 @@
5456 codeBlockIndex: number; // To track which codeblock we are applying
5557 isLastCodeblock: boolean;
5658 codeBlockStreamId: string;
59+ forceToolCallId?: string; // If this is defined, we will use this streamId instead of the one from the codeBlock
5760 range?: string;
5861 children: any;
5962 expanded?: boolean;
@@ -68,6 +71,7 @@
6871 codeBlockIndex,
6972 isLastCodeblock,
7073 codeBlockStreamId,
74+ forceToolCallId,
7175 range,
7276 children,
7377 expanded,
@@ -99,8 +103,8 @@
99103 const applyState = useAppSelector((state) =>
100104 selectApplyStateByStreamId(state, codeBlockStreamId),
101105 );
102- const currentToolCallApplyState = useAppSelector(
103- selectCurrentToolCallApplyState,
106+ const toolCallApplyState = useAppSelector((state) =>
107+ selectApplyStateByToolCallId(state, forceToolCallId),
104108 );
105109
106110 /**
@@ -147,7 +151,7 @@
147151 setRelativeFilepathUri(resolvedUri);
148152 }
149153 };
150- getRelativeFilepathUri();
154+ void getRelativeFilepathUri();
151155 }, [relativeFilepath, ideMessenger.ide]);
152156
153157 async function getFileUriToApplyTo() {
@@ -173,7 +177,7 @@
173177 async function onClickApply() {
174178 const fileUri = await getFileUriToApplyTo();
175179 if (!fileUri) {
176- ideMessenger.ide.showToast(
180+ void ideMessenger.ide.showToast(
177181 "error",
178182 "Could not resolve filepath to apply changes",
179183 );
@@ -188,7 +192,7 @@
188192 });
189193
190194 setAppliedFileUri(fileUri);
191- refreshFileExists();
195+ void refreshFileExists();
192196 }
193197
194198 function onClickInsertAtCursor() {
@@ -198,7 +202,7 @@
198202 async function handleDiffAction(action: "accept" | "reject") {
199203 const filepath = await getFileUriToApplyTo();
200204 if (!filepath) {
201- ideMessenger.ide.showToast(
205+ void ideMessenger.ide.showToast(
202206 "error",
203207 `Could not resolve filepath to ${action} changes`,
204208 );
@@ -233,10 +237,7 @@
233237 }
234238
235239 const renderActionButtons = () => {
236- const isPendingToolCall =
237- currentToolCallApplyState &&
238- currentToolCallApplyState.streamId === applyState?.streamId &&
239- currentToolCallApplyState.status === "not-started";
240+ const isPendingToolCall = toolCallApplyState?.status === "not-started";
240241
241242 if (isGeneratingCodeBlock || isPendingToolCall) {
242243 const numLines = codeBlockContent.split("\n").length;
@@ -271,7 +272,7 @@
271272 return (
272273 <ApplyActions
273274 disableManualApply={disableManualApply}
274- applyState={applyState}
275+ applyState={toolCallApplyState ?? applyState}
275276 onClickApply={onClickApply}
276277 onClickAccept={() => handleDiffAction("accept")}
277278 onClickReject={() => handleDiffAction("reject")}
@@ -293,6 +294,7 @@
293294 <ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
294295 <div className="max-w-[50% flex flex-row items-center">
295296 <ChevronDownIcon
297+ data-testid="toggle-codeblock"
296298 onClick={() => setIsExpanded(!isExpanded)}
297299 className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
298300 isExpanded ? "rotate-0" : "-rotate-90"
modified gui/src/components/StyledMarkdownPreview/index.tsx +4 −9
@@ -126,7 +126,7 @@
126126 itemIndex?: number;
127127 useParentBackgroundColor?: boolean;
128128 disableManualApply?: boolean;
129- forceStreamId?: string;
129+ toolCallId?: string;
130130 expandCodeblocks?: boolean;
131131 }
132132
@@ -196,11 +196,6 @@
196196 const itemIndexRef = useUpdatingRef(props.itemIndex);
197197
198198 const codeblockStreamIds = useRef<string[]>([]);
199- useEffect(() => {
200- if (props.forceStreamId) {
201- codeblockStreamIds.current = [props.forceStreamId];
202- }
203- }, [props.forceStreamId, codeblockStreamIds]);
204199
205200 const [reactContent, setMarkdownSource] = useRemark({
206201 remarkPlugins: [
@@ -295,8 +290,7 @@
295290 const isLastCodeblock = preChildProps["data-islastcodeblock"];
296291
297292 if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
298- codeblockStreamIds.current[codeBlockIndex] =
299- props.forceStreamId ?? uuidv4();
293+ codeblockStreamIds.current[codeBlockIndex] = uuidv4();
300294 }
301295
302296 return (
@@ -308,7 +302,8 @@
308302 relativeFilepath={relativeFilePath}
309303 isLastCodeblock={isLastCodeblock}
310304 range={range}
311- codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
305+ codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found
306+ forceToolCallId={props.toolCallId}
312307 expanded={props.expandCodeblocks}
313308 disableManualApply={props.disableManualApply}
314309 >
modified gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +4 −1
@@ -330,7 +330,10 @@
330330 ],
331331 editorProps: {
332332 attributes: {
333- class: "outline-none overflow-hidden",
333+ "data-testid": props.isMainInput
334+ ? "editor-input-main"
335+ : `editor-input-${props.inputId}`,
336+ class: "ProseMirror outline-none overflow-hidden",
334337 style: `font-size: ${getFontSize()}px;`,
335338 },
336339 },
modified gui/src/context/MockIdeMessenger.ts +111 −70
@@ -1,7 +1,6 @@
1-import { IDE, PromptLog } from "core";
1+import { ChatMessage, IDE, PromptLog } from "core";
22 import { AuthType } from "core/control-plane/AuthTypes";
33 import {
4- FromIdeProtocol,
54 FromWebviewProtocol,
65 ToCoreProtocol,
76 ToWebviewProtocol,
@@ -13,73 +12,83 @@
1312 GeneratorYieldType,
1413 WebviewSingleProtocolMessage,
1514 } from "core/protocol/util";
16-import { ChatMessage } from "../redux/store";
1715 import { IIdeMessenger } from "./IdeMessenger";
1816
19-async function defaultMockHandleMessage<T extends keyof FromWebviewProtocol>(
20- messageType: T,
21- data: FromWebviewProtocol[T][0],
22-): Promise<FromWebviewProtocol[T][1]> {
23- function returnFor<K extends keyof FromWebviewProtocol>(
24- _: K,
25- value: FromWebviewProtocol[K][1],
26- ): FromWebviewProtocol[T][1] {
27- return value as unknown as FromWebviewProtocol[T][1];
28- }
17+type MockResponses = Partial<{
18+ [K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
19+}>;
2920
30- switch (messageType) {
31- case "history/list":
32- return returnFor("history/list", [
33- {
34- title: "Session 1",
35- sessionId: "session-1",
36- dateCreated: new Date().toString(),
37- workspaceDirectory: "/tmp",
38- },
39- ]);
40- case "getControlPlaneSessionInfo":
41- return returnFor("getControlPlaneSessionInfo", {
42- AUTH_TYPE: AuthType.WorkOsStaging,
43- accessToken: "",
44- account: {
45- label: "",
46- id: "",
47- },
48- });
49- case "config/getSerializedProfileInfo":
50- return returnFor("config/getSerializedProfileInfo", {
51- organizations: [],
52- profileId: "test-profile",
53- result: {
54- config: undefined,
55- errors: [],
56- configLoadInterrupted: false,
57- },
58- selectedOrgId: "local",
59- });
60- default:
61- throw new Error(`Unknown message type ${messageType}`);
62- }
63-}
21+const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
22+ fileExists: true,
23+ getCurrentFile: {
24+ isUntitled: false,
25+ contents: "Current file contents",
26+ path: "file:///Users/user/workspace1/current_file.py",
27+ },
28+ "controlPlane/getFreeTrialStatus": {
29+ autocompleteLimit: 1000,
30+ optedInToFreeTrial: false,
31+ chatLimit: 1000,
32+ autocompleteCount: 0,
33+ chatCount: 0,
34+ },
35+ getWorkspaceDirs: [
36+ "file:///Users/user/workspace1",
37+ "file:///Users/user/workspace2",
38+ ],
39+ "history/list": [
40+ {
41+ title: "Session 1",
42+ sessionId: "session-1",
43+ dateCreated: new Date().toString(),
44+ workspaceDirectory: "/tmp",
45+ },
46+ ],
47+ "history/save": undefined,
48+ getControlPlaneSessionInfo: {
49+ AUTH_TYPE: AuthType.WorkOsStaging,
50+ accessToken: "",
51+ account: {
52+ label: "",
53+ id: "",
54+ },
55+ },
56+ "config/getSerializedProfileInfo": {
57+ organizations: [],
58+ profileId: "test-profile",
59+ result: {
60+ config: undefined,
61+ errors: [],
62+ configLoadInterrupted: false,
63+ },
64+ selectedOrgId: "local",
65+ },
66+ "chatDescriber/describe": "Session summary",
67+ applyToFile: undefined,
68+ acceptDiff: undefined,
69+};
6470
71+const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
72+ {
73+ role: "assistant",
74+ content: "This is a test",
75+ },
76+];
6577 export class MockIdeMessenger implements IIdeMessenger {
6678 ide: IDE;
67- private messageHandlers: Map<
68- keyof FromIdeProtocol,
69- Array<(data: any) => void>
70- > = new Map();
7179
7280 constructor() {
7381 this.ide = new MessageIde(
74- (messageType, data) => {
75- throw new Error("Not implemented");
82+ async (messageType, data) => {
83+ const response = await this.request.bind(this)(messageType, data);
84+ if (response.status === "error") {
85+ throw new Error(response.error);
86+ } else {
87+ return response.content;
88+ }
7689 },
7790 (messageType, callback) => {
78- // Store the callback in our handlers map
79- if (!this.messageHandlers.has(messageType)) {
80- this.messageHandlers.set(messageType, []);
81- }
82- this.messageHandlers.get(messageType)?.push(callback);
91+ return;
8392 },
8493 );
8594 }
@@ -109,16 +118,38 @@
109118 );
110119 }
111120
112- async *llmStreamChat(
113- msg: ToCoreProtocol["llm/streamChat"][0],
114- cancelToken: AbortSignal,
115- ): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
116- yield [
121+ responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
122+ chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
123+ chatStreamDelay: number = 0;
124+ setChatResponseText(text: string): void {
125+ this.chatResponse = [
117126 {
118127 role: "assistant",
119- content: "This is a test",
128+ content: text,
120129 },
121130 ];
131+ }
132+
133+ async *llmStreamChat(
134+ msg: ToCoreProtocol["llm/streamChat"][0],
135+ cancelToken: AbortSignal,
136+ ): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
137+ for (const response of this.chatResponse) {
138+ if (cancelToken.aborted) {
139+ console.log("MockIdeMessenger: Stream aborted");
140+ return undefined;
141+ }
142+ console.log(
143+ "MockIdeMessenger: Yielding chunk",
144+ JSON.stringify(response, null, 2),
145+ );
146+ yield [response];
147+ if (this.chatStreamDelay > 0) {
148+ await new Promise((resolve) =>
149+ setTimeout(resolve, this.chatStreamDelay),
150+ );
151+ }
152+ }
122153 return undefined;
123154 }
124155
@@ -133,12 +164,16 @@
133164 messageType: T,
134165 data: FromWebviewProtocol[T][0],
135166 ): Promise<WebviewSingleProtocolMessage<T>> {
136- const content = await defaultMockHandleMessage(messageType, data);
137- return {
138- status: "success",
139- content,
140- done: true,
141- };
167+ if (messageType in this.responses) {
168+ const content = this.responses[messageType];
169+ return {
170+ status: "success",
171+ content,
172+ done: true,
173+ };
174+ }
175+ console.error(messageType);
176+ throw new Error("MockIdeMessenger: No response defined for " + messageType);
142177 }
143178
144179 respond<T extends keyof ToWebviewProtocol>(
@@ -157,4 +192,10 @@
157192 > {
158193 return undefined;
159194 }
195+
196+ resetMocks(): void {
197+ this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
198+ this.chatResponse = DEFAULT_CHAT_RESPONSE;
199+ this.chatStreamDelay = 0;
200+ }
160201 }
modified gui/src/hooks/ParallelListeners.tsx +38 −18
@@ -20,6 +20,7 @@
2020 import {
2121 acceptToolCall,
2222 addContextItemsAtIndex,
23+ selectCurrentToolCall,
2324 setHasReasoningEnabled,
2425 updateApplyState,
2526 } from "../redux/slices/sessionSlice";
@@ -244,6 +245,10 @@
244245 dispatch(updateIndexingStatus(data));
245246 });
246247
248+ const autoAcceptEditToolDiffs = useAppSelector(
249+ (store) => store.config.config.ui?.autoAcceptEditToolDiffs,
250+ );
251+ const currentToolCall = useAppSelector(selectCurrentToolCall);
247252 useWebviewListener(
248253 "updateApplyState",
249254 async (state) => {
@@ -259,30 +264,45 @@
259264
260265 // Handle apply status updates that are associated with current tool call
261266 if (
262- state.status === "closed" &&
263267 currentToolCallApplyState &&
264268 currentToolCallApplyState.streamId === state.streamId
265269 ) {
266- // const output: ContextItem = {
267- // name: "Edit tool output",
268- // content: "Completed edit",
269- // description: "",
270- // };
271- dispatch(
272- acceptToolCall({
273- toolCallId: currentToolCallApplyState.toolCallId!,
274- }),
275- );
276- // dispatch(setToolCallOutput([]));
277- void dispatch(
278- streamResponseAfterToolCall({
279- toolCallId: currentToolCallApplyState.toolCallId!,
280- }),
281- );
270+ if (state.status === "done" && autoAcceptEditToolDiffs) {
271+ console.log("AUTO ACCEPTED");
272+ ideMessenger.post("acceptDiff", {
273+ streamId: state.streamId,
274+ filepath: state.filepath,
275+ });
276+ }
277+ if (state.status === "closed") {
278+ if (currentToolCall?.status !== "canceled") {
279+ dispatch(
280+ acceptToolCall({
281+ toolCallId: currentToolCallApplyState.toolCallId!,
282+ }),
283+ );
284+ }
285+ // const output: ContextItem = {
286+ // name: "Edit tool output",
287+ // content: "Completed edit",
288+ // description: "",
289+ // };
290+ // dispatch(setToolCallOutput([]));
291+ void dispatch(
292+ streamResponseAfterToolCall({
293+ toolCallId: currentToolCallApplyState.toolCallId!,
294+ }),
295+ );
296+ }
282297 }
283298 }
284299 },
285- [currentToolCallApplyState, history],
300+ [
301+ currentToolCall,
302+ currentToolCallApplyState,
303+ autoAcceptEditToolDiffs,
304+ ideMessenger,
305+ ],
286306 );
287307
288308 useEffect(() => {
deleted gui/src/pages/gui/Chat.test.tsx +0 −161
@@ -1,161 +0,0 @@
1-import { screen, waitFor } from "@testing-library/dom";
2-import { act } from "@testing-library/react";
3-import { renderWithProviders } from "../../util/test/render";
4-import { Chat } from "./Chat";
5-
6-describe("Chat page test", () => {
7- it("should render input box", async () => {
8- await renderWithProviders(<Chat />);
9- expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument();
10- });
11-
12- it("should be able to toggle modes", async () => {
13- await renderWithProviders(<Chat />);
14- expect(screen.getByText("Chat")).toBeInTheDocument();
15-
16- // Simulate cmd+. keyboard shortcut to toggle modes
17- act(() => {
18- document.dispatchEvent(
19- new KeyboardEvent("keydown", {
20- key: ".",
21- metaKey: true, // cmd key on Mac
22- }),
23- );
24- });
25-
26- // Check that it switched to Agent mode
27- expect(await screen.findByText("Agent")).toBeInTheDocument();
28-
29- act(() => {
30- document.dispatchEvent(
31- new KeyboardEvent("keydown", {
32- key: ".",
33- metaKey: true, // cmd key on Mac
34- }),
35- );
36- });
37-
38- // Check that it switched back to Chat mode
39- expect(await screen.findByText("Chat")).toBeInTheDocument();
40- });
41-
42- it.skip("should send a message and receive a response", async () => {
43- const { user, container } = await renderWithProviders(<Chat />);
44- const inputBox = await waitFor(() =>
45- container.querySelector(".ProseMirror")!.querySelector("p"),
46- );
47- expect(inputBox).toBeDefined();
48-
49- const sendButton = await screen.findByTestId("submit-input-button");
50-
51- await act(async () => {
52- // Focus input box
53- inputBox!.focus();
54-
55- // Type message
56- await user.type(inputBox!, "Hello, world!");
57-
58- sendButton.click();
59- });
60- expect(await screen.findByText("Hello, world!")).toBeInTheDocument();
61- });
62-
63- it("should handle apply updates and display the accept / reject all buttons", async () => {
64- const { ideMessenger } = await renderWithProviders(<Chat />);
65-
66- // Use queryByText which returns null when element isn't found
67- const acceptAllButton = screen.queryByText("Accept All");
68- const rejectAllButton = screen.queryByText("Reject All");
69-
70- // Assert that the buttons don't exist
71- expect(acceptAllButton).not.toBeInTheDocument();
72- expect(rejectAllButton).not.toBeInTheDocument();
73-
74- for (let i = 0; i < 5; i++) {
75- ideMessenger.mockMessageToWebview("updateApplyState", {
76- status: "streaming",
77- streamId: `12345`,
78- });
79- }
80-
81- ideMessenger.mockMessageToWebview("updateApplyState", {
82- status: "done",
83- streamId: "12345",
84- });
85-
86- // Wait for the buttons to appear
87- await waitFor(() => {
88- expect(
89- screen.getByTestId("accept-reject-all-buttons"),
90- ).toBeInTheDocument();
91- });
92-
93- // IDE sends back message that it is done
94- ideMessenger.mockMessageToWebview("updateApplyState", {
95- status: "closed",
96- streamId: "12345",
97- });
98-
99- // Wait for the buttons to disappear
100- await waitFor(() => {
101- expect(
102- screen.queryByTestId("edit-accept-button"),
103- ).not.toBeInTheDocument();
104- expect(
105- screen.queryByTestId("edit-reject-button"),
106- ).not.toBeInTheDocument();
107- });
108- });
109-
110- it("should show apply cancellation", async () => {
111- const { ideMessenger } = await renderWithProviders(<Chat />);
112-
113- // Spy on the request method of ideMessenger
114- const messengerPostSpy = vi.spyOn(ideMessenger, "post");
115-
116- for (let i = 0; i < 5; i++) {
117- ideMessenger.mockMessageToWebview("updateApplyState", {
118- status: "streaming",
119- streamId: `12345`,
120- });
121- }
122-
123- // Wait for applying toolbar to appear
124- await waitFor(() => {
125- const cancelApplyButton = screen.getByTestId(
126- "notch-applying-cancel-button",
127- );
128- const applyingText = screen.getByTestId("notch-applying-text");
129-
130- expect(cancelApplyButton).toBeInTheDocument();
131- expect(applyingText).toBeInTheDocument();
132- });
133-
134- const cancelApplyButton = screen.getByTestId(
135- "notch-applying-cancel-button",
136- );
137- cancelApplyButton.click();
138-
139- // Verify that rejectDiff message has been posted to ideMessenger
140- expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
141-
142- // Now simulate the IDE sending back a message that the apply state is closed
143- ideMessenger.mockMessageToWebview("updateApplyState", {
144- status: "closed",
145- streamId: "12345",
146- });
147-
148- await waitFor(() => {
149- const cancelApplyButton = screen.queryByTestId(
150- "notch-applying-cancel-button",
151- );
152- const applyingText = screen.queryByTestId("notch-applying-text");
153-
154- expect(cancelApplyButton).not.toBeInTheDocument();
155- expect(applyingText).not.toBeInTheDocument();
156- });
157-
158- // Cleanup spy
159- messengerPostSpy.mockRestore();
160- });
161-});
modified gui/src/pages/gui/ToolCallDiv/EditFile.tsx +1 −26
@@ -1,12 +1,5 @@
11 import { getMarkdownLanguageTagForFile } from "core/util";
2-import { useEffect } from "react";
3-import { v4 as uuidv4 } from "uuid";
42 import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
5-import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
6-import {
7- selectApplyStateByToolCallId,
8- updateApplyState,
9-} from "../../../redux/slices/sessionSlice";
103
114 type EditToolCallProps = {
125 relativeFilePath: string;
@@ -16,24 +9,6 @@
169 };
1710
1811 export function EditFile(props: EditToolCallProps) {
19- const dispatch = useAppDispatch();
20-
21- const applyState = useAppSelector((state) =>
22- selectApplyStateByToolCallId(state, props.toolCallId),
23- );
24-
25- useEffect(() => {
26- if (!applyState) {
27- dispatch(
28- updateApplyState({
29- streamId: uuidv4(),
30- toolCallId: props.toolCallId,
31- status: "not-started",
32- }),
33- );
34- }
35- }, [applyState, props.toolCallId]);
36-
3712 if (!props.relativeFilePath || !props.changes) {
3813 return null;
3914 }
@@ -45,7 +20,7 @@
4520 isRenderingInStepContainer
4621 disableManualApply
4722 source={src}
48- forceStreamId={applyState?.streamId}
23+ toolCallId={props.toolCallId}
4924 expandCodeblocks={false}
5025 itemIndex={props.historyIndex}
5126 />
added gui/src/pages/gui/chat-tests/ApplyScenarios.test.tsx +80 −0
@@ -0,0 +1,80 @@
1+import { act } from "@testing-library/react";
2+import { renderWithProviders } from "../../../util/test/render";
3+import {
4+ getElementByTestId,
5+ verifyNotPresentByTestId,
6+ verifyNotPresentByText,
7+} from "../../../util/test/utils";
8+import { Chat } from "../Chat";
9+
10+test("Chat apply scenarios: handle apply updates and display the accept / reject all buttons", async () => {
11+ const { ideMessenger } = await renderWithProviders(<Chat />);
12+
13+ // Use queryByText which returns null when element isn't found
14+ await verifyNotPresentByText("Accept All");
15+ await verifyNotPresentByText("Reject All");
16+
17+ for (let i = 0; i < 5; i++) {
18+ ideMessenger.mockMessageToWebview("updateApplyState", {
19+ status: "streaming",
20+ streamId: `12345`,
21+ });
22+ }
23+
24+ ideMessenger.mockMessageToWebview("updateApplyState", {
25+ status: "done",
26+ streamId: "12345",
27+ });
28+
29+ // Wait for the buttons to appear
30+ await getElementByTestId("accept-reject-all-buttons");
31+
32+ // IDE sends back message that it is done
33+ ideMessenger.mockMessageToWebview("updateApplyState", {
34+ status: "closed",
35+ streamId: "12345",
36+ });
37+
38+ // Wait for the buttons to disappear
39+ await verifyNotPresentByTestId("edit-accept-button");
40+ await verifyNotPresentByTestId("edit-reject-button");
41+});
42+
43+test("Chat apply scenarios: show apply cancellation", async () => {
44+ const { ideMessenger } = await renderWithProviders(<Chat />);
45+
46+ // Spy on the request method of ideMessenger
47+ const messengerPostSpy = vi.spyOn(ideMessenger, "post");
48+
49+ for (let i = 0; i < 5; i++) {
50+ ideMessenger.mockMessageToWebview("updateApplyState", {
51+ status: "streaming",
52+ streamId: `12345`,
53+ });
54+ }
55+
56+ // Wait for applying toolbar to appear
57+ await getElementByTestId("notch-applying-text");
58+
59+ await act(async () => {
60+ const cancelApplyButton = await getElementByTestId(
61+ "notch-applying-cancel-button",
62+ );
63+ cancelApplyButton.click();
64+ });
65+
66+ // Verify that rejectDiff message has been posted to ideMessenger
67+ expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
68+
69+ // Now simulate the IDE sending back a message that the apply state is closed
70+ ideMessenger.mockMessageToWebview("updateApplyState", {
71+ status: "closed",
72+ streamId: "12345",
73+ });
74+
75+ await verifyNotPresentByTestId("notch-applying-text");
76+ await verifyNotPresentByTestId("notch-applying-cancel-button");
77+
78+ // Cleanup spy
79+ messengerPostSpy.mockRestore();
80+});
added gui/src/pages/gui/chat-tests/Chat.test.tsx +61 −0
@@ -0,0 +1,61 @@
1+import { act } from "@testing-library/react";
2+import { addAndSelectMockLlm } from "../../../util/test/config";
3+import { renderWithProviders } from "../../../util/test/render";
4+import {
5+ getElementByTestId,
6+ getElementByText,
7+ sendInputWithMockedResponse,
8+} from "../../../util/test/utils";
9+import { Chat } from "../Chat";
10+
11+test("should render input box", async () => {
12+ await renderWithProviders(<Chat />);
13+ await getElementByTestId("continue-input-box");
14+});
15+
16+test("should be able to toggle modes", async () => {
17+ await renderWithProviders(<Chat />);
18+ await getElementByText("Chat");
19+
20+ // Simulate cmd+. keyboard shortcut to toggle modes
21+ act(() => {
22+ document.dispatchEvent(
23+ new KeyboardEvent("keydown", {
24+ key: ".",
25+ metaKey: true, // cmd key on Mac
26+ }),
27+ );
28+ });
29+
30+ // Check that it switched to Agent mode
31+ await getElementByText("Agent");
32+
33+ act(() => {
34+ document.dispatchEvent(
35+ new KeyboardEvent("keydown", {
36+ key: ".",
37+ metaKey: true, // cmd key on Mac
38+ }),
39+ );
40+ });
41+
42+ await getElementByText("Chat");
43+});
44+
45+test("should send a message and receive a response", async () => {
46+ const { ideMessenger, store } = await renderWithProviders(<Chat />);
47+
48+ // First add and select the mock LLM
49+ await act(async () => {
50+ addAndSelectMockLlm(store, ideMessenger);
51+ });
52+
53+ const CONTENT = "Expected response";
54+ const INPUT = "User input";
55+
56+ await sendInputWithMockedResponse(ideMessenger, INPUT, [
57+ { role: "assistant", content: CONTENT },
58+ ]);
59+
60+ await getElementByText(CONTENT);
61+});
added gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +231 −0
@@ -0,0 +1,231 @@
1+import { BuiltInToolNames } from "core/tools/builtIn";
2+import {
3+ addAndSelectMockLlm,
4+ triggerConfigUpdate,
5+} from "../../../util/test/config";
6+import { renderWithProviders } from "../../../util/test/render";
7+import { Chat } from "../Chat";
8+
9+import { waitFor } from "@testing-library/dom";
10+import { ChatMessage } from "core";
11+import { toggleToolSetting } from "../../../redux/slices/uiSlice";
12+import {
13+ getElementByTestId,
14+ getElementByText,
15+ sendInputWithMockedResponse,
16+ verifyNotPresentByTestId,
17+} from "../../../util/test/utils";
18+
19+const EDIT_WORKSPACE_DIR = "file:///workspace";
20+const EDIT_FILEPATH = "test.txt";
21+const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`;
22+const EDIT_CHANGES = "New content";
23+const EDIT_TOOL_CALL_ID = "known-id";
24+const EDIT_MESSAGES: ChatMessage[] = [
25+ {
26+ role: "assistant",
27+ content: "",
28+ toolCalls: [
29+ {
30+ id: EDIT_TOOL_CALL_ID,
31+ function: {
32+ name: BuiltInToolNames.EditExistingFile,
33+ arguments: JSON.stringify({
34+ filepath: EDIT_FILEPATH,
35+ changes: EDIT_CHANGES,
36+ }),
37+ },
38+ },
39+ ],
40+ },
41+];
42+
43+const POST_EDIT_RESPONSE = "Edit applied successfully";
44+beforeEach(() => {
45+ vi.clearAllMocks();
46+});
47+
48+test("Edit run with ask first policy and no auto apply", async () => {
49+ // Setup
50+ const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
51+
52+ ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
53+ const messengerPostSpy = vi.spyOn(ideMessenger, "post");
54+
55+ addAndSelectMockLlm(store, ideMessenger);
56+
57+ // Send the input that will respond with an edit tool call
58+ await sendInputWithMockedResponse(
59+ ideMessenger,
60+ "Edit this file",
61+ EDIT_MESSAGES,
62+ );
63+
64+ // Toggle the codeblock and make sure the changes show
65+ const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
66+
67+ await user.click(toggleCodeblockChevron);
68+ await getElementByText(EDIT_CHANGES);
69+
70+ // Pending tool call - find and click the accept button
71+ const acceptToolCallButton = await getElementByTestId(
72+ "accept-tool-call-button",
73+ );
74+ await user.click(acceptToolCallButton);
75+
76+ // Tool call, check that applyToFile was called for edit
77+ await waitFor(() => {
78+ expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
79+ streamId: expect.any(String),
80+ filepath: EDIT_FILE_URI,
81+ text: EDIT_CHANGES,
82+ toolCallId: EDIT_TOOL_CALL_ID,
83+ });
84+ });
85+
86+ // Extract stream ID and initiate mock streaming
87+ const streamId = messengerPostSpy.mock.calls.find(
88+ (call) => call[0] === "applyToFile",
89+ )?.[1]?.streamId;
90+ expect(streamId).toBeDefined();
91+
92+ ideMessenger.mockMessageToWebview("updateApplyState", {
93+ status: "streaming",
94+ streamId,
95+ toolCallId: EDIT_TOOL_CALL_ID,
96+ filepath: EDIT_FILE_URI,
97+ });
98+
99+ // Mid stream, should show applying in notch
100+ await getElementByTestId("notch-applying-text");
101+ await getElementByTestId("notch-applying-cancel-button");
102+
103+ // Close the stream
104+ ideMessenger.mockMessageToWebview("updateApplyState", {
105+ status: "done",
106+ streamId,
107+ toolCallId: EDIT_TOOL_CALL_ID,
108+ filepath: EDIT_FILE_URI,
109+ });
110+
111+ // Verify accept/reject buttons are present
112+ const acceptButton = await getElementByTestId("edit-accept-button");
113+ await getElementByTestId("edit-reject-button");
114+
115+ // Accept the changes, which should trigger a response after the tool call
116+ await user.click(acceptButton);
117+
118+ expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
119+ streamId,
120+ filepath: EDIT_FILE_URI,
121+ });
122+
123+ ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
124+ ideMessenger.mockMessageToWebview("updateApplyState", {
125+ status: "closed",
126+ streamId,
127+ toolCallId: EDIT_TOOL_CALL_ID,
128+ filepath: EDIT_FILE_URI,
129+ });
130+
131+ await verifyNotPresentByTestId("edit-accept-button");
132+ await verifyNotPresentByTestId("edit-reject-button");
133+
134+ await getElementByText(POST_EDIT_RESPONSE);
135+});
136+
137+test("Edit run with no policy and yolo mode", async () => {
138+ // Setup
139+ const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
140+
141+ ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
142+ const messengerPostSpy = vi.spyOn(ideMessenger, "post");
143+
144+ addAndSelectMockLlm(store, ideMessenger);
145+
146+ // Enable automatic edit and yolo mode
147+ store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile));
148+ triggerConfigUpdate({
149+ store,
150+ ideMessenger,
151+ editConfig: (current) => {
152+ current.ui = {
153+ ...current.ui,
154+ autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs
155+ };
156+ return current;
157+ },
158+ });
159+ expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true);
160+
161+ // Send the input that will respond with an edit tool call
162+ await sendInputWithMockedResponse(
163+ ideMessenger,
164+ "Edit this file",
165+ EDIT_MESSAGES,
166+ );
167+
168+ // Toggle the codeblock and make sure the changes show
169+ const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
170+
171+ await user.click(toggleCodeblockChevron);
172+ await getElementByText(EDIT_CHANGES);
173+
174+ // Make sure there's no pending tool call
175+ verifyNotPresentByTestId("accept-tool-call-button");
176+ // Tool call, check that applyToFile was called for edit
177+ await waitFor(() => {
178+ expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
179+ streamId: expect.any(String),
180+ filepath: EDIT_FILE_URI,
181+ text: EDIT_CHANGES,
182+ toolCallId: EDIT_TOOL_CALL_ID,
183+ });
184+ });
185+
186+ // Extract stream ID and initiate mock streaming
187+ const streamId = messengerPostSpy.mock.calls.find(
188+ (call) => call[0] === "applyToFile",
189+ )?.[1]?.streamId;
190+ expect(streamId).toBeDefined();
191+
192+ ideMessenger.mockMessageToWebview("updateApplyState", {
193+ status: "streaming",
194+ streamId,
195+ toolCallId: EDIT_TOOL_CALL_ID,
196+ filepath: EDIT_FILE_URI,
197+ });
198+
199+ // Mid stream, should show applying in notch
200+ await getElementByTestId("notch-applying-text");
201+ await getElementByTestId("notch-applying-cancel-button");
202+
203+ // Close the stream
204+ ideMessenger.mockMessageToWebview("updateApplyState", {
205+ status: "done",
206+ streamId,
207+ toolCallId: EDIT_TOOL_CALL_ID,
208+ filepath: EDIT_FILE_URI,
209+ });
210+
211+ await waitFor(() => {
212+ expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
213+ streamId,
214+ filepath: EDIT_FILE_URI,
215+ });
216+ });
217+
218+ // Close the stream, ensure response is shown and diff buttons are not present
219+ ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
220+ ideMessenger.mockMessageToWebview("updateApplyState", {
221+ status: "closed",
222+ streamId,
223+ toolCallId: EDIT_TOOL_CALL_ID,
224+ filepath: EDIT_FILE_URI,
225+ });
226+
227+ await verifyNotPresentByTestId("edit-accept-button");
228+ await verifyNotPresentByTestId("edit-reject-button");
229+
230+ await getElementByText(POST_EDIT_RESPONSE);
231+});
modified gui/src/redux/slices/sessionSlice.ts +3 −1
@@ -657,7 +657,9 @@
657657 (state: RootState, toolCallId?: string) => toolCallId,
658658 ],
659659 (states, toolCallId) => {
660- return states.find((state) => state.toolCallId === toolCallId);
660+ if (toolCallId) {
661+ return states.find((state) => state.toolCallId === toolCallId);
662+ }
661663 },
662664 );
663665
modified gui/src/redux/store.ts +0 −5
@@ -23,11 +23,6 @@
2323 import tabsReducer from "./slices/tabsSlice";
2424 import uiReducer from "./slices/uiSlice";
2525
26-export interface ChatMessage {
27- role: "system" | "user" | "assistant";
28- content: string;
29-}
30-
3126 const rootReducer = combineReducers({
3227 session: sessionReducer,
3328 ui: uiReducer,
modified gui/src/redux/thunks/callCurrentTool.ts +2 −7
@@ -19,7 +19,6 @@
1919 async (_, { dispatch, extra, getState }) => {
2020 const state = getState();
2121 const toolCallState = selectCurrentToolCall(state);
22-
2322 if (!toolCallState) {
2423 return;
2524 }
@@ -61,19 +60,15 @@
6160 ) {
6261 // Tool is called on client side
6362 const {
64- output: clientToolOuput,
63+ output: clientToolOutput,
6564 respondImmediately,
6665 errorMessage: clientToolError,
6766 } = await callClientTool(toolCallState, {
6867 dispatch,
6968 ideMessenger: extra.ideMessenger,
70- streamId: state.session.codeBlockApplyStates.states.find(
71- (state) =>
72- state.toolCallId && state.toolCallId === toolCallState.toolCallId,
73- )?.streamId,
7469 getState,
7570 });
76- output = clientToolOuput;
71+ output = clientToolOutput;
7772 errorMessage = clientToolError;
7873 streamResponse = respondImmediately;
7974 } else {
modified gui/src/redux/thunks/edit.ts +3 −0
@@ -17,6 +17,7 @@
1717 import {
1818 newSession,
1919 setActive,
20+ setInactive,
2021 setIsInEdit,
2122 setMainEditorContentTrigger,
2223 setMode,
@@ -61,6 +62,8 @@
6162 range: codeToEdit[0] as RangeInFileWithContents,
6263 });
6364
65+ dispatch(setInactive());
66+
6467 if (response.status === "error") {
6568 throw new Error(response.error);
6669 }
modified gui/src/redux/thunks/streamNormalInput.ts +6 −0
@@ -8,6 +8,8 @@
88 import {
99 abortStream,
1010 addPromptCompletionPair,
11+ setActive,
12+ setInactive,
1113 setToolGenerated,
1214 streamUpdate,
1315 } from "../slices/sessionSlice";
@@ -53,6 +55,8 @@
5355 };
5456 }
5557
58+ dispatch(setActive());
59+
5660 // Send request
5761 const gen = extra.ideMessenger.llmStreamChat(
5862 {
@@ -76,6 +80,8 @@
7680 next = await gen.next();
7781 }
7882
83+ dispatch(setInactive());
84+
7985 // Attach prompt log and end thinking for reasoning models
8086 if (next.done && next.value) {
8187 dispatch(addPromptCompletionPair([next.value]));
modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +1 −7
@@ -4,11 +4,7 @@
44 import { renderContextItems } from "core/util/messageContent";
55 import { getBaseSystemMessage } from "../../util";
66 import { selectSelectedChatModel } from "../slices/configSlice";
7-import {
8- addContextItemsAtIndex,
9- setActive,
10- streamUpdate,
11-} from "../slices/sessionSlice";
7+import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
128 import { ThunkApiType } from "../store";
139 import { findToolCall } from "../util";
1410 import { resetStateForNewMessage } from "./resetStateForNewMessage";
@@ -63,8 +59,6 @@
6359 }),
6460 );
6561
66- dispatch(setActive());
67-
6862 const updatedHistory = getState().session.history;
6963 const messageMode = getState().session.mode;
7064
modified gui/src/redux/thunks/streamThunkWrapper.tsx +0 −2
@@ -1,6 +1,5 @@
11 import { createAsyncThunk } from "@reduxjs/toolkit";
22 import StreamErrorDialog from "../../pages/gui/StreamError";
3-import { setInactive } from "../slices/sessionSlice";
43 import { setDialogMessage, setShowDialog } from "../slices/uiSlice";
54 import { ThunkApiType } from "../store";
65 import { cancelStream } from "./cancelStream";
@@ -22,7 +21,6 @@
2221 }),
2322 );
2423 }
25- dispatch(setInactive());
2624 } catch (e) {
2725 dispatch(cancelStream());
2826 dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
modified gui/src/util/clientTools/callClientTool.ts +0 −1
@@ -8,7 +8,6 @@
88 getState: () => RootState;
99 dispatch: AppThunkDispatch;
1010 ideMessenger: IIdeMessenger;
11- streamId?: string;
1211 }
1312
1413 export interface ClientToolOutput {
modified gui/src/util/clientTools/editImpl.ts +5 −24
@@ -1,14 +1,11 @@
11 import { resolveRelativePathInDir } from "core/util/ideUtils";
2+import { v4 as uuid } from "uuid";
23 import { ClientToolImpl } from "./callClientTool";
3-
44 export const editToolImpl: ClientToolImpl = async (
55 args,
66 toolCallId,
77 extras,
88 ) => {
9- if (!extras.streamId) {
10- throw new Error("Invalid apply state");
11- }
129 const firstUriMatch = await resolveRelativePathInDir(
1310 args.filepath,
1411 extras.ideMessenger.ide,
@@ -16,30 +13,14 @@
1613 if (!firstUriMatch) {
1714 throw new Error(`${args.filepath} does not exist`);
1815 }
19- const apply = await extras.ideMessenger.request("applyToFile", {
20- streamId: extras.streamId,
16+ const streamId = uuid();
17+ extras.ideMessenger.post("applyToFile", {
18+ streamId,
2119 text: args.changes,
2220 toolCallId,
2321 filepath: firstUriMatch,
2422 });
25- if (apply.status === "error") {
26- throw new Error(apply.error);
27- }
28- const state = extras.getState();
29- const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs;
30- if (autoAccept) {
31- const out = await extras.ideMessenger.request("acceptDiff", {
32- streamId: extras.streamId,
33- filepath: firstUriMatch,
34- });
35- if (out.status === "error") {
36- throw new Error(out.error);
37- }
38- return {
39- respondImmediately: true,
40- output: undefined, // TODO - feed edit results back to model (also in parallel listeners)
41- };
42- }
23+
4324 return {
4425 respondImmediately: false,
4526 output: undefined, // No immediate output.
added gui/src/util/test/config.ts +67 −0
@@ -0,0 +1,67 @@
1+import { EnhancedStore } from "@reduxjs/toolkit";
2+import { BrowserSerializedContinueConfig, ModelDescription } from "core";
3+import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
4+import { copyOf } from "core/util";
5+import { MockIdeMessenger } from "../../context/MockIdeMessenger";
6+
7+interface TestConfigUpdateParams {
8+ store: EnhancedStore;
9+ ideMessenger: MockIdeMessenger;
10+ newProfileId?: string;
11+ newOrgId?: string;
12+ newOrgs?: SerializedOrgWithProfiles[];
13+ editConfig?: (
14+ current: BrowserSerializedContinueConfig,
15+ ) => BrowserSerializedContinueConfig;
16+}
17+
18+export function triggerConfigUpdate({
19+ store,
20+ ideMessenger,
21+ editConfig,
22+ newOrgs,
23+ newOrgId,
24+ newProfileId,
25+}: TestConfigUpdateParams) {
26+ const state = store.getState();
27+ ideMessenger.mockMessageToWebview("configUpdate", {
28+ organizations: newOrgs ?? state.profiles.organizations,
29+ selectedOrgId: newOrgId ?? state.profiles.selectedOrganizationId,
30+ profileId: newProfileId ?? state.profiles.selectedProfileId,
31+ result: {
32+ config: editConfig
33+ ? editConfig(copyOf(state.config.config))
34+ : state.config.config,
35+ configLoadInterrupted: false,
36+ errors: [],
37+ },
38+ });
39+}
40+
41+export function addAndSelectChatModel(
42+ store: EnhancedStore,
43+ ideMessenger: MockIdeMessenger,
44+ llmDesc: ModelDescription,
45+) {
46+ triggerConfigUpdate({
47+ store,
48+ ideMessenger,
49+ editConfig(current) {
50+ current.modelsByRole.chat.push(llmDesc);
51+ current.selectedModelByRole.chat = llmDesc;
52+ return current;
53+ },
54+ });
55+}
56+
57+export function addAndSelectMockLlm(
58+ store: EnhancedStore,
59+ ideMessenger: MockIdeMessenger,
60+) {
61+ addAndSelectChatModel(store, ideMessenger, {
62+ model: "mock",
63+ provider: "mock",
64+ title: "Mock LLM",
65+ underlyingProviderName: "mock",
66+ });
67+}
added gui/src/util/test/utils.ts +102 −0
@@ -0,0 +1,102 @@
1+import { screen, waitFor } from "@testing-library/dom";
2+import { act } from "@testing-library/react";
3+import { Editor } from "@tiptap/core";
4+import { ChatMessage } from "core";
5+import { MockIdeMessenger } from "../../context/MockIdeMessenger";
6+
7+function logDomText() {
8+ const bodyText = document.body.innerHTML;
9+ const parser = new DOMParser();
10+ const doc = parser.parseFromString(bodyText, "text/html");
11+ let cleaned = doc.body.textContent ?? "";
12+ cleaned = cleaned?.replace(
13+ "No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first assistant",
14+ "",
15+ );
16+ cleaned = cleaned?.replace(
17+ "Alt⏎ Active file⏎ Enter⏎Log in to access a free trial of theModels Add-OnLog in to Continue HubOr, configure your own models",
18+ "",
19+ );
20+ cleaned = cleaned.replaceAll("Select model", "");
21+ cleaned = cleaned.replaceAll("Mock LLM", "");
22+ cleaned = cleaned.replaceAll(/^Chat|Chat$/g, "");
23+ console.log(cleaned || "No body content");
24+}
25+
26+export function logAllTestIds() {
27+ const elements = document.querySelectorAll("*");
28+
29+ const testIds = Array.from(elements)
30+ .map((el) => Array.from(el.attributes))
31+ .flat()
32+ .filter((a) => a.name === "data-testid")
33+ .map((a) => a.value);
34+ console.log("Available test ids", testIds);
35+}
36+export async function getElementByTestId(testId: string): Promise<HTMLElement> {
37+ try {
38+ const testIdElement = await waitFor(() => screen.findByTestId(testId));
39+ expect(testIdElement).toBeInTheDocument();
40+ return testIdElement;
41+ } catch (e) {
42+ logAllTestIds();
43+ throw new Error(`Element with testId "${testId}" not found`);
44+ }
45+}
46+
47+export async function verifyNotPresentByTestId(testId: string): Promise<void> {
48+ const element = await waitFor(() => screen.queryByTestId(testId));
49+ expect(element).not.toBeInTheDocument();
50+}
51+
52+export async function verifyNotPresentByText(text: string): Promise<void> {
53+ const element = screen.queryByText(text);
54+ expect(element).not.toBeInTheDocument();
55+}
56+
57+export async function getElementByText(text: string): Promise<HTMLElement> {
58+ try {
59+ const textElement = await waitFor(() => screen.findByText(text));
60+ expect(textElement).toBeInTheDocument();
61+ return textElement;
62+ } catch (e) {
63+ logDomText();
64+ throw new Error(`Element with text "${text}" not found.`);
65+ }
66+}
67+
68+export async function getMainEditor(): Promise<Editor> {
69+ const editorElement = await getElementByTestId("editor-input-main");
70+ if ("editor" in editorElement) {
71+ return editorElement.editor as Editor;
72+ } else {
73+ throw new Error("Main editor not found within editor container");
74+ }
75+}
76+
77+export async function sendInputWithMockedResponse(
78+ ideMessenger: MockIdeMessenger,
79+ input: string,
80+ response: ChatMessage[],
81+): Promise<void> {
82+ // Setup the mock response before any actions
83+ ideMessenger.chatResponse = response;
84+
85+ // Wait for the editor to be in the document
86+ const editor = await getMainEditor();
87+
88+ // Find the submit button
89+ const sendButton = await getElementByTestId("submit-input-button");
90+
91+ // Insert content into the editor
92+ await act(async () => {
93+ editor.commands.insertContent(input);
94+ });
95+
96+ await getElementByText(input);
97+
98+ // Click the send button
99+ await act(async () => {
100+ sendButton.click();
101+ });
102+}
modified gui/vite.config.ts +13 −0
@@ -32,5 +32,18 @@
3232 globals: true,
3333 environment: "jsdom",
3434 setupFiles: "./src/util/test/setupTests.ts",
35+ onConsoleLog(log, type) {
36+ if (type === "stderr") {
37+ if (
38+ [
39+ "contentEditable",
40+ "An update to Chat inside a test was not wrapped in act",
41+ ].some((text) => log.includes(text))
42+ ) {
43+ return false;
44+ }
45+ }
46+ return true;
47+ },
3548 },
3649 });