diff --git a/src/features/http-client/HttpClientView.tsx b/src/features/http-client/HttpClientView.tsx index 7e811e46b..e6a97a99f 100644 --- a/src/features/http-client/HttpClientView.tsx +++ b/src/features/http-client/HttpClientView.tsx @@ -265,7 +265,7 @@ function HeaderTable({ headers }: { headers: Array<[string, string]> }) { export function HttpClientView() { const history = useHttpClient((s) => s.history); const selected = useHttpClient((s) => s.selected); - const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined)); + const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected)); const running = useHttpClient((s) => s.running); useEffect(() => { void refreshHistory(); diff --git a/src/features/http-client/responseFind.test.tsx b/src/features/http-client/responseFind.test.tsx index fc45a32e1..d22111182 100644 --- a/src/features/http-client/responseFind.test.tsx +++ b/src/features/http-client/responseFind.test.tsx @@ -39,11 +39,11 @@ const exchange: HttpExchange = { }; describe("HTTP response find", () => { - afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null })); + afterEach(() => useHttpClient.setState({ history: [], exchanges: [], selected: null })); it("opens a find bar with ⌘F in the response and marks the matches", () => { Element.prototype.scrollIntoView ??= () => {}; - useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" }); + useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" }); render(); const body = screen.getByLabelText("Response body"); fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true }); diff --git a/src/features/http-client/store.test.ts b/src/features/http-client/store.test.ts index aaedff599..e4153357c 100644 --- a/src/features/http-client/store.test.ts +++ b/src/features/http-client/store.test.ts @@ -1,10 +1,11 @@ import { beforeEach, expect, it, vi } from "vitest"; import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc"; -import { runAll, runRequest, setEnvironment, useHttpClient } from "./store"; +import { runAll, runRequest, selectEntry, setEnvironment, useHttpClient } from "./store"; const backend = vi.hoisted(() => ({ httpEnvironments: vi.fn(), httpExecute: vi.fn(), + httpHistoryGet: vi.fn(), httpRequests: vi.fn(), })); vi.mock("@/platform/ipc", async (importOriginal) => { @@ -95,3 +96,40 @@ it.each(["A", "missing"])("validates the starting choice %s once when environmen expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment); expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment); }); + +function response(id: string): HttpExchange { + return { ...exchange, entry: { ...exchange.entry, id } }; +} + +it("keeps 100 history rows and the four most recently used exchanges", async () => { + for (let n = 0; n < 101; n++) { + backend.httpExecute.mockResolvedValueOnce(ok(response(String(n)))); + await runRequest(null, text, 0); + } + const state = useHttpClient.getState(); + expect(state.history).toHaveLength(100); + expect(state.history.at(-1)?.id).toBe("1"); + expect(state.exchanges).toHaveLength(4); + + await selectEntry("97"); // Touch the oldest resident before opening a cold row. + backend.httpHistoryGet.mockResolvedValueOnce(ok(response("1"))); + await selectEntry("1"); + await selectEntry("97"); + expect(backend.httpHistoryGet.mock.calls).toEqual([["1"]]); + expect(useHttpClient.getState().exchanges.map((e) => e.entry.id)).toEqual(["97", "1", "100", "99"]); +}); + +it("keeps the latest selection when two cold reads finish out of order", async () => { + let finishFirst!: (result: ReturnType>) => void; + const first = new Promise>>((resolve) => { + finishFirst = resolve; + }); + backend.httpHistoryGet.mockReturnValueOnce(first).mockResolvedValueOnce(ok(response("b"))); + const pending = selectEntry("a"); + await selectEntry("b"); + finishFirst(ok(response("a"))); + await pending; + const { selected, exchanges } = useHttpClient.getState(); + expect(selected).toBe("b"); + expect(exchanges).toEqual([response("b")]); +}); diff --git a/src/features/http-client/store.ts b/src/features/http-client/store.ts index 57576bba0..38b456e5f 100644 --- a/src/features/http-client/store.ts +++ b/src/features/http-client/store.ts @@ -14,6 +14,9 @@ import { writeClipboardText } from "@/platform/clipboard"; import { editorService, notifications, showServiceView, showStatusInfo } from "@/workbench/contributions"; export const SERVICE_VIEW = "httpClient"; +// Same bound as ide_http::history::MAX_ENTRIES. Only recent rows keep their bodies in the UI. +const HISTORY_LIMIT = 100; +const EXCHANGE_LIMIT = 4; const ENV_KEY = "openidea.httpClient.environments"; function readEnvChoices(): Record { @@ -41,8 +44,8 @@ interface HttpClientState { environments: Record; /** History entries, newest first (this session's runs included). */ history: HttpHistoryEntry[]; - /** Loaded exchanges by entry id. */ - exchanges: Record; + /** Loaded exchanges, most recently viewed first. */ + exchanges: HttpExchange[]; selected: string | null; running: Running | null; } @@ -51,7 +54,7 @@ export const useHttpClient = create(() => ({ envByFile: readEnvChoices(), environments: {}, history: [], - exchanges: {}, + exchanges: [], selected: null, running: null, })); @@ -96,6 +99,10 @@ function effectiveEnvironment(path: string | null, selection?: string | null): s return null; } +function rememberExchange(exchange: HttpExchange, recent: HttpExchange[]) { + return [exchange, ...recent.filter((e) => e.entry.id !== exchange.entry.id)].slice(0, EXCHANGE_LIMIT); +} + export async function refreshHistory() { try { const history = await call(commands.httpHistory()); @@ -106,12 +113,18 @@ export async function refreshHistory() { } export async function selectEntry(id: string) { + const { exchanges } = useHttpClient.getState(); + const cached = exchanges.find((e) => e.entry.id === id); + if (cached) { + useHttpClient.setState({ selected: id, exchanges: rememberExchange(cached, exchanges) }); + return; + } useHttpClient.setState({ selected: id }); - if (useHttpClient.getState().exchanges[id]) return; try { const ex = await call(commands.httpHistoryGet(id)); - useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } })); + useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s)); } catch (e) { + if (useHttpClient.getState().selected !== id) return; notifications().notify({ level: "error", title: "Cannot open the response", @@ -122,7 +135,7 @@ export async function selectEntry(id: string) { export async function clearHistory() { await call(commands.httpHistoryClear()); - useHttpClient.setState({ history: [], exchanges: {}, selected: null }); + useHttpClient.setState({ history: [], exchanges: [], selected: null }); } export function parseRequests(text: string): Promise { @@ -159,8 +172,8 @@ export async function runRequest( const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment; const ex = await call(commands.httpExecute(request, path, text, index, env)); useHttpClient.setState((s) => ({ - history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)], - exchanges: { ...s.exchanges, [ex.entry.id]: ex }, + history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT), + exchanges: rememberExchange(ex, s.exchanges), selected: ex.entry.id, })); return true; @@ -235,5 +248,5 @@ export function cancelRunning() { /** The window switched projects: history, responses and environments belong to the previous one. */ export function resetHttpClient() { cancelRunning(); - useHttpClient.setState({ environments: {}, history: [], exchanges: {}, selected: null, running: null }); + useHttpClient.setState({ environments: {}, history: [], exchanges: [], selected: null, running: null }); }