/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * @import { HttpServer } from "resource://testing-common/httpd.sys.mjs" */ import { AIWindowTestUtils } from "resource://testing-common/AIWindowTestUtils.sys.mjs"; import { BrowserTestUtils } from "resource://testing-common/BrowserTestUtils.sys.mjs"; import { sinon } from "resource://testing-common/Sinon.sys.mjs"; import { AuthProvider } from "moz-src:///browser/components/aiwindow/models/AuthProvider.sys.mjs"; import { Chat } from "moz-src:///browser/components/aiwindow/models/Chat.sys.mjs"; import { openAIEngine } from "moz-src:///browser/components/aiwindow/models/openAIEngine.sys.mjs"; const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { HttpServer: "resource://testing-common/httpd.sys.mjs", NetUtil: "resource://gre/modules/NetUtil.sys.mjs", setTimeout: "resource://gre/modules/Timer.sys.mjs", }); /** * @typedef {object} MockOpenAIServerOptions * @property {string[]} [streamChunks] - The content of each chunk of a * streamed response. Defaults to ["Hello from mock."]. * @property {number} [streamChunkDelayMs] - Delay before each streamed chunk. * @property {(index: number) => Promise|void} [beforeStreamChunk] * Called before each streamed chunk; may pause the stream. * @property {object} [usage] - Token usage sent with the last streamed chunk. * @property {(body: object) => void} [onRequest] - Called with the parsed body * of every request. * @property {string} [completion] - Content of a non-streamed response. * Defaults to "Mock response". */ /** * @typedef {object} ChatWindowFixture * @property {MozBrowser} browser - The new window's selected browser. * @property {sinon.SinonStub} buildStub - Records engine builds and delegates * chat and title generation to their production implementations. */ function readRequestBody(request) { const stream = request.bodyInputStream; return lazy.NetUtil.readInputStreamToString(stream, stream.available(), { charset: "UTF-8", }); } /** * A local server that speaks the OpenAI chat completions protocol. * * Use MockEngineManager from AIWindowTestUtils.sys.mjs instead, unless the test * checks something only the real engine and HTTP layer produce, such as the * request body sent over the wire, parsed streaming usage, or the engine's * lifecycle. Tests that need this server go in * browser/components/aiwindow/ui/test/browser/http. */ export const MockOpenAIServer = { /** * Starts the server, which streams SSE chunks or returns a JSON completion * depending on the request's `stream` flag. * * @param {MockOpenAIServerOptions} [options] * @returns {{ server: HttpServer, port: number }} */ start({ streamChunks = ["Hello from mock."], streamChunkDelayMs = 0, beforeStreamChunk, usage, onRequest, completion = "Mock response", } = {}) { const server = new lazy.HttpServer(); server.registerPathHandler("/v1/chat/completions", (request, response) => { let body = {}; try { body = JSON.parse(readRequestBody(request) || "{}"); } catch (_) {} onRequest?.(body); const created = Math.floor(Date.now() / 1000); response.setStatusLine(request.httpVersion, 200, "OK"); response.setHeader("Access-Control-Allow-Origin", "*", false); if (!body.stream) { response.setHeader("Content-Type", "application/json", false); response.write( JSON.stringify({ id: "chatcmpl-aiwindow-non-stream", object: "chat.completion", created, model: "aiwindow-mock", choices: [ { index: 0, message: { role: "assistant", content: completion }, finish_reason: "stop", }, ], }) ); return; } response.setHeader( "Content-Type", "text/event-stream; charset=utf-8", false ); response.setHeader("Cache-Control", "no-cache", false); response.processAsync(); // Encode as UTF-8 so tokens such as §followup:§ survive the write. const sendSSE = event => response.write( Array.from( new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`), byte => String.fromCharCode(byte) ).join("") ); (async () => { for (const [index, chunk] of streamChunks.entries()) { await beforeStreamChunk?.(index); if (streamChunkDelayMs) { await new Promise(resolve => lazy.setTimeout(resolve, streamChunkDelayMs) ); } const isLast = index === streamChunks.length - 1; sendSSE({ id: `chatcmpl-aiwindow-stream-${index}`, object: "chat.completion.chunk", created, model: "aiwindow-mock", choices: [ { index: 0, delta: { content: chunk }, finish_reason: isLast ? "stop" : null, }, ], ...(isLast && usage ? { usage } : {}), }); } response.write("data: [DONE]\n\n"); response.finish(); })(); }); server.start(-1); return { server, port: server.identity.primaryPort }; }, /** * @param {HttpServer} server - A server from `start()`. * @returns {Promise} Resolves once the server has stopped. */ stop(server) { return new Promise(resolve => server.stop(resolve)); }, /** * Runs a task with the Smart Window endpoints pointing at a new server and * sign-in stubbed. * * @param {MockOpenAIServerOptions} options * @param {(server: { port: number }) => Promise} task * @returns {Promise} */ async withServer(options, task) { const { specialPowers } = AIWindowTestUtils; const { server, port } = MockOpenAIServer.start(options); await specialPowers.pushPrefEnv({ set: [ ["browser.smartwindow.endpoint", `http://localhost:${port}/v1`], ["browser.smartwindow.customEndpoint", `http://localhost:${port}/v1`], ], }); const getTokenStub = sinon .stub(AuthProvider, "getToken") .resolves("mock-fxa-token"); try { await task({ port }); } finally { getTokenStub.restore(); await specialPowers.popPrefEnv(); await MockOpenAIServer.stop(server); } }, /** * Runs a chat scenario in a new window whose chat and title generation go * through the real engine to a new server, with the other features' engines * mocked. Waits for the chat turns and titles before closing the window. * * @param {MockOpenAIServerOptions} options * @param {(fixture: ChatWindowFixture) => Promise} task * @returns {Promise} */ async withChatWindow(options, task) { const { specialPowers } = AIWindowTestUtils; const { server, port } = MockOpenAIServer.start(options); await specialPowers.pushPrefEnv({ set: [ ["browser.smartwindow.endpoint", `http://localhost:${port}/v1`], ["browser.smartwindow.customEndpoint", `http://localhost:${port}/v1`], ], }); const sandbox = sinon.createSandbox(); const realFeatures = new Set(["chat", "title-generation"]); const originalBuild = openAIEngine.build.bind(openAIEngine); sandbox.stub(openAIEngine, "build").callsFake(async config => { if (realFeatures.has(config.feature)) { return originalBuild(config); } return { feature: config.feature, model: config.model, async run() { return { finalOutput: "Mock" }; }, runWithGenerator() {}, }; }); sandbox.stub(AuthProvider, "getToken").resolves("mock-fxa-token"); const abortController = new AbortController(); const turns = new Set(); const conversations = new Set(); let win; try { const fetchWithHistory = sandbox .stub(Chat, "fetchWithHistory") .callsFake(fetchOptions => { conversations.add(fetchOptions.conversation); const signal = fetchOptions.signal ? AbortSignal.any([fetchOptions.signal, abortController.signal]) : abortController.signal; const turn = fetchWithHistory.wrappedMethod.call(Chat, { ...fetchOptions, signal, }); turns.add(turn); const settled = () => turns.delete(turn); turn.then(settled, settled); return turn; }); win = await AIWindowTestUtils.openReadyAIWindow(); await task({ browser: win.gBrowser.selectedBrowser, buildStub: openAIEngine.build, }); } finally { abortController.abort(); try { while (turns.size) { await Promise.allSettled(turns); } await Promise.allSettled( Array.from(conversations, conversation => conversation.titlePromise) ); } finally { try { if (win) { await BrowserTestUtils.closeWindow(win); } } finally { sandbox.restore(); await specialPowers.popPrefEnv(); await MockOpenAIServer.stop(server); } } } }, };