From f9a0721df467af94bcd21a8328e79f82cac03e69 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 10:24:53 +0000 Subject: [PATCH 1/3] add API cllas for new AI hint endpoints and pollAiHint helper --- src/utils/apiCallHandler.js | 23 +++++ src/utils/apiCallHandler.test.js | 49 +++++++++ src/utils/pollAiHint.js | 69 +++++++++++++ src/utils/pollAiHint.test.js | 167 +++++++++++++++++++++++++++++++ 4 files changed, 308 insertions(+) create mode 100644 src/utils/pollAiHint.js create mode 100644 src/utils/pollAiHint.test.js diff --git a/src/utils/apiCallHandler.js b/src/utils/apiCallHandler.js index 69094ae19..c99c09bf2 100644 --- a/src/utils/apiCallHandler.js +++ b/src/utils/apiCallHandler.js @@ -1,6 +1,8 @@ import axios from "axios"; import omit from "lodash/omit"; +const AI_HINT_REQUEST_TIMEOUT_MS = 5000; + const ApiCallHandler = ({ reactAppApiEndpoint }) => { const host = reactAppApiEndpoint; @@ -112,6 +114,25 @@ const ApiCallHandler = ({ reactAppApiEndpoint }) => { ); }; + const createAiHint = async ( + { message, trace, runtime, code }, + accessToken, + ) => { + return await post( + `${host}/api/ai_hints`, + { message, trace, runtime, code }, + { headers: headers(accessToken), timeout: AI_HINT_REQUEST_TIMEOUT_MS }, + ); + }; + + const getAiHint = async (id, accessToken, { signal } = {}) => { + return await get(`${host}/api/ai_hints/${encodeURIComponent(id)}`, { + headers: headers(accessToken), + timeout: AI_HINT_REQUEST_TIMEOUT_MS, + signal, + }); + }; + const getUserSettings = async (accessToken) => { return await get(`${host}/api/user_settings`, { headers: headers(accessToken), @@ -139,6 +160,8 @@ const ApiCallHandler = ({ reactAppApiEndpoint }) => { loadAssets, createError, getAiErrorHint, + createAiHint, + getAiHint, getUserSettings, updateUserSettings, }; diff --git a/src/utils/apiCallHandler.test.js b/src/utils/apiCallHandler.test.js index 0068912b2..9c7881320 100644 --- a/src/utils/apiCallHandler.test.js +++ b/src/utils/apiCallHandler.test.js @@ -17,6 +17,8 @@ const { createRemix, createError, getAiErrorHint, + createAiHint, + getAiHint, getUserSettings, updateUserSettings, } = ApiCallHandler({ reactAppApiEndpoint: host }); @@ -253,6 +255,53 @@ describe("Testing AI error hint API calls", () => { }); }); +describe("Testing async AI hint API calls", () => { + const errorDetails = { + message: "NameError: name 'prnt' is not defined on line 1 of main.py", + trace: "NameError: name 'prnt' is not defined on line 1 of main.py", + runtime: "skulpt", + code: 'prnt("Hello world")', + }; + const hintId = "6f1c1e2a-3b4d-4e5f-8a9b-0c1d2e3f4a5b"; + + test("Creating a hint posts error details and returns the id", async () => { + axios.post.mockImplementationOnce(() => + Promise.resolve({ status: 202, data: { id: hintId } }), + ); + + const response = await createAiHint(errorDetails, accessToken); + + expect(axios.post).toHaveBeenCalledWith( + `${host}/api/ai_hints`, + errorDetails, + { ...authHeaders, timeout: 5000 }, + ); + expect(response.data.id).toBe(hintId); + }); + + test("Getting a hint fetches it by id with the abort signal", async () => { + const { signal } = new AbortController(); + axios.get.mockImplementationOnce(() => + Promise.resolve({ + status: 200, + data: { status: "completed", hint: "A friendly hint" }, + }), + ); + + const response = await getAiHint(hintId, accessToken, { signal }); + + expect(axios.get).toHaveBeenCalledWith(`${host}/api/ai_hints/${hintId}`, { + ...authHeaders, + timeout: 5000, + signal, + }); + expect(response.data).toEqual({ + status: "completed", + hint: "A friendly hint", + }); + }); +}); + describe("Testing user settings API calls", () => { test("Getting user settings", async () => { axios.get.mockImplementationOnce(() => diff --git a/src/utils/pollAiHint.js b/src/utils/pollAiHint.js new file mode 100644 index 000000000..a9addc537 --- /dev/null +++ b/src/utils/pollAiHint.js @@ -0,0 +1,69 @@ +// Keep in step with GenerateAiHintJob::MAX_QUEUE_WAIT in editor-api. +export const AI_HINT_POLL_TIMEOUT_MS = 30000; +export const AI_HINT_POLL_INTERVAL_MS = 1000; + +export class AiHintPollError extends Error { + constructor(reason) { + super(`AI hint ${reason}`); + this.name = "AiHintPollError"; + this.reason = reason; + } +} + +const wait = (ms, signal) => + new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timer); + reject(new AiHintPollError("aborted")); + }; + + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + + signal?.addEventListener("abort", onAbort, { once: true }); + }); + +const throwIfAborted = (signal) => { + if (signal?.aborted) throw new AiHintPollError("aborted"); +}; + +const pollAiHint = async ( + id, + { + getAiHint, + signal, + intervalMs = AI_HINT_POLL_INTERVAL_MS, + timeoutMs = AI_HINT_POLL_TIMEOUT_MS, + }, +) => { + const deadline = Date.now() + timeoutMs; + + while (Date.now() + intervalMs <= deadline) { + throwIfAborted(signal); + await wait(intervalMs, signal); + + let data; + try { + ({ data } = await getAiHint(id, { signal })); + } catch (error) { + throwIfAborted(signal); + // Retry network errors and 5xx; a 4xx won't change. + const status = error?.response?.status; + if (status >= 400 && status < 500) throw new AiHintPollError("failed"); + continue; + } + throwIfAborted(signal); + + if (data?.status === "completed") { + if (!data.hint) throw new AiHintPollError("failed"); + return data.hint; + } + if (data?.status === "failed") throw new AiHintPollError("failed"); + } + + throw new AiHintPollError("timeout"); +}; + +export default pollAiHint; diff --git a/src/utils/pollAiHint.test.js b/src/utils/pollAiHint.test.js new file mode 100644 index 000000000..d7863f614 --- /dev/null +++ b/src/utils/pollAiHint.test.js @@ -0,0 +1,167 @@ +import pollAiHint, { AiHintPollError } from "./pollAiHint"; + +const hintId = "6f1c1e2a-3b4d-4e5f-8a9b-0c1d2e3f4a5b"; +const intervalMs = 1000; +const timeoutMs = 5000; + +const pending = { data: { status: "pending" } }; +const completed = { data: { status: "completed", hint: "A friendly hint" } }; +const failed = { data: { status: "failed" } }; +const httpError = (status) => + Object.assign(new Error(`HTTP ${status}`), { response: { status } }); + +let getAiHint; + +const startPolling = (signal) => { + const promise = pollAiHint(hintId, { + getAiHint, + signal, + intervalMs, + timeoutMs, + }); + // Stop unhandled rejection warnings before the test awaits it. + promise.catch(() => {}); + return promise; +}; + +const expectRejection = async (promise, reason) => { + await expect(promise).rejects.toBeInstanceOf(AiHintPollError); + await expect(promise).rejects.toMatchObject({ reason }); +}; + +beforeEach(() => { + vi.useFakeTimers(); + getAiHint = vi.fn(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test("waits one interval before the first poll", async () => { + getAiHint.mockResolvedValue(completed); + startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs - 1); + expect(getAiHint).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + expect(getAiHint).toHaveBeenCalledTimes(1); +}); + +test("passes the id and abort signal to getAiHint", async () => { + const { signal } = new AbortController(); + getAiHint.mockResolvedValue(completed); + const promise = startPolling(signal); + + await vi.advanceTimersByTimeAsync(intervalMs); + + await expect(promise).resolves.toBe("A friendly hint"); + expect(getAiHint).toHaveBeenCalledWith(hintId, { signal }); +}); + +test("keeps polling while pending and resolves with the hint", async () => { + getAiHint + .mockResolvedValueOnce(pending) + .mockResolvedValueOnce(pending) + .mockResolvedValueOnce(completed); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs * 3); + + await expect(promise).resolves.toBe("A friendly hint"); + expect(getAiHint).toHaveBeenCalledTimes(3); +}); + +test("rejects when the hint fails", async () => { + getAiHint.mockResolvedValueOnce(pending).mockResolvedValueOnce(failed); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs * 2); + + await expectRejection(promise, "failed"); + expect(getAiHint).toHaveBeenCalledTimes(2); +}); + +test("rejects when a completed hint is empty", async () => { + getAiHint.mockResolvedValue({ data: { status: "completed", hint: "" } }); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs); + + await expectRejection(promise, "failed"); +}); + +test.each([401, 404])( + "rejects without retrying on a %i response", + async (status) => { + getAiHint.mockRejectedValue(httpError(status)); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs * 3); + + await expectRejection(promise, "failed"); + expect(getAiHint).toHaveBeenCalledTimes(1); + }, +); + +test("keeps polling after a network error or 5xx", async () => { + getAiHint + .mockRejectedValueOnce(new Error("Network Error")) + .mockRejectedValueOnce(httpError(503)) + .mockResolvedValueOnce(completed); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(intervalMs * 3); + + await expect(promise).resolves.toBe("A friendly hint"); + expect(getAiHint).toHaveBeenCalledTimes(3); +}); + +test("rejects with a timeout once the deadline passes", async () => { + getAiHint.mockResolvedValue(pending); + const promise = startPolling(); + + await vi.advanceTimersByTimeAsync(timeoutMs); + + await expectRejection(promise, "timeout"); + expect(getAiHint).toHaveBeenCalledTimes(timeoutMs / intervalMs); +}); + +test("stops polling when aborted while waiting", async () => { + const controller = new AbortController(); + getAiHint.mockResolvedValue(pending); + const promise = startPolling(controller.signal); + + await vi.advanceTimersByTimeAsync(intervalMs); + controller.abort(); + await vi.advanceTimersByTimeAsync(intervalMs * 3); + + await expectRejection(promise, "aborted"); + expect(getAiHint).toHaveBeenCalledTimes(1); +}); + +test("rejects as aborted when aborted during a request", async () => { + const controller = new AbortController(); + getAiHint.mockImplementation(() => { + controller.abort(); + return Promise.reject(new Error("canceled")); + }); + const promise = startPolling(controller.signal); + + await vi.advanceTimersByTimeAsync(intervalMs); + + await expectRejection(promise, "aborted"); + expect(getAiHint).toHaveBeenCalledTimes(1); +}); + +test("does not poll when already aborted", async () => { + const controller = new AbortController(); + controller.abort(); + const promise = startPolling(controller.signal); + + await vi.advanceTimersByTimeAsync(intervalMs); + + await expectRejection(promise, "aborted"); + expect(getAiHint).not.toHaveBeenCalled(); +}); From 61ca84033deaf7e3b3f77282c3a5b6b7a3202fe9 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 10:38:04 +0000 Subject: [PATCH 2/3] Update AiErrorMessage to create and poll AI hint endpoints --- .../Editor/AiErrorMessage/AiErrorMessage.jsx | 40 +++-- .../AiErrorMessage/AiErrorMessage.test.jsx | 145 ++++++++++++------ src/utils/apiCallHandler.js | 14 -- src/utils/apiCallHandler.test.js | 25 --- 4 files changed, 126 insertions(+), 98 deletions(-) diff --git a/src/components/Editor/AiErrorMessage/AiErrorMessage.jsx b/src/components/Editor/AiErrorMessage/AiErrorMessage.jsx index f386af30b..ba1a1b53b 100644 --- a/src/components/Editor/AiErrorMessage/AiErrorMessage.jsx +++ b/src/components/Editor/AiErrorMessage/AiErrorMessage.jsx @@ -7,6 +7,7 @@ import BadgeQuestionMarkIcon from "../../../assets/icons/badge_question_mark.svg import SettingsIcon from "../../../assets/icons/settings.svg"; import { openAiHintSettings } from "../../../redux/EditorSlice"; import ApiCallHandler from "../../../utils/apiCallHandler"; +import pollAiHint from "../../../utils/pollAiHint"; import { getAiHintLinkComponents } from "../../../utils/aiHintLinks"; import { aiHintLearnMoreLinkClickedEvent, @@ -32,19 +33,18 @@ const AiErrorMessage = () => { const [failed, setFailed] = useState(false); const [hint, setHint] = useState(""); - // The error currently on screen, so a pending request can tell whether - // the user has moved on before it settles. - const currentErrorRef = useRef(errorDetails); + // Aborted when the error changes or the component unmounts, which stops + // polling and tells a pending request that the user has moved on. + const abortControllerRef = useRef(null); useEffect(() => { - currentErrorRef.current = errorDetails; + const controller = new AbortController(); + abortControllerRef.current = controller; setHint(""); setFailed(false); setLoading(false); - return () => { - currentErrorRef.current = null; - }; + return () => controller.abort(); }, [errorDetails]); // Showing the hint removes the button that had focus, so move focus to the result. @@ -60,17 +60,21 @@ const AiErrorMessage = () => { projectCode?.find((c) => c.name === "main" && c.extension === "py") ?.content ?? ""; + const { signal } = abortControllerRef.current; + const isStale = () => signal.aborted; + setLoading(true); setFailed(false); - const isStale = () => currentErrorRef.current !== errorDetails; const minLoadingTime = new Promise((resolve) => setTimeout(resolve, MIN_LOADING_MS), ); try { - const { getAiErrorHint } = ApiCallHandler({ reactAppApiEndpoint }); - const [{ data }] = await Promise.all([ - getAiErrorHint( + const { createAiHint, getAiHint } = ApiCallHandler({ + reactAppApiEndpoint, + }); + const requestHint = async () => { + const { data } = await createAiHint( { message: errorDetails.message, trace: errorDetails.trace, @@ -78,12 +82,16 @@ const AiErrorMessage = () => { code, }, accessToken, - ), - minLoadingTime, - ]); + ); + if (!data?.id) throw new Error("No hint id"); + return await pollAiHint(data.id, { + getAiHint: (id, options) => getAiHint(id, accessToken, options), + signal, + }); + }; + const [hintText] = await Promise.all([requestHint(), minLoadingTime]); if (isStale()) return; - if (!data?.fem) throw new Error("Empty hint"); - setHint(data.fem); + setHint(hintText); document.dispatchEvent( aiHintRequestedEvent({ projectIdentifier, diff --git a/src/components/Editor/AiErrorMessage/AiErrorMessage.test.jsx b/src/components/Editor/AiErrorMessage/AiErrorMessage.test.jsx index ab45c3cc2..61d235787 100644 --- a/src/components/Editor/AiErrorMessage/AiErrorMessage.test.jsx +++ b/src/components/Editor/AiErrorMessage/AiErrorMessage.test.jsx @@ -3,9 +3,11 @@ import { Provider } from "react-redux"; import { act, fireEvent, render, screen } from "@testing-library/react"; import AiErrorMessage, { MIN_LOADING_MS } from "./AiErrorMessage"; import ApiCallHandler from "../../../utils/apiCallHandler"; +import pollAiHint from "../../../utils/pollAiHint"; import { AI_HINT_LEARN_MORE_URL } from "../../../utils/aiHintLinks"; vi.mock("../../../utils/apiCallHandler"); +vi.mock("../../../utils/pollAiHint"); vi.mock("react-i18next", async () => { const { cloneElement, createElement } = await vi.importActual("react"); @@ -68,12 +70,17 @@ const clickButtonAndWait = async () => { await advanceTimers(MIN_LOADING_MS); }; -let getAiErrorHint; +const hintId = "6f1c1e2a-3b4d-4e5f-8a9b-0c1d2e3f4a5b"; + +let createAiHint; +let getAiHint; beforeEach(() => { vi.useFakeTimers(); - getAiErrorHint = vi.fn(); - ApiCallHandler.mockImplementation(() => ({ getAiErrorHint })); + createAiHint = vi.fn().mockResolvedValue({ data: { id: hintId } }); + getAiHint = vi.fn(); + ApiCallHandler.mockImplementation(() => ({ createAiHint, getAiHint })); + pollAiHint.mockReset(); }); afterEach(() => { @@ -98,15 +105,15 @@ describe("AiErrorMessage", () => { ).toBeInTheDocument(); }); - test("Sends the error details, main.py code and access token", async () => { - getAiErrorHint.mockResolvedValue({ data: { fem: "A friendly hint" } }); + test("Creates the hint with the error details, main.py code and access token", async () => { + pollAiHint.mockResolvedValue("A friendly hint"); renderAiErrorMessage(); await clickButtonAndWait(); expect(ApiCallHandler).toHaveBeenCalledWith({ reactAppApiEndpoint: "http://localhost:3009", }); - expect(getAiErrorHint).toHaveBeenCalledWith( + expect(createAiHint).toHaveBeenCalledWith( { message: errorDetails.message, trace: errorDetails.trace, @@ -117,9 +124,26 @@ describe("AiErrorMessage", () => { ); }); + test("Polls for the created hint with the access token and an abort signal", async () => { + pollAiHint.mockResolvedValue("A friendly hint"); + renderAiErrorMessage(); + await clickButtonAndWait(); + + expect(pollAiHint).toHaveBeenCalledWith(hintId, { + getAiHint: expect.any(Function), + signal: expect.any(AbortSignal), + }); + + const pollOptions = pollAiHint.mock.calls[0][1]; + const pollGetAiHint = pollOptions.getAiHint; + const signal = pollOptions.signal; + pollGetAiHint(hintId, { signal }); + expect(getAiHint).toHaveBeenCalledWith(hintId, accessToken, { signal }); + }); + test("Shows loading text while the hint is being generated", async () => { let resolveRequest; - getAiErrorHint.mockReturnValue( + pollAiHint.mockReturnValue( new Promise((resolve) => { resolveRequest = resolve; }), @@ -132,7 +156,7 @@ describe("AiErrorMessage", () => { screen.getAllByText("output.aiErrorMessages.loadingText").length, ).toBeGreaterThan(0); - await act(async () => resolveRequest({ data: { fem: "A friendly hint" } })); + await act(async () => resolveRequest("A friendly hint")); await advanceTimers(MIN_LOADING_MS); expect(screen.getByText("A friendly hint")).toBeInTheDocument(); expect( @@ -141,7 +165,7 @@ describe("AiErrorMessage", () => { }); test("Shows the hint and heading, and hides the button, on success", async () => { - getAiErrorHint.mockResolvedValue({ data: { fem: "A friendly hint" } }); + pollAiHint.mockResolvedValue("A friendly hint"); renderAiErrorMessage(); await clickButtonAndWait(); @@ -155,7 +179,7 @@ describe("AiErrorMessage", () => { }); test("Moves focus to the hint when it replaces the button", async () => { - getAiErrorHint.mockResolvedValue({ data: { fem: "A friendly hint" } }); + pollAiHint.mockResolvedValue("A friendly hint"); renderAiErrorMessage(); hintButton().focus(); await clickButtonAndWait(); @@ -164,7 +188,7 @@ describe("AiErrorMessage", () => { }); test("Moves focus to the error text when the request fails", async () => { - getAiErrorHint.mockRejectedValue(new Error("Bad gateway")); + pollAiHint.mockRejectedValue(new Error("Hint failed")); renderAiErrorMessage(); hintButton().focus(); await clickButtonAndWait(); @@ -179,7 +203,7 @@ describe("AiErrorMessage", () => { }); test("Keeps loading for the minimum time when the response is fast", async () => { - getAiErrorHint.mockResolvedValue({ data: { fem: "A friendly hint" } }); + pollAiHint.mockResolvedValue("A friendly hint"); renderAiErrorMessage(); clickButton(); @@ -192,7 +216,7 @@ describe("AiErrorMessage", () => { }); test("Keeps loading for the minimum time when the request fails fast", async () => { - getAiErrorHint.mockRejectedValue(new Error("Bad gateway")); + pollAiHint.mockRejectedValue(new Error("Hint failed")); renderAiErrorMessage(); clickButton(); @@ -208,7 +232,7 @@ describe("AiErrorMessage", () => { }); test("Shows the error text and keeps the button when the request fails", async () => { - getAiErrorHint.mockRejectedValue(new Error("Bad gateway")); + pollAiHint.mockRejectedValue(new Error("Hint failed")); renderAiErrorMessage(); await clickButtonAndWait(); @@ -223,26 +247,32 @@ describe("AiErrorMessage", () => { ).toBeInTheDocument(); }); - test.each([{ fem: "" }, {}])( - "Shows the error text when the response has empty hint in the form of %o", - async (data) => { - getAiErrorHint.mockResolvedValue({ data }); - renderAiErrorMessage(); - await clickButtonAndWait(); + test("Shows the error text without polling when creating the hint fails", async () => { + createAiHint.mockRejectedValue(new Error("Bad gateway")); + renderAiErrorMessage(); + await clickButtonAndWait(); - expect( - screen.getByText("output.aiErrorMessages.errorText"), - ).toBeInTheDocument(); - expect( - screen.getByText("output.aiErrorMessages.aiGeneratedHint"), - ).toBeInTheDocument(); - }, - ); + expect( + screen.getByText("output.aiErrorMessages.errorText"), + ).toBeInTheDocument(); + expect(pollAiHint).not.toHaveBeenCalled(); + }); + + test("Shows the error text without polling when no hint id is returned", async () => { + createAiHint.mockResolvedValue({ data: {} }); + renderAiErrorMessage(); + await clickButtonAndWait(); + + expect( + screen.getByText("output.aiErrorMessages.errorText"), + ).toBeInTheDocument(); + expect(pollAiHint).not.toHaveBeenCalled(); + }); test("Clears the error text and shows the hint when a retry succeeds", async () => { - getAiErrorHint - .mockRejectedValueOnce(new Error("Bad gateway")) - .mockResolvedValueOnce({ data: { fem: "A friendly hint" } }); + pollAiHint + .mockRejectedValueOnce(new Error("Hint failed")) + .mockResolvedValueOnce("A friendly hint"); renderAiErrorMessage(); await clickButtonAndWait(); @@ -258,7 +288,7 @@ describe("AiErrorMessage", () => { }); test("Resets to the button when a new error occurs", async () => { - getAiErrorHint.mockResolvedValue({ data: { fem: "A friendly hint" } }); + pollAiHint.mockResolvedValue("A friendly hint"); const { rerender } = renderAiErrorMessage(); await clickButtonAndWait(); expect(screen.getByText("A friendly hint")).toBeInTheDocument(); @@ -278,6 +308,41 @@ describe("AiErrorMessage", () => { ).toBeInTheDocument(); }); + describe("stopping polling", () => { + const pollSignal = () => pollAiHint.mock.calls[0][1].signal; + + beforeEach(() => { + pollAiHint.mockReturnValue(new Promise(() => {})); + }); + + test("Aborts polling when the component unmounts", async () => { + const { unmount } = renderAiErrorMessage(); + await clickButtonAndWait(); + expect(pollSignal().aborted).toBe(false); + + unmount(); + + expect(pollSignal().aborted).toBe(true); + }); + + test("Aborts polling when a new error occurs", async () => { + const { rerender } = renderAiErrorMessage(); + await clickButtonAndWait(); + + rerender( + + + , + ); + + expect(pollSignal().aborted).toBe(true); + }); + }); + describe("hint requested event", () => { const handler = vi.fn(); const onHintRequested = (e) => handler(e.detail); @@ -292,14 +357,8 @@ describe("AiErrorMessage", () => { }); test.each([ - [ - "shown", - () => getAiErrorHint.mockResolvedValue({ data: { fem: "A hint" } }), - ], - [ - "failed", - () => getAiErrorHint.mockRejectedValue(new Error("Bad gateway")), - ], + ["shown", () => pollAiHint.mockResolvedValue("A hint")], + ["failed", () => pollAiHint.mockRejectedValue(new Error("Hint failed"))], ])("Dispatches the event with outcome %s", async (outcome, mockApi) => { mockApi(); const state = buildState(); @@ -319,7 +378,7 @@ describe("AiErrorMessage", () => { let settleRequest; beforeEach(() => { - getAiErrorHint.mockReturnValue( + pollAiHint.mockReturnValue( new Promise((resolve, reject) => { settleRequest = { resolve, reject }; }), @@ -327,8 +386,8 @@ describe("AiErrorMessage", () => { }); const settleWith = { - success: () => settleRequest.resolve({ data: { fem: "Stale hint" } }), - failure: () => settleRequest.reject(new Error("Bad gateway")), + success: () => settleRequest.resolve("Stale hint"), + failure: () => settleRequest.reject(new Error("Hint failed")), }; test.each(Object.keys(settleWith))( diff --git a/src/utils/apiCallHandler.js b/src/utils/apiCallHandler.js index c99c09bf2..e1bd91fb0 100644 --- a/src/utils/apiCallHandler.js +++ b/src/utils/apiCallHandler.js @@ -101,19 +101,6 @@ const ApiCallHandler = ({ reactAppApiEndpoint }) => { }); }; - const getAiErrorHint = async ( - { message, trace, runtime, code }, - accessToken, - ) => { - // Timeout is set longer than editor-api's 15 seconds - // so that the backend's 502 bad gateway arrives first. - return await post( - `${host}/api/friendly_error_messages`, - { message, trace, runtime, code }, - { headers: headers(accessToken), timeout: 20000 }, - ); - }; - const createAiHint = async ( { message, trace, runtime, code }, accessToken, @@ -159,7 +146,6 @@ const ApiCallHandler = ({ reactAppApiEndpoint }) => { readProject, loadAssets, createError, - getAiErrorHint, createAiHint, getAiHint, getUserSettings, diff --git a/src/utils/apiCallHandler.test.js b/src/utils/apiCallHandler.test.js index 9c7881320..31199d0de 100644 --- a/src/utils/apiCallHandler.test.js +++ b/src/utils/apiCallHandler.test.js @@ -16,7 +16,6 @@ const { loadAssets, createRemix, createError, - getAiErrorHint, createAiHint, getAiHint, getUserSettings, @@ -231,30 +230,6 @@ describe("Testing project errors API calls", () => { }); }); -describe("Testing AI error hint API calls", () => { - const errorDetails = { - message: "NameError: name 'prnt' is not defined on line 1 of main.py", - trace: "NameError: name 'prnt' is not defined on line 1 of main.py", - runtime: "skulpt", - code: 'prnt("Hello world")', - }; - - test("Posts error details with auth headers and a timeout", async () => { - axios.post.mockImplementationOnce(() => - Promise.resolve({ status: 200, data: { fem: "A friendly hint" } }), - ); - - const response = await getAiErrorHint(errorDetails, accessToken); - - expect(axios.post).toHaveBeenCalledWith( - `${host}/api/friendly_error_messages`, - errorDetails, - { ...authHeaders, timeout: 20000 }, - ); - expect(response.data.fem).toBe("A friendly hint"); - }); -}); - describe("Testing async AI hint API calls", () => { const errorDetails = { message: "NameError: name 'prnt' is not defined on line 1 of main.py", From bf661145f71c9622241f8cdbcffe27904bb00d6e Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 11:16:59 +0000 Subject: [PATCH 3/3] tidy tests --- src/utils/apiCallHandler.test.js | 11 +++-------- src/utils/pollAiHint.test.js | 11 ----------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/src/utils/apiCallHandler.test.js b/src/utils/apiCallHandler.test.js index 31199d0de..d44b9342d 100644 --- a/src/utils/apiCallHandler.test.js +++ b/src/utils/apiCallHandler.test.js @@ -239,19 +239,18 @@ describe("Testing async AI hint API calls", () => { }; const hintId = "6f1c1e2a-3b4d-4e5f-8a9b-0c1d2e3f4a5b"; - test("Creating a hint posts error details and returns the id", async () => { + test("Creating a hint posts error details", async () => { axios.post.mockImplementationOnce(() => Promise.resolve({ status: 202, data: { id: hintId } }), ); - const response = await createAiHint(errorDetails, accessToken); + await createAiHint(errorDetails, accessToken); expect(axios.post).toHaveBeenCalledWith( `${host}/api/ai_hints`, errorDetails, { ...authHeaders, timeout: 5000 }, ); - expect(response.data.id).toBe(hintId); }); test("Getting a hint fetches it by id with the abort signal", async () => { @@ -263,17 +262,13 @@ describe("Testing async AI hint API calls", () => { }), ); - const response = await getAiHint(hintId, accessToken, { signal }); + await getAiHint(hintId, accessToken, { signal }); expect(axios.get).toHaveBeenCalledWith(`${host}/api/ai_hints/${hintId}`, { ...authHeaders, timeout: 5000, signal, }); - expect(response.data).toEqual({ - status: "completed", - hint: "A friendly hint", - }); }); }); diff --git a/src/utils/pollAiHint.test.js b/src/utils/pollAiHint.test.js index d7863f614..bebf3fa19 100644 --- a/src/utils/pollAiHint.test.js +++ b/src/utils/pollAiHint.test.js @@ -154,14 +154,3 @@ test("rejects as aborted when aborted during a request", async () => { await expectRejection(promise, "aborted"); expect(getAiHint).toHaveBeenCalledTimes(1); }); - -test("does not poll when already aborted", async () => { - const controller = new AbortController(); - controller.abort(); - const promise = startPolling(controller.signal); - - await vi.advanceTimersByTimeAsync(intervalMs); - - await expectRejection(promise, "aborted"); - expect(getAiHint).not.toHaveBeenCalled(); -});