Skip to content

Commit 2a2e4f3

Browse files
committed
no-mistakes: apply CI fixes
1 parent 82c34c9 commit 2a2e4f3

6 files changed

Lines changed: 689 additions & 9 deletions

File tree

Lines changed: 161 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,39 @@
11
import { buildApiHandler } from "../../index"
22
import { KimiCodeHandler } from "../kimi-code"
3+
import type { Mock } from "vitest"
34

4-
vi.mock("../../../integrations/kimi-code/oauth", () => ({
5-
kimiCodeOAuthManager: {
6-
getAccessToken: vi.fn().mockResolvedValue("oauth-token"),
7-
forceRefreshAccessToken: vi.fn().mockResolvedValue("refreshed-token"),
8-
},
9-
}))
5+
vi.mock("../../../integrations/kimi-code/oauth", () => {
6+
const mockGetAccessToken = vi.fn().mockResolvedValue("oauth-token")
7+
const mockForceRefreshAccessToken = vi.fn().mockResolvedValue("refreshed-token")
8+
return {
9+
kimiCodeOAuthManager: {
10+
getAccessToken: mockGetAccessToken,
11+
forceRefreshAccessToken: mockForceRefreshAccessToken,
12+
},
13+
mockGetAccessToken,
14+
mockForceRefreshAccessToken,
15+
}
16+
})
17+
18+
vi.mock("../fetchers/modelCache", () => {
19+
const mockGetModels = vi.fn().mockRejectedValue(new Error("offline"))
20+
return {
21+
getModels: mockGetModels,
22+
mockGetModels,
23+
}
24+
})
1025

11-
vi.mock("../fetchers/modelCache", () => ({
12-
getModels: vi.fn().mockRejectedValue(new Error("offline")),
13-
}))
26+
const { mockGetAccessToken, mockForceRefreshAccessToken } = await import("../../../integrations/kimi-code/oauth")
27+
const { mockGetModels } = await import("../fetchers/modelCache")
1428

1529
describe("KimiCodeHandler", () => {
30+
beforeEach(() => {
31+
vi.clearAllMocks()
32+
;(mockGetAccessToken as any).mockResolvedValue("oauth-token")
33+
;(mockForceRefreshAccessToken as any).mockResolvedValue("refreshed-token")
34+
;(mockGetModels as any).mockRejectedValue(new Error("offline"))
35+
})
36+
1637
it("is dispatched separately from Moonshot and preserves an unknown selected model", () => {
1738
const handler = buildApiHandler({
1839
apiProvider: "kimi-code",
@@ -28,4 +49,135 @@ describe("KimiCodeHandler", () => {
2849
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "kimi-key" })
2950
expect(handler.getModel().id).toBe("kimi-for-coding")
3051
})
52+
53+
it("uses API key when auth method is api-key", async () => {
54+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "my-api-key" })
55+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
56+
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
57+
new Response(JSON.stringify({ choices: [{ message: { content: "response" }, finish_reason: "stop" }] }), {
58+
status: 200,
59+
}),
60+
)
61+
try {
62+
for await (const chunk of gen) {
63+
// consume
64+
}
65+
} catch {
66+
// expected - mock is incomplete
67+
}
68+
expect(mockGetAccessToken as any).not.toHaveBeenCalled()
69+
})
70+
71+
it("uses OAuth token when auth method is oauth or not specified", async () => {
72+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" })
73+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
74+
try {
75+
for await (const chunk of gen) {
76+
// consume
77+
}
78+
} catch {
79+
// expected - mock will fail
80+
}
81+
expect(mockGetAccessToken as any).toHaveBeenCalled()
82+
})
83+
84+
it("throws error when OAuth is required but no token available", async () => {
85+
;(mockGetAccessToken as any).mockResolvedValueOnce(null)
86+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" })
87+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
88+
await expect(async () => {
89+
for await (const chunk of gen) {
90+
// consume
91+
}
92+
}).rejects.toThrow("Not authenticated with Kimi Code")
93+
})
94+
95+
it("throws error when API key auth is missing the key", async () => {
96+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key" })
97+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
98+
await expect(async () => {
99+
for await (const chunk of gen) {
100+
// consume
101+
}
102+
}).rejects.toThrow("Kimi Code API key is required")
103+
})
104+
105+
it("retries with forced refresh on 401 when using OAuth", async () => {
106+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" })
107+
const fetchSpy = vi.spyOn(globalThis, "fetch")
108+
fetchSpy.mockResolvedValueOnce(
109+
new Response(null, { status: 401 }),
110+
)
111+
fetchSpy.mockResolvedValueOnce(
112+
new Response(JSON.stringify({ choices: [{ message: { content: "ok" }, finish_reason: "stop" }] }), {
113+
status: 200,
114+
}),
115+
)
116+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
117+
try {
118+
for await (const chunk of gen) {
119+
// consume
120+
}
121+
} catch {
122+
// expected - mock is incomplete
123+
}
124+
expect(mockForceRefreshAccessToken as any).toHaveBeenCalled()
125+
})
126+
127+
it("does not retry on 401 when using API key auth", async () => {
128+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
129+
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
130+
new Response(null, { status: 401 }),
131+
)
132+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
133+
await expect(async () => {
134+
for await (const chunk of gen) {
135+
// consume
136+
}
137+
}).rejects.toThrow()
138+
expect(mockForceRefreshAccessToken as any).not.toHaveBeenCalled()
139+
})
140+
141+
it("fetches models during prepareRequest", async () => {
142+
;(mockGetModels as any).mockResolvedValueOnce({ "test-model": { maxTokens: 1000 } })
143+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
144+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
145+
try {
146+
for await (const chunk of gen) {
147+
// consume
148+
}
149+
} catch {
150+
// expected
151+
}
152+
expect(mockGetModels as any).toHaveBeenCalled()
153+
})
154+
155+
it("continues when model discovery fails", async () => {
156+
;(mockGetModels as any).mockRejectedValueOnce(new Error("discovery failed"))
157+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
158+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
159+
try {
160+
for await (const chunk of gen) {
161+
// consume
162+
}
163+
} catch {
164+
// expected - different error
165+
}
166+
expect(mockGetModels as any).toHaveBeenCalled()
167+
})
168+
169+
it("uses discovered model info when available", async () => {
170+
;(mockGetModels as any).mockResolvedValueOnce({ "kimi-for-coding": { maxTokens: 8000, contextWindow: 128000 } })
171+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
172+
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
173+
try {
174+
for await (const chunk of gen) {
175+
// consume
176+
}
177+
} catch {
178+
// expected
179+
}
180+
const model = handler.getModel()
181+
expect(model.info.maxTokens).toBe(8000)
182+
})
31183
})

‎src/api/providers/fetchers/__tests__/kimi-code.spec.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,48 @@ describe("Kimi Code model discovery", () => {
3333
expect.objectContaining({ headers: expect.objectContaining({ Authorization: "Bearer secret-token" }) }),
3434
)
3535
})
36+
37+
it("applies default values when optional fields are missing", () => {
38+
const mapped = mapKimiCodeModel({
39+
id: "basic-model",
40+
})
41+
expect(mapped.supportsReasoningBinary).toBe(false)
42+
expect(mapped.supportsImages).toBe(false)
43+
expect(mapped.contextWindow).toBeGreaterThan(0)
44+
})
45+
46+
it("throws error when apiKey is missing", async () => {
47+
await expect(getKimiCodeModels()).rejects.toThrow("Kimi Code authentication is required")
48+
})
49+
50+
it("throws error with status code on failed request", async () => {
51+
vi.spyOn(globalThis, "fetch").mockResolvedValue(
52+
new Response("Unauthorized", { status: 401, statusText: "Unauthorized" }),
53+
)
54+
try {
55+
await getKimiCodeModels("bad-token")
56+
expect.fail("should have thrown")
57+
} catch (error: any) {
58+
expect(error.message).toContain("401")
59+
expect(error.status).toBe(401)
60+
}
61+
})
62+
63+
it("returns multiple models as a record", async () => {
64+
vi.spyOn(globalThis, "fetch").mockResolvedValue(
65+
new Response(
66+
JSON.stringify({
67+
data: [
68+
{ id: "model-a", context_length: 100000 },
69+
{ id: "model-b", context_length: 200000, supports_reasoning: true },
70+
],
71+
}),
72+
{ status: 200 },
73+
),
74+
)
75+
const models = await getKimiCodeModels("token")
76+
expect(Object.keys(models)).toHaveLength(2)
77+
expect(models["model-a"].contextWindow).toBe(100000)
78+
expect(models["model-b"].supportsReasoningBinary).toBe(true)
79+
})
3680
})

‎src/core/webview/__tests__/webviewMessageHandler.spec.ts‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,3 +1470,148 @@ describe("zooCodeSignOut", () => {
14701470
)
14711471
})
14721472
})
1473+
1474+
describe("webviewMessageHandler - kimiCodeSignIn", () => {
1475+
beforeEach(() => {
1476+
vi.clearAllMocks()
1477+
})
1478+
1479+
it("starts OAuth authorization and opens browser", async () => {
1480+
const mockStartAuthorization = vi.fn().mockResolvedValue({
1481+
userCode: "TEST-CODE",
1482+
verificationUri: "https://auth.kimi.com/device",
1483+
expiresAt: Date.now() + 600000,
1484+
})
1485+
const mockWaitForAuthorization = vi.fn().mockResolvedValue({
1486+
type: "kimi-code",
1487+
accessToken: "token",
1488+
refreshToken: "refresh",
1489+
expiresAt: Date.now() + 3600000,
1490+
})
1491+
1492+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1493+
kimiCodeOAuthManager: {
1494+
startAuthorization: mockStartAuthorization,
1495+
waitForAuthorization: mockWaitForAuthorization,
1496+
},
1497+
}))
1498+
1499+
const mockOpenExternal = vi.fn().mockResolvedValue(true)
1500+
;(vscode as any).env = { openExternal: mockOpenExternal }
1501+
;(vscode as any).Uri = { parse: vi.fn((url: string) => url) }
1502+
1503+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" })
1504+
1505+
expect(mockStartAuthorization).toHaveBeenCalled()
1506+
expect(mockOpenExternal).toHaveBeenCalled()
1507+
expect(mockClineProvider.postStateToWebview).toHaveBeenCalled()
1508+
})
1509+
1510+
it("shows success message after successful authorization", async () => {
1511+
const mockStartAuthorization = vi.fn().mockResolvedValue({
1512+
userCode: "TEST-CODE",
1513+
verificationUri: "https://auth.kimi.com/device",
1514+
expiresAt: Date.now() + 600000,
1515+
})
1516+
const mockWaitForAuthorization = vi.fn().mockResolvedValue({
1517+
type: "kimi-code",
1518+
accessToken: "token",
1519+
refreshToken: "refresh",
1520+
expiresAt: Date.now() + 3600000,
1521+
})
1522+
1523+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1524+
kimiCodeOAuthManager: {
1525+
startAuthorization: mockStartAuthorization,
1526+
waitForAuthorization: mockWaitForAuthorization,
1527+
},
1528+
}))
1529+
1530+
const mockOpenExternal = vi.fn().mockResolvedValue(true)
1531+
;(vscode as any).env = { openExternal: mockOpenExternal }
1532+
;(vscode as any).Uri = { parse: vi.fn((url: string) => url) }
1533+
1534+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" })
1535+
await new Promise((resolve) => setTimeout(resolve, 10))
1536+
1537+
expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("Successfully signed in to Kimi Code")
1538+
})
1539+
1540+
it("handles authorization failure", async () => {
1541+
const mockStartAuthorization = vi.fn().mockResolvedValue({
1542+
userCode: "TEST-CODE",
1543+
verificationUri: "https://auth.kimi.com/device",
1544+
expiresAt: Date.now() + 600000,
1545+
})
1546+
const mockWaitForAuthorization = vi.fn().mockRejectedValue(new Error("Authorization cancelled"))
1547+
1548+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1549+
kimiCodeOAuthManager: {
1550+
startAuthorization: mockStartAuthorization,
1551+
waitForAuthorization: mockWaitForAuthorization,
1552+
},
1553+
}))
1554+
1555+
const mockOpenExternal = vi.fn().mockResolvedValue(true)
1556+
;(vscode as any).env = { openExternal: mockOpenExternal }
1557+
;(vscode as any).Uri = { parse: vi.fn((url: string) => url) }
1558+
1559+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" })
1560+
await new Promise((resolve) => setTimeout(resolve, 10))
1561+
1562+
expect(mockClineProvider.postStateToWebview).toHaveBeenCalled()
1563+
})
1564+
1565+
it("handles startAuthorization error", async () => {
1566+
const mockStartAuthorization = vi.fn().mockRejectedValue(new Error("Network error"))
1567+
1568+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1569+
kimiCodeOAuthManager: {
1570+
startAuthorization: mockStartAuthorization,
1571+
},
1572+
}))
1573+
1574+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignIn" })
1575+
1576+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
1577+
expect.stringContaining("Kimi Code sign in failed"),
1578+
)
1579+
expect(mockClineProvider.postStateToWebview).toHaveBeenCalled()
1580+
})
1581+
})
1582+
1583+
describe("webviewMessageHandler - kimiCodeSignOut", () => {
1584+
beforeEach(() => {
1585+
vi.clearAllMocks()
1586+
})
1587+
1588+
it("clears credentials and shows success message", async () => {
1589+
const mockClearCredentials = vi.fn().mockResolvedValue(undefined)
1590+
1591+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1592+
kimiCodeOAuthManager: {
1593+
clearCredentials: mockClearCredentials,
1594+
},
1595+
}))
1596+
1597+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignOut" })
1598+
1599+
expect(mockClearCredentials).toHaveBeenCalled()
1600+
expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("Signed out from Kimi Code")
1601+
expect(mockClineProvider.postStateToWebview).toHaveBeenCalled()
1602+
})
1603+
1604+
it("handles sign out error", async () => {
1605+
const mockClearCredentials = vi.fn().mockRejectedValue(new Error("Clear failed"))
1606+
1607+
vi.doMock("../../../integrations/kimi-code/oauth", () => ({
1608+
kimiCodeOAuthManager: {
1609+
clearCredentials: mockClearCredentials,
1610+
},
1611+
}))
1612+
1613+
await webviewMessageHandler(mockClineProvider, { type: "kimiCodeSignOut" })
1614+
1615+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Kimi Code sign out failed.")
1616+
})
1617+
})

0 commit comments

Comments
 (0)