native-release-smoke.cjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Actual packaged Electron + bundled PaaS. Only the model endpoint is synthetic.
  2. const { createRequire } = require("node:module")
  3. const path = require("node:path")
  4. const fs = require("node:fs/promises")
  5. const http = require("node:http")
  6. const req = createRequire(path.resolve(__dirname, "../../app/package.json"))
  7. const { _electron: electron, expect } = req("@playwright/test")
  8. ;(async () => {
  9. if (!process.argv[2]) throw new Error("Pass the packaged executable")
  10. const root = await fs.mkdtemp(path.join(require("node:os").tmpdir(), "lambda-release-"))
  11. const profile = path.join(root, "profile")
  12. const archive = path.join(root, "project.zip")
  13. let calls = 0
  14. let release = () => {}
  15. const model = http.createServer(async (request, response) => {
  16. for await (const _ of request) {
  17. }
  18. calls++
  19. const send = () => {
  20. if (response.writableEnded || response.destroyed) return
  21. response.setHeader("Content-Type", "application/json")
  22. response.end(
  23. JSON.stringify({
  24. id: "test",
  25. object: "chat.completion",
  26. created: 1,
  27. model: "synthetic-model",
  28. choices: [
  29. { index: 0, message: { role: "assistant", content: "本机安装包验收完成。" }, finish_reason: "stop" },
  30. ],
  31. usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 },
  32. }),
  33. )
  34. }
  35. if (calls === 1) release = send
  36. else send()
  37. })
  38. await new Promise((resolve) => model.listen(0, "127.0.0.1", resolve))
  39. const env = Object.fromEntries(
  40. Object.entries(process.env).filter(([key]) => !/^(AGENTPAAS_|AGENT_SERVICE_|PYTHONPATH$)|(_API_KEY|_TOKEN)$/.test(key)),
  41. )
  42. Object.assign(env, {
  43. OPENCODE_TEST_ONBOARDING: "1",
  44. OPENCODE_TEST_PROFILE: profile,
  45. AGENTPAAS_URL: "http://127.0.0.1:9",
  46. AGENTPAAS_API_KEY: "synthetic-unconnected",
  47. })
  48. let app
  49. let page
  50. let connection
  51. let userData
  52. const launch = async () => {
  53. app = await electron.launch({ executablePath: path.resolve(process.argv[2]), env, timeout: 60000 })
  54. page = await app.firstWindow()
  55. await page.waitForFunction(() => !!window.api?.paas)
  56. userData = await app.evaluate(({ app }) => app.getPath("userData"))
  57. if (!userData.startsWith(profile + path.sep)) throw new Error("Test profile is not isolated")
  58. await page.evaluate(() => window.api.paas.localRuntime.start(true))
  59. connection = await page.evaluate(() => window.api.paas.connect())
  60. return connection
  61. }
  62. const api = async (route, body, method = body ? "POST" : "GET") => {
  63. const config = JSON.parse(await fs.readFile(path.join(userData, "paas-runtime/config/config.json"), "utf8"))
  64. const status = await page.evaluate(() => window.api.paas.localRuntime.status())
  65. const response = await fetch(status.url + "/api/v1" + route, {
  66. method,
  67. headers: { Authorization: `Bearer ${config.api_key}`, "Content-Type": "application/json" },
  68. body: body ? JSON.stringify(body) : undefined,
  69. })
  70. const data = await response.json()
  71. if (!response.ok) throw new Error(`HTTP ${response.status} ${route}: ${JSON.stringify(data)}`)
  72. return data
  73. }
  74. try {
  75. const original = await launch()
  76. const setup = await api("/desktop/setup")
  77. for (const id of ["anthropic", "ollama"]) {
  78. const provider = setup.providers.find((item) => item.id === id)
  79. if (!provider || provider.configured) throw new Error(`Fresh ${id} incorrectly configured`)
  80. }
  81. const folders = [path.join(root, "primary"), path.join(root, "secondary")]
  82. await Promise.all(folders.map((folder) => fs.mkdir(folder)))
  83. await api("/desktop/providers/openai", { api_key: "synthetic-native-key" })
  84. const agent = await api("/agents", {
  85. name: "安装包测试助手",
  86. config: {
  87. type: "simple",
  88. systemPrompt: "Answer briefly.",
  89. model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.address().port}/v1` },
  90. },
  91. })
  92. const agentID = agent.agent_id || agent.id
  93. const scope = await page.evaluate((agentID) => window.api.paas.request({ action: "task-scope", agentID }), agentID)
  94. if (scope.agent_id !== agentID || scope.local_tools.length) throw new Error("Simple agent scope incorrect")
  95. await page.evaluate(({ id, folders }) => {
  96. window.nativeReleaseRun = window.api.paas.request({
  97. action: "execute",
  98. agentID: id,
  99. input: "验证后台运行",
  100. mode: "iterate",
  101. executionID: "native-release-owned",
  102. workDir: folders[0],
  103. workDirs: folders,
  104. })
  105. }, { id: agentID, folders })
  106. await expect.poll(() => calls, { timeout: 60000 }).toBeGreaterThan(0)
  107. await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close())
  108. await expect
  109. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  110. .toBe(false)
  111. await app.evaluate(({ app }) => app.emit("activate"))
  112. await expect
  113. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  114. .toBe(true)
  115. await app.evaluate(({ app, dialog }) => {
  116. dialog.showMessageBox = async () => ({ response: 0 })
  117. app.quit()
  118. })
  119. await expect
  120. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  121. .toBe(false)
  122. release()
  123. const run = await page.evaluate(() => window.nativeReleaseRun)
  124. if (run.status !== "completed") throw new Error("Background task did not complete")
  125. await app.evaluate(({ app }) => app.emit("activate"))
  126. await app.evaluate(({ dialog }, archive) => {
  127. dialog.showSaveDialog = async () => ({ canceled: false, filePath: archive })
  128. }, archive)
  129. await page.evaluate(
  130. async ({ agentID, archive }) => {
  131. await window.api.paas.backupProject(
  132. {
  133. format: "lambda-agent-project",
  134. version: 1,
  135. name: "打包验收",
  136. chats: [
  137. {
  138. title: "历史",
  139. agentID,
  140. name: "测试助手",
  141. draft: "保留草稿",
  142. messages: [{ role: "assistant", text: "本机安装包验收完成。", status: "completed" }],
  143. },
  144. ],
  145. },
  146. [],
  147. )
  148. },
  149. { agentID, archive },
  150. )
  151. await app.evaluate(
  152. ({ dialog }, { root, archive }) => {
  153. let selection = 0
  154. dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selection++ ? root : archive] })
  155. },
  156. { root, archive },
  157. )
  158. const restored = await page.evaluate(() => window.api.paas.restoreProject())
  159. if (restored.data.chats[0].draft !== "保留草稿") throw new Error("Backup lost draft")
  160. const before = calls
  161. // Relaunch only this test-owned application/profile, never an installed user instance.
  162. await app.close()
  163. app = undefined
  164. await launch()
  165. const saved = await api(`/agents/${agentID}/runs/${run.run_id}`)
  166. if (saved.status !== "completed" || calls !== before) throw new Error("Relaunch lost or replayed task")
  167. if (connection.scope !== original.scope) throw new Error("Managed workspace identity changed")
  168. await fs.writeFile(
  169. path.join(root, "result.json"),
  170. JSON.stringify(
  171. {
  172. packaged: true,
  173. freshProvidersUnconfigured: true,
  174. scopePreview: true,
  175. multiFolderRequest: true,
  176. closeContinued: true,
  177. quitDeclinedContinued: true,
  178. backupRestored: true,
  179. relaunchPreserved: true,
  180. replayedCalls: calls - before,
  181. version: await app.evaluate(({ app }) => app.getVersion()),
  182. },
  183. null,
  184. 2,
  185. ),
  186. )
  187. console.log(JSON.stringify({ status: "passed", root, calls, replayedCalls: calls - before }))
  188. } catch (error) {
  189. console.error("Acceptance files:", root)
  190. if (page && !page.isClosed()) await page.screenshot({ path: path.join(root, "failure.png") }).catch(() => {})
  191. throw error
  192. } finally {
  193. release()
  194. if (app) {
  195. await app
  196. .evaluate(({ dialog }) => {
  197. dialog.showMessageBox = async () => ({ response: 1 })
  198. })
  199. .catch(() => {})
  200. await app.close().catch(() => {})
  201. }
  202. await new Promise((resolve) => model.close(resolve))
  203. }
  204. })().catch((error) => {
  205. console.error(error)
  206. process.exitCode = 1
  207. })