|
| 1 | +import * as assert from "assert" |
| 2 | +import { createServer, type IncomingMessage, type ServerResponse } from "http" |
| 3 | + |
| 4 | +import { RooCodeEventName, mimoModels, type ClineMessage } from "@roo-code/types" |
| 5 | + |
| 6 | +import { setDefaultSuiteTimeout } from "./test-utils" |
| 7 | + |
| 8 | +/** |
| 9 | + * E2E coverage for the B17 provider cost metric calculation. |
| 10 | + * |
| 11 | + * The MiMo provider (src/api/providers/mimo.ts) computes `totalCost` from |
| 12 | + * streamed `usage` chunks via `calculateApiCostOpenAI` and yields it as a |
| 13 | + * `usage` stream item. Task.ts then persists it on the `api_req_started` |
| 14 | + * cline message (`cost` field of ClineApiReqInfo) and forwards it to |
| 15 | + * `TelemetryService.captureLlmCompletion`. This suite drives the built |
| 16 | + * extension against a local OpenAI-compatible stub that returns a fixed |
| 17 | + * usage payload and asserts the persisted cost matches the model's |
| 18 | + * published pricing (inputPrice/outputPrice of mimo-v2.5-pro). |
| 19 | + */ |
| 20 | + |
| 21 | +type CapturedMimoRequest = { |
| 22 | + model?: string |
| 23 | + stream?: boolean |
| 24 | + includeUsage?: boolean |
| 25 | +} |
| 26 | + |
| 27 | +const MIMO_MODEL_ID = "mimo-v2.5-pro" |
| 28 | +// Deterministic usage payload served by the stub. Cost expectation: |
| 29 | +// input: 1000 / 1e6 * $1.00 = $0.001 |
| 30 | +// output: 500 / 1e6 * $3.00 = $0.0015 |
| 31 | +// total = $0.0025 |
| 32 | +const STUB_INPUT_TOKENS = 1000 |
| 33 | +const STUB_OUTPUT_TOKENS = 500 |
| 34 | +const EXPECTED_TOTAL_COST = 0.0025 |
| 35 | + |
| 36 | +function readRequestBody(req: IncomingMessage): Promise<string> { |
| 37 | + return new Promise((resolve, reject) => { |
| 38 | + const chunks: Buffer[] = [] |
| 39 | + req.on("data", (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))) |
| 40 | + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))) |
| 41 | + req.on("error", reject) |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +function buildSsePayload(modelId: string): string { |
| 46 | + const textChunk = { |
| 47 | + id: "chatcmpl-stub", |
| 48 | + object: "chat.completion.chunk", |
| 49 | + created: 0, |
| 50 | + model: modelId, |
| 51 | + choices: [{ index: 0, delta: { role: "assistant", content: "4" }, finish_reason: null }], |
| 52 | + } |
| 53 | + |
| 54 | + const finalChunk = { |
| 55 | + id: "chatcmpl-stub", |
| 56 | + object: "chat.completion.chunk", |
| 57 | + created: 0, |
| 58 | + model: modelId, |
| 59 | + choices: [{ index: 0, delta: {}, finish_reason: "stop" }], |
| 60 | + usage: { |
| 61 | + prompt_tokens: STUB_INPUT_TOKENS, |
| 62 | + completion_tokens: STUB_OUTPUT_TOKENS, |
| 63 | + total_tokens: STUB_INPUT_TOKENS + STUB_OUTPUT_TOKENS, |
| 64 | + }, |
| 65 | + } |
| 66 | + |
| 67 | + return `data: ${JSON.stringify(textChunk)}\n\ndata: ${JSON.stringify(finalChunk)}\n\ndata: [DONE]\n\n` |
| 68 | +} |
| 69 | + |
| 70 | +function isChatCompletionsUrl(rawUrl: string): boolean { |
| 71 | + try { |
| 72 | + return new URL(rawUrl, "http://127.0.0.1").pathname.endsWith("/chat/completions") |
| 73 | + } catch { |
| 74 | + return false |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +async function withMimoStub<T>( |
| 79 | + run: (args: { baseUrl: string; requests: CapturedMimoRequest[] }) => Promise<T>, |
| 80 | +): Promise<T> { |
| 81 | + const requests: CapturedMimoRequest[] = [] |
| 82 | + let serverError: Error | undefined |
| 83 | + |
| 84 | + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { |
| 85 | + try { |
| 86 | + const requestUrl = req.url ?? "/" |
| 87 | + |
| 88 | + if (!isChatCompletionsUrl(requestUrl)) { |
| 89 | + res.writeHead(404) |
| 90 | + res.end("Not found") |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + const bodyText = await readRequestBody(req) |
| 95 | + const body = JSON.parse(bodyText) as { |
| 96 | + model?: string |
| 97 | + stream?: boolean |
| 98 | + stream_options?: { include_usage?: boolean } |
| 99 | + } |
| 100 | + |
| 101 | + requests.push({ |
| 102 | + model: body.model, |
| 103 | + stream: body.stream, |
| 104 | + includeUsage: body.stream_options?.include_usage, |
| 105 | + }) |
| 106 | + |
| 107 | + res.writeHead(200, { |
| 108 | + "Content-Type": "text/event-stream", |
| 109 | + "Cache-Control": "no-cache", |
| 110 | + Connection: "keep-alive", |
| 111 | + }) |
| 112 | + res.end(buildSsePayload(body.model ?? MIMO_MODEL_ID)) |
| 113 | + } catch (error) { |
| 114 | + serverError = error instanceof Error ? error : new Error(String(error)) |
| 115 | + res.writeHead(500) |
| 116 | + res.end("Stub failure") |
| 117 | + } |
| 118 | + }) |
| 119 | + |
| 120 | + await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve())) |
| 121 | + const address = server.address() |
| 122 | + if (!address || typeof address === "string") { |
| 123 | + server.close() |
| 124 | + throw new Error("Failed to start MiMo stub server") |
| 125 | + } |
| 126 | + |
| 127 | + const baseUrl = `http://127.0.0.1:${address.port}/v1` |
| 128 | + |
| 129 | + try { |
| 130 | + const result = await run({ baseUrl, requests }) |
| 131 | + if (serverError) { |
| 132 | + throw serverError |
| 133 | + } |
| 134 | + return result |
| 135 | + } finally { |
| 136 | + await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +function extractCost(message: ClineMessage): number | undefined { |
| 141 | + if (message.type !== "say" || message.say !== "api_req_started" || !message.text) { |
| 142 | + return undefined |
| 143 | + } |
| 144 | + try { |
| 145 | + const info = JSON.parse(message.text) as { cost?: number } |
| 146 | + return typeof info.cost === "number" ? info.cost : undefined |
| 147 | + } catch { |
| 148 | + return undefined |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +suite("Provider Cost Metrics (B17)", function () { |
| 153 | + setDefaultSuiteTimeout(this) |
| 154 | + |
| 155 | + // Restore the default OpenRouter config so subsequent suites are unaffected. |
| 156 | + suiteTeardown(async () => { |
| 157 | + const aimockUrl = process.env.AIMOCK_URL |
| 158 | + const isRecord = process.env.AIMOCK_RECORD === "true" |
| 159 | + await globalThis.api.setConfiguration({ |
| 160 | + apiProvider: "openrouter" as const, |
| 161 | + openRouterApiKey: aimockUrl && !isRecord ? "mock-key" : process.env.OPENROUTER_API_KEY!, |
| 162 | + openRouterModelId: "openai/gpt-4.1", |
| 163 | + ...(aimockUrl && { openRouterBaseUrl: `${aimockUrl}/v1` }), |
| 164 | + }) |
| 165 | + }) |
| 166 | + |
| 167 | + test("MiMo provider streams usage, calculates cost, and persists it on api_req_started", async function () { |
| 168 | + const api = globalThis.api |
| 169 | + |
| 170 | + await withMimoStub(async ({ baseUrl, requests }) => { |
| 171 | + await api.setConfiguration({ |
| 172 | + apiProvider: "mimo" as const, |
| 173 | + mimoApiKey: "stub-key", |
| 174 | + // The zod schema restricts mimoBaseUrl to Xiaomi's hosted endpoints, |
| 175 | + // but the runtime provider accepts any OpenAI-compatible base URL |
| 176 | + // (options.mimoBaseUrl || default). A local stub URL is required to |
| 177 | + // exercise the streaming/usage path without network access, so this |
| 178 | + // test intentionally widens the type. |
| 179 | + mimoBaseUrl: baseUrl as "https://api.xiaomimimo.com/v1", |
| 180 | + apiModelId: MIMO_MODEL_ID, |
| 181 | + }) |
| 182 | + |
| 183 | + const apiReqMessages: ClineMessage[] = [] |
| 184 | + const onMessage = ({ message }: { message: ClineMessage }) => { |
| 185 | + if (message.type === "say" && message.say === "api_req_started" && message.partial === false) { |
| 186 | + apiReqMessages.push(message) |
| 187 | + } |
| 188 | + } |
| 189 | + api.on(RooCodeEventName.Message, onMessage) |
| 190 | + |
| 191 | + let taskId: string |
| 192 | + try { |
| 193 | + taskId = await api.startNewTask({ |
| 194 | + configuration: { mode: "ask", alwaysAllowModeSwitch: true, autoApprovalEnabled: true }, |
| 195 | + text: "provider-cost-e2e: what is 2+2? Reply with only the number.", |
| 196 | + }) |
| 197 | + |
| 198 | + await new Promise<void>((resolve, reject) => { |
| 199 | + const timer = setTimeout(() => { |
| 200 | + cleanup() |
| 201 | + reject(new Error("Timeout after 60s")) |
| 202 | + }, 60_000) |
| 203 | + |
| 204 | + const cleanup = () => { |
| 205 | + clearTimeout(timer) |
| 206 | + api.off(RooCodeEventName.TaskCompleted, onCompleted) |
| 207 | + api.off(RooCodeEventName.TaskAborted, onAborted) |
| 208 | + } |
| 209 | + |
| 210 | + const onCompleted = (completedId: string) => { |
| 211 | + if (completedId === taskId) { |
| 212 | + cleanup() |
| 213 | + resolve() |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + const onAborted = (abortedId: string) => { |
| 218 | + if (abortedId === taskId) { |
| 219 | + cleanup() |
| 220 | + reject(new Error("Task was aborted - MiMo stub request failed")) |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + api.on(RooCodeEventName.TaskCompleted, onCompleted) |
| 225 | + api.on(RooCodeEventName.TaskAborted, onAborted) |
| 226 | + }) |
| 227 | + } finally { |
| 228 | + api.off(RooCodeEventName.Message, onMessage) |
| 229 | + } |
| 230 | + |
| 231 | + // The provider must have issued at least one streaming request asking for usage. |
| 232 | + const firstRequest = requests[0] |
| 233 | + assert.ok(firstRequest, "MiMo provider should issue at least one /chat/completions request") |
| 234 | + assert.strictEqual(firstRequest.model, MIMO_MODEL_ID) |
| 235 | + assert.strictEqual(firstRequest.stream, true) |
| 236 | + assert.strictEqual( |
| 237 | + firstRequest.includeUsage, |
| 238 | + true, |
| 239 | + "MiMo provider must request usage via stream_options.include_usage", |
| 240 | + ) |
| 241 | + |
| 242 | + // Cost data flows into usage stats: the final api_req_started message |
| 243 | + // must carry the cost computed by calculateApiCostOpenAI for the stubbed |
| 244 | + // token counts and mimo-v2.5-pro pricing. |
| 245 | + const costs = apiReqMessages.map(extractCost).filter((c): c is number => typeof c === "number") |
| 246 | + assert.ok(costs.length > 0, "At least one api_req_started message should contain a cost value") |
| 247 | + |
| 248 | + const finalCost = costs[costs.length - 1] |
| 249 | + assert.ok( |
| 250 | + finalCost !== undefined && Math.abs(finalCost - EXPECTED_TOTAL_COST) < 1e-9, |
| 251 | + `Expected total cost ${EXPECTED_TOTAL_COST} but got ${finalCost}`, |
| 252 | + ) |
| 253 | + |
| 254 | + // Sanity: the pricing inputs come from the mimoModels registry. |
| 255 | + assert.strictEqual(mimoModels[MIMO_MODEL_ID].inputPrice, 1.0) |
| 256 | + assert.strictEqual(mimoModels[MIMO_MODEL_ID].outputPrice, 3.0) |
| 257 | + }) |
| 258 | + }) |
| 259 | +}) |
0 commit comments