// Actual packaged Electron + bundled PaaS. Only the model endpoint is synthetic. const { createRequire } = require("node:module") const path = require("node:path") const fs = require("node:fs/promises") const http = require("node:http") const req = createRequire(path.resolve(__dirname, "../../app/package.json")) const { _electron: electron, expect } = req("@playwright/test") ;(async () => { if (!process.argv[2]) throw new Error("Pass the packaged executable") const root = await fs.mkdtemp(path.join(require("node:os").tmpdir(), "lambda-release-")) const profile = path.join(root, "profile") const archive = path.join(root, "project.zip") let calls = 0 let release = () => {} const model = http.createServer(async (request, response) => { for await (const _ of request) { } calls++ const send = () => { if (response.writableEnded || response.destroyed) return response.setHeader("Content-Type", "application/json") response.end( JSON.stringify({ id: "test", object: "chat.completion", created: 1, model: "synthetic-model", choices: [ { index: 0, message: { role: "assistant", content: "本机安装包验收完成。" }, finish_reason: "stop" }, ], usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 }, }), ) } if (calls === 1) release = send else send() }) await new Promise((resolve) => model.listen(0, "127.0.0.1", resolve)) const env = Object.fromEntries( Object.entries(process.env).filter(([key]) => !/^(AGENTPAAS_|AGENT_SERVICE_|PYTHONPATH$)|(_API_KEY|_TOKEN)$/.test(key)), ) Object.assign(env, { OPENCODE_TEST_ONBOARDING: "1", OPENCODE_TEST_PROFILE: profile, AGENTPAAS_URL: "http://127.0.0.1:9", AGENTPAAS_API_KEY: "synthetic-unconnected", }) let app let page let connection let userData const launch = async () => { app = await electron.launch({ executablePath: path.resolve(process.argv[2]), env, timeout: 60000 }) page = await app.firstWindow() await page.waitForFunction(() => !!window.api?.paas) userData = await app.evaluate(({ app }) => app.getPath("userData")) if (!userData.startsWith(profile + path.sep)) throw new Error("Test profile is not isolated") await page.evaluate(() => window.api.paas.localRuntime.start(true)) connection = await page.evaluate(() => window.api.paas.connect()) return connection } const api = async (route, body, method = body ? "POST" : "GET") => { const config = JSON.parse(await fs.readFile(path.join(userData, "paas-runtime/config/config.json"), "utf8")) const status = await page.evaluate(() => window.api.paas.localRuntime.status()) const response = await fetch(status.url + "/api/v1" + route, { method, headers: { Authorization: `Bearer ${config.api_key}`, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, }) const data = await response.json() if (!response.ok) throw new Error(`HTTP ${response.status} ${route}: ${JSON.stringify(data)}`) return data } try { const original = await launch() const setup = await api("/desktop/setup") for (const id of ["anthropic", "ollama"]) { const provider = setup.providers.find((item) => item.id === id) if (!provider || provider.configured) throw new Error(`Fresh ${id} incorrectly configured`) } const folders = [path.join(root, "primary"), path.join(root, "secondary")] await Promise.all(folders.map((folder) => fs.mkdir(folder))) await api("/desktop/providers/openai", { api_key: "synthetic-native-key" }) const agent = await api("/agents", { name: "安装包测试助手", config: { type: "simple", systemPrompt: "Answer briefly.", model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.address().port}/v1` }, }, }) const agentID = agent.agent_id || agent.id const scope = await page.evaluate((agentID) => window.api.paas.request({ action: "task-scope", agentID }), agentID) if (scope.agent_id !== agentID || scope.local_tools.length) throw new Error("Simple agent scope incorrect") await page.evaluate(({ id, folders }) => { window.nativeReleaseRun = window.api.paas.request({ action: "execute", agentID: id, input: "验证后台运行", mode: "iterate", executionID: "native-release-owned", workDir: folders[0], workDirs: folders, }) }, { id: agentID, folders }) await expect.poll(() => calls, { timeout: 60000 }).toBeGreaterThan(0) await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close()) await expect .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())) .toBe(false) await app.evaluate(({ app }) => app.emit("activate")) await expect .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())) .toBe(true) await app.evaluate(({ app, dialog }) => { dialog.showMessageBox = async () => ({ response: 0 }) app.quit() }) await expect .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())) .toBe(false) release() const run = await page.evaluate(() => window.nativeReleaseRun) if (run.status !== "completed") throw new Error("Background task did not complete") await app.evaluate(({ app }) => app.emit("activate")) await app.evaluate(({ dialog }, archive) => { dialog.showSaveDialog = async () => ({ canceled: false, filePath: archive }) }, archive) await page.evaluate( async ({ agentID, archive }) => { await window.api.paas.backupProject( { format: "lambda-agent-project", version: 1, name: "打包验收", chats: [ { title: "历史", agentID, name: "测试助手", draft: "保留草稿", messages: [{ role: "assistant", text: "本机安装包验收完成。", status: "completed" }], }, ], }, [], ) }, { agentID, archive }, ) await app.evaluate( ({ dialog }, { root, archive }) => { let selection = 0 dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selection++ ? root : archive] }) }, { root, archive }, ) const restored = await page.evaluate(() => window.api.paas.restoreProject()) if (restored.data.chats[0].draft !== "保留草稿") throw new Error("Backup lost draft") const before = calls // Relaunch only this test-owned application/profile, never an installed user instance. await app.close() app = undefined await launch() const saved = await api(`/agents/${agentID}/runs/${run.run_id}`) if (saved.status !== "completed" || calls !== before) throw new Error("Relaunch lost or replayed task") if (connection.scope !== original.scope) throw new Error("Managed workspace identity changed") await fs.writeFile( path.join(root, "result.json"), JSON.stringify( { packaged: true, freshProvidersUnconfigured: true, scopePreview: true, multiFolderRequest: true, closeContinued: true, quitDeclinedContinued: true, backupRestored: true, relaunchPreserved: true, replayedCalls: calls - before, version: await app.evaluate(({ app }) => app.getVersion()), }, null, 2, ), ) console.log(JSON.stringify({ status: "passed", root, calls, replayedCalls: calls - before })) } catch (error) { console.error("Acceptance files:", root) if (page && !page.isClosed()) await page.screenshot({ path: path.join(root, "failure.png") }).catch(() => {}) throw error } finally { release() if (app) { await app .evaluate(({ dialog }) => { dialog.showMessageBox = async () => ({ response: 1 }) }) .catch(() => {}) await app.close().catch(() => {}) } await new Promise((resolve) => model.close(resolve)) } })().catch((error) => { console.error(error) process.exitCode = 1 })