Skip to content

Commit 57307f6

Browse files
myk1ytedelauna
andauthored
perf(webview): replace axios in key-info hooks with fetch (#2261)
* perf(webview): replace axios in key-info hooks with fetch What: useOpenRouterKeyInfo, useRequestyKeyInfo and useOpenRouterModelProviders now call global fetch instead of axios.get, and axios is removed from webview-ui/package.json plus the webview importer block in pnpm-lock.yaml. Why: these three hooks were the only axios consumers in the webview bundle. axios shipped ~50 kB of entry-chunk code for three plain GET requests with no interceptors, no timeout config and no axios-specific error handling anywhere in the webview. Dropping it removes that weight from every webview load. Impact: entry chunk 6,183,743 B -> 6,133,127 B (-50,616 B, -0.82%). axios no longer appears in the entry bundle at all. Behavior is preserved by construction: characterization tests pin URL, method, headers, response shaping and the non-2xx throw decision, and the same 19 assertions pass unchanged against both the axios and the fetch implementation. src/ keeps its axios dependency; 14 production files there still import it. * lint(webview): forbid re-importing axios in webview sources What: webview-ui/eslint.config.mjs gains a no-restricted-imports block scoped to src/**/*.{ts,tsx} that rejects `axios` with a message explaining the scoped dependency drop. Why: axios was removed from webview-ui/package.json, but pnpm's hoisted store still resolves it, so a new `import axios from "axios"` would silently reintroduce the dependency instead of failing loudly. The guard turns the "axios removed" claim from incidental into enforced. Impact: no runtime change. A webview file importing axios now fails lint with exit 1. src/ is unaffected and keeps its axios dependency. * test(webview): pin the unparseable-2xx-body path in the key-info hooks What: one new case per hook covering a 2xx response whose body is not valid JSON, so response.json() rejects inside the try block. Each asserts the same log call and fallback value as the existing blanket-catch cases. Why: the fetch swap moved body parsing inside the try, so a malformed 2xx body now flows through the catch instead of axios' parse step. That path was uncovered. The transport seam gained an optional jsonRejects field so json() can reject while ok stays true. Impact: no production change. Verified fail-on-shape: with the hook's catch changed to rethrow, the new case fails at isSuccess, so it pins the swallow rather than merely exercising the line. * test(webview): assert the diagnostic in key-info hook error matchers What: the non-2xx cases now match the logged Error's message exactly ("Request failed with status code 401/403/500") instead of expect.anything(). The schema-validation cases now match the logged ZodError's issues array and a real issue path instead of expect.anything(). Why: expect.anything() accepts any value, including an Error with an empty message, so a regression that dropped the HTTP status from the thrown message would still pass. The same looseness applied to the validation-failure logs, which is the adjacent instance of the pattern. Impact: no production change. Verified the tightened matchers bite by temporarily degrading each hook (message without status, validation log replaced by a generic Error): in both cases exactly the targeted test fails. * test(webview): strengthen fetch hook coverage and lint guardrails --------- Co-authored-by: Elliott de Launay <[email protected]>
1 parent c6d5360 commit 57307f6

10 files changed

Lines changed: 479 additions & 30 deletions

‎pnpm-lock.yaml‎

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/eslint.config.mjs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,23 @@ export default [
4040
"no-case-declarations": "off",
4141
},
4242
},
43+
{
44+
files: ["src/**/*.{ts,tsx}"],
45+
rules: {
46+
"no-restricted-imports": [
47+
"error",
48+
{
49+
paths: [
50+
{
51+
name: "axios",
52+
message:
53+
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
54+
},
55+
],
56+
},
57+
],
58+
},
59+
},
4360
{
4461
files: ["src/__mocks__/**/*.js"],
4562
rules: {
@@ -63,6 +80,11 @@ export default [
6380
"error",
6481
{
6582
paths: [
83+
{
84+
name: "axios",
85+
message:
86+
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
87+
},
6688
{
6789
name: "@tanstack/react-query",
6890
importNames: ["QueryClientProvider"],

‎webview-ui/package.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
"@vscode/codicons": "^0.0.45",
3939
"@vscode/webview-ui-toolkit": "^1.4.0",
4040
"ansi-to-html": "^0.7.2",
41-
"axios": "^1.18.1",
4241
"class-variance-authority": "^0.7.1",
4342
"clsx": "^2.1.1",
4443
"cmdk": "^1.0.0",
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { renderHook, waitFor } from "@testing-library/react"
2+
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
3+
import React from "react"
4+
5+
import { stubTransport } from "@src/utils/test-utils"
6+
7+
import { useOpenRouterKeyInfo } from "../useOpenRouterKeyInfo"
8+
9+
const KEY_INFO = {
10+
label: "sk-or-v1-...abc",
11+
usage: 12.5,
12+
is_free_tier: false,
13+
is_provisioning_key: false,
14+
rate_limit: { requests: 60, interval: "1m" },
15+
limit: 100,
16+
}
17+
18+
const wrapper = ({ children }: React.PropsWithChildren) => (
19+
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
20+
{children}
21+
</QueryClientProvider>
22+
)
23+
24+
describe("useOpenRouterKeyInfo", () => {
25+
afterEach(() => {
26+
vi.restoreAllMocks()
27+
})
28+
29+
it("returns undefined and issues no request when apiKey is missing", async () => {
30+
const { calls } = stubTransport(() => ({ status: 200, body: { data: KEY_INFO } }))
31+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
32+
33+
const { result } = renderHook(() => useOpenRouterKeyInfo(undefined), { wrapper })
34+
35+
await waitFor(() => expect(result.current.fetchStatus).toBe("idle"))
36+
expect(result.current.data).toBeUndefined()
37+
expect(calls).toHaveLength(0)
38+
expect(consoleError).not.toHaveBeenCalled()
39+
})
40+
41+
it("requests the default key endpoint with a bearer token and returns the parsed key info", async () => {
42+
const { calls } = stubTransport(() => ({ status: 200, body: { data: KEY_INFO } }))
43+
44+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test"), { wrapper })
45+
46+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
47+
expect(result.current.data).toEqual(KEY_INFO)
48+
expect(calls).toEqual([
49+
{
50+
url: "https://openrouter.ai/api/v1/key",
51+
method: "GET",
52+
headers: { authorization: "Bearer sk-or-v1-test" },
53+
},
54+
])
55+
})
56+
57+
it("uses a caller-supplied baseUrl verbatim", async () => {
58+
const { calls } = stubTransport(() => ({ status: 200, body: { data: KEY_INFO } }))
59+
60+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test", "https://proxy.example.com/api/v1"), {
61+
wrapper,
62+
})
63+
64+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
65+
expect(calls[0].url).toBe("https://proxy.example.com/api/v1/key")
66+
})
67+
68+
it("returns null and logs a validation failure when the payload does not match the schema", async () => {
69+
stubTransport(() => ({ status: 200, body: { data: { label: "only-label" } } }))
70+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
71+
72+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test"), { wrapper })
73+
74+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
75+
expect(result.current.data).toBeNull()
76+
expect(consoleError).toHaveBeenCalledWith(
77+
"OpenRouter API key info validation failed:",
78+
expect.objectContaining({
79+
issues: expect.arrayContaining([expect.objectContaining({ path: ["data", "usage"] })]),
80+
}),
81+
)
82+
})
83+
84+
it("returns null and logs a fetch failure when the response is not 2xx", async () => {
85+
stubTransport(() => ({ status: 401, body: { error: { message: "No auth credentials found" } } }))
86+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
87+
88+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test"), { wrapper })
89+
90+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
91+
expect(result.current.data).toBeNull()
92+
expect(consoleError).toHaveBeenCalledWith(
93+
"Error fetching OpenRouter key info:",
94+
expect.objectContaining({ message: "Request failed with status code 401" }),
95+
)
96+
})
97+
98+
it("returns null and logs a fetch failure when the request rejects", async () => {
99+
const failure = new Error("network down")
100+
stubTransport(() => {
101+
throw failure
102+
})
103+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
104+
105+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test"), { wrapper })
106+
107+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
108+
expect(result.current.data).toBeNull()
109+
expect(consoleError).toHaveBeenCalledWith("Error fetching OpenRouter key info:", failure)
110+
})
111+
112+
it("returns null and logs a fetch failure when a 2xx body is not valid JSON", async () => {
113+
const parseFailure = new SyntaxError("Unexpected token '<', \"<html>\" is not valid JSON")
114+
stubTransport(() => ({ status: 200, body: undefined, jsonRejects: parseFailure }))
115+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
116+
117+
const { result } = renderHook(() => useOpenRouterKeyInfo("sk-or-v1-test"), { wrapper })
118+
119+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
120+
expect(result.current.data).toBeNull()
121+
expect(consoleError).toHaveBeenCalledWith("Error fetching OpenRouter key info:", parseFailure)
122+
})
123+
})
Lines changed: 157 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,39 @@
1-
import React from "react"
2-
import axios from "axios"
3-
import { QueryClientProvider } from "@tanstack/react-query"
41
import { renderHook, waitFor } from "@testing-library/react"
5-
import { z } from "zod"
2+
import { QueryClientProvider } from "@tanstack/react-query"
3+
import React from "react"
64

7-
import { createTestQueryClient } from "@src/utils/test-utils"
5+
import { createTestQueryClient, stubTransport } from "@src/utils/test-utils"
86

97
import { useOpenRouterModelProviders } from "../useOpenRouterModelProviders"
108

11-
vi.mock("axios")
9+
const endpointsPayload = (overrides: Record<string, unknown> = {}) => ({
10+
data: {
11+
id: "vendor/model",
12+
name: "Vendor Model",
13+
description: "A test model",
14+
architecture: { input_modalities: ["text", "image"], output_modalities: ["text"] },
15+
endpoints: [
16+
{
17+
name: "Provider A",
18+
tag: "provider-a",
19+
context_length: 128000,
20+
max_completion_tokens: 4096,
21+
pricing: {
22+
prompt: "0.000003",
23+
completion: "0.000015",
24+
input_cache_read: "0.0000003",
25+
input_cache_write: "0.0000036",
26+
},
27+
},
28+
{
29+
name: "Provider B",
30+
context_length: 32000,
31+
pricing: { prompt: "0.000001", completion: "0.000002" },
32+
},
33+
],
34+
...overrides,
35+
},
36+
})
1237

1338
const wrapper = ({ children }: React.PropsWithChildren) => (
1439
<QueryClientProvider client={createTestQueryClient()}>{children}</QueryClientProvider>
@@ -19,21 +44,129 @@ describe("useOpenRouterModelProviders", () => {
1944
vi.restoreAllMocks()
2045
})
2146

22-
it("logs the zod issues and returns no providers when validation throws", async () => {
23-
const zodError = new z.ZodError([{ code: "custom", path: ["data"], message: "bad data" }])
24-
vi.mocked(axios.get).mockRejectedValue(zodError)
47+
it("returns an empty record without a request when modelId is missing", async () => {
48+
const { calls } = stubTransport(() => ({ status: 200, body: endpointsPayload() }))
49+
50+
const { result } = renderHook(() => useOpenRouterModelProviders(undefined), { wrapper })
51+
52+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
53+
expect(result.current.data).toEqual({})
54+
expect(calls).toHaveLength(0)
55+
})
56+
57+
it("requests the endpoints URL and maps each endpoint to provider model info", async () => {
58+
const { calls } = stubTransport(() => ({ status: 200, body: endpointsPayload() }))
59+
60+
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
61+
62+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
63+
64+
expect(calls).toEqual([
65+
{ url: "https://openrouter.ai/api/v1/models/vendor/model/endpoints", method: "GET", headers: {} },
66+
])
67+
68+
expect(result.current.data).toEqual({
69+
"provider-a": {
70+
maxTokens: 4096,
71+
contextWindow: 128000,
72+
supportsImages: true,
73+
supportsPromptCache: true,
74+
cacheReadsPrice: 0.3,
75+
cacheWritesPrice: expect.closeTo(3.6, 10),
76+
inputPrice: 3,
77+
outputPrice: 15,
78+
description: "A test model",
79+
label: "provider-a",
80+
},
81+
"Provider B": {
82+
maxTokens: 32000,
83+
contextWindow: 32000,
84+
supportsImages: true,
85+
supportsPromptCache: false,
86+
cacheReadsPrice: undefined,
87+
cacheWritesPrice: undefined,
88+
inputPrice: 1,
89+
outputPrice: 2,
90+
description: "A test model",
91+
label: "Provider B",
92+
},
93+
})
94+
})
95+
96+
it.each([
97+
{ name: "text-only architecture", architecture: { input_modalities: ["text"], output_modalities: ["text"] } },
98+
{ name: "omitted architecture", architecture: undefined },
99+
])("disables image support for $name", async ({ architecture }) => {
100+
stubTransport(() => ({ status: 200, body: endpointsPayload({ architecture }) }))
101+
102+
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
103+
104+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
105+
expect(result.current.data).toMatchObject({
106+
"provider-a": { supportsImages: false },
107+
"Provider B": { supportsImages: false },
108+
})
109+
})
110+
111+
it("uses a caller-supplied baseUrl", async () => {
112+
const { calls } = stubTransport(() => ({ status: 200, body: endpointsPayload() }))
113+
114+
const { result } = renderHook(
115+
() => useOpenRouterModelProviders("vendor/model", "https://proxy.example.com/api/v1"),
116+
{ wrapper },
117+
)
118+
119+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
120+
expect(calls[0].url).toBe("https://proxy.example.com/api/v1/models/vendor/model/endpoints")
121+
})
122+
123+
it("returns no providers for image-generation models", async () => {
124+
stubTransport(() => ({
125+
status: 200,
126+
body: endpointsPayload({ architecture: { input_modalities: ["text"], output_modalities: ["image"] } }),
127+
}))
128+
129+
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
130+
131+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
132+
expect(result.current.data).toEqual({})
133+
})
134+
135+
it("logs a validation failure and returns no providers when the payload does not match the schema", async () => {
136+
stubTransport(() => ({ status: 200, body: { data: { id: "vendor/model" } } }))
137+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
138+
139+
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
140+
141+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
142+
expect(result.current.data).toEqual({})
143+
expect(consoleError).toHaveBeenCalledWith(
144+
"OpenRouter API response validation failed:",
145+
expect.objectContaining({
146+
issues: expect.arrayContaining([expect.objectContaining({ path: ["data", "endpoints"] })]),
147+
}),
148+
)
149+
})
150+
151+
it("logs a fetch failure and returns no providers when the response is not 2xx", async () => {
152+
stubTransport(() => ({ status: 500, body: { error: "boom" } }))
25153
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
26154

27155
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
28156

29157
await waitFor(() => expect(result.current.isSuccess).toBe(true))
30158
expect(result.current.data).toEqual({})
31-
expect(consoleError).toHaveBeenCalledWith("OpenRouter API response validation failed:", zodError.issues)
159+
expect(consoleError).toHaveBeenCalledWith(
160+
"Error fetching OpenRouter providers:",
161+
expect.objectContaining({ message: "Request failed with status code 500" }),
162+
)
32163
})
33164

34-
it("logs other errors and returns no providers", async () => {
165+
it("logs a fetch failure and returns no providers when the request rejects", async () => {
35166
const failure = new Error("network down")
36-
vi.mocked(axios.get).mockRejectedValue(failure)
167+
stubTransport(() => {
168+
throw failure
169+
})
37170
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
38171

39172
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
@@ -42,4 +175,16 @@ describe("useOpenRouterModelProviders", () => {
42175
expect(result.current.data).toEqual({})
43176
expect(consoleError).toHaveBeenCalledWith("Error fetching OpenRouter providers:", failure)
44177
})
178+
179+
it("logs a fetch failure and returns no providers when a 2xx body is not valid JSON", async () => {
180+
const parseFailure = new SyntaxError("Unexpected token '<', \"<html>\" is not valid JSON")
181+
stubTransport(() => ({ status: 200, body: undefined, jsonRejects: parseFailure }))
182+
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
183+
184+
const { result } = renderHook(() => useOpenRouterModelProviders("vendor/model"), { wrapper })
185+
186+
await waitFor(() => expect(result.current.isSuccess).toBe(true))
187+
expect(result.current.data).toEqual({})
188+
expect(consoleError).toHaveBeenCalledWith("Error fetching OpenRouter providers:", parseFailure)
189+
})
45190
})

0 commit comments

Comments
 (0)