native-release-smoke.cjs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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$)/.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. await api("/desktop/providers/openai", { api_key: "synthetic-native-key" })
  77. const agent = await api("/agents", {
  78. name: "安装包测试助手",
  79. config: {
  80. type: "simple",
  81. systemPrompt: "Answer briefly.",
  82. model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.address().port}/v1` },
  83. },
  84. })
  85. const agentID = agent.agent_id || agent.id
  86. await page.evaluate((id) => {
  87. window.nativeReleaseRun = window.api.paas.request({
  88. action: "execute",
  89. agentID: id,
  90. input: "验证后台运行",
  91. mode: "iterate",
  92. executionID: "native-release-owned",
  93. })
  94. }, agentID)
  95. await expect.poll(() => calls, { timeout: 60000 }).toBeGreaterThan(0)
  96. await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close())
  97. await expect
  98. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  99. .toBe(false)
  100. await app.evaluate(({ app }) => app.emit("activate"))
  101. await expect
  102. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  103. .toBe(true)
  104. await app.evaluate(({ app, dialog }) => {
  105. dialog.showMessageBox = async () => ({ response: 0 })
  106. app.quit()
  107. })
  108. await expect
  109. .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible()))
  110. .toBe(false)
  111. release()
  112. const run = await page.evaluate(() => window.nativeReleaseRun)
  113. if (run.status !== "completed") throw new Error("Background task did not complete")
  114. await app.evaluate(({ app }) => app.emit("activate"))
  115. await app.evaluate(({ dialog }, archive) => {
  116. dialog.showSaveDialog = async () => ({ canceled: false, filePath: archive })
  117. }, archive)
  118. await page.evaluate(
  119. async ({ agentID, archive }) => {
  120. await window.api.paas.backupProject(
  121. {
  122. format: "lambda-agent-project",
  123. version: 1,
  124. name: "打包验收",
  125. chats: [
  126. {
  127. title: "历史",
  128. agentID,
  129. name: "测试助手",
  130. draft: "保留草稿",
  131. messages: [{ role: "assistant", text: "本机安装包验收完成。", status: "completed" }],
  132. },
  133. ],
  134. },
  135. [],
  136. )
  137. },
  138. { agentID, archive },
  139. )
  140. await app.evaluate(
  141. ({ dialog }, { root, archive }) => {
  142. let selection = 0
  143. dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selection++ ? root : archive] })
  144. },
  145. { root, archive },
  146. )
  147. const restored = await page.evaluate(() => window.api.paas.restoreProject())
  148. if (restored.data.chats[0].draft !== "保留草稿") throw new Error("Backup lost draft")
  149. const before = calls
  150. // Relaunch only this test-owned application/profile, never an installed user instance.
  151. await app.close()
  152. app = undefined
  153. await launch()
  154. const saved = await api(`/agents/${agentID}/runs/${run.run_id}`)
  155. if (saved.status !== "completed" || calls !== before) throw new Error("Relaunch lost or replayed task")
  156. if (connection.scope !== original.scope) throw new Error("Managed workspace identity changed")
  157. await fs.writeFile(
  158. path.join(root, "result.json"),
  159. JSON.stringify(
  160. {
  161. packaged: true,
  162. closeContinued: true,
  163. quitDeclinedContinued: true,
  164. backupRestored: true,
  165. relaunchPreserved: true,
  166. replayedCalls: calls - before,
  167. version: await app.evaluate(({ app }) => app.getVersion()),
  168. },
  169. null,
  170. 2,
  171. ),
  172. )
  173. console.log(JSON.stringify({ status: "passed", root, calls, replayedCalls: calls - before }))
  174. } catch (error) {
  175. console.error("Acceptance files:", root)
  176. if (page && !page.isClosed()) await page.screenshot({ path: path.join(root, "failure.png") }).catch(() => {})
  177. throw error
  178. } finally {
  179. release()
  180. if (app) {
  181. await app
  182. .evaluate(({ dialog }) => {
  183. dialog.showMessageBox = async () => ({ response: 1 })
  184. })
  185. .catch(() => {})
  186. await app.close().catch(() => {})
  187. }
  188. await new Promise((resolve) => model.close(resolve))
  189. }
  190. })().catch((error) => {
  191. console.error(error)
  192. process.exitCode = 1
  193. })