native-release-smoke.cjs 8.9 KB

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