native-smoke.cjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Packaged-app smoke test: synthetic HTTP API; native file dialog selections are stubbed.
  2. const { createRequire } = require("node:module")
  3. const req = createRequire(require("node:path").resolve(__dirname, "../../app/package.json"))
  4. const { _electron: electron, expect } = req("@playwright/test")
  5. const http = require("node:http")
  6. const fs = require("node:fs/promises")
  7. const path = require("node:path")
  8. ;(async () => {
  9. if (!process.argv[2]) throw new Error("Usage: node scripts/native-smoke.cjs <packaged executable>")
  10. const root = await fs.mkdtemp(path.join(require("node:os").tmpdir(), "lambda-native-"))
  11. const material = path.join(root, "material.txt"),
  12. saved = path.join(root, "research-plan.txt"),
  13. report = path.join(root, "research-report.md")
  14. await fs.writeFile(material, "Native desktop research material")
  15. const calls = []
  16. const run = {
  17. run_id: "run_native",
  18. agent_id: "research",
  19. thread_id: "thread_native",
  20. status: "completed",
  21. output:
  22. "# 科研方案验收\n\nNative research plan completed\n\n## 对照与判断\n\n1. 明确适用条件。\n2. 保留引用与验证步骤。\n\n| 方案 | 样本量 |\n|---|---|\n| 对照组 | 20 |\n| 实验组 | 20 |\n\n待验证公式:$\\delta > 0$。\n\n## 后续研究\n\n本文件为桌面导出测试材料,不代表真实实验结果。",
  23. }
  24. const server = http.createServer(async (request, response) => {
  25. const url = new URL(request.url, "http://localhost")
  26. const chunks = []
  27. for await (const chunk of request) chunks.push(chunk)
  28. const body = Buffer.concat(chunks)
  29. calls.push({ path: url.pathname, method: request.method, body: body.toString() })
  30. response.setHeader("Content-Type", "application/json")
  31. const send = (value) => response.end(JSON.stringify(value))
  32. if (url.pathname === "/api/v1/agents")
  33. return send({ agents: [{ id: "research", name: "科研助手", current_version: 1 }] })
  34. if (url.pathname === "/api/v1/agents/research") return send({ id: "research", name: "科研助手", work_dir: root })
  35. if (url.pathname.endsWith("/run-options")) return send({ efforts: [] })
  36. if (url.pathname.endsWith("/threads")) return send({ threads: [] })
  37. if (url.pathname.endsWith("/files/capabilities")) return send({ direct_upload_max_bytes: 268435456 })
  38. if (url.pathname === "/api/v1/files") return send({ file_id: "native_file", name: "material.txt" })
  39. if (url.pathname.endsWith("/run/stream")) {
  40. response.setHeader("Content-Type", "text/event-stream")
  41. return response.end(
  42. "event: started\ndata: " +
  43. JSON.stringify({ run_id: run.run_id, thread_id: run.thread_id }) +
  44. "\n\nevent: done\ndata: " +
  45. JSON.stringify(run) +
  46. "\n\n",
  47. )
  48. }
  49. if (url.pathname.endsWith("/workspace/plan.txt")) {
  50. response.setHeader("Content-Type", "text/plain")
  51. return response.end("Saved from native IPC")
  52. }
  53. if (url.pathname.endsWith("/workspace/research-report.pdf")) {
  54. response.setHeader("Content-Type", "application/pdf")
  55. return response.end(await fs.readFile(report.replace(/\.md$/, ".pdf")))
  56. }
  57. if (url.pathname.endsWith("/workspace")) {
  58. const files = [{ name: "plan.txt", path: "plan.txt" }]
  59. if (
  60. await fs.stat(report.replace(/\.md$/, ".pdf")).then(
  61. () => true,
  62. () => false,
  63. )
  64. )
  65. files.push({ name: "research-report.pdf", path: "research-report.pdf" })
  66. return send({ files })
  67. }
  68. if (url.pathname.endsWith("/runs/run_native")) return send(run)
  69. if (url.pathname.endsWith("/runs")) return send({ runs: [run] })
  70. return send({ threads: [], runs: [] })
  71. })
  72. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
  73. const url = "http://127.0.0.1:" + server.address().port
  74. let app
  75. try {
  76. app = await electron.launch({
  77. executablePath: path.resolve(process.argv[2]),
  78. env: { ...process.env, OPENCODE_TEST_ONBOARDING: "1", AGENTPAAS_URL: url, AGENTPAAS_API_KEY: "native-test-only" },
  79. timeout: 60000,
  80. })
  81. const window = await app.firstWindow()
  82. const errors = []
  83. window.on("pageerror", (e) => {
  84. errors.push(e.message)
  85. console.log("PAGEERROR", e.message)
  86. })
  87. await window.waitForLoadState("domcontentloaded")
  88. console.log("window", await window.title())
  89. await expect(window.getByRole("button", { name: "智能体", exact: true })).toBeVisible({ timeout: 30000 })
  90. await window.getByRole("button", { name: "智能体", exact: true }).click()
  91. await window.getByRole("button", { name: "与 科研助手 对话", exact: true }).click()
  92. await window.locator(".paas-suggestions button").first().click()
  93. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toBeFocused()
  94. await window.getByRole("textbox", { name: "消息", exact: true }).fill("中文确认不会自动发送")
  95. await window.getByRole("textbox", { name: "消息", exact: true }).dispatchEvent("keydown", {
  96. key: "Enter",
  97. code: "Enter",
  98. keyCode: 229,
  99. bubbles: true,
  100. })
  101. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("中文确认不会自动发送")
  102. if (calls.some((call) => call.path.endsWith("/run/stream"))) throw new Error("IME confirmation submitted research")
  103. await app.evaluate(({ Menu }) => {
  104. const entry = Menu.getApplicationMenu()
  105. .items.flatMap((item) => item.submenu?.items || [])
  106. .find((item) => item.label === "Settings")
  107. entry.click()
  108. })
  109. await expect(window.getByRole("heading", { name: "平台连接", exact: true })).toBeVisible()
  110. await app.evaluate(({ Menu }) => {
  111. const entry = Menu.getApplicationMenu()
  112. .items.flatMap((item) => item.submenu?.items || [])
  113. .find((item) => item.label === "New Session")
  114. entry.click()
  115. })
  116. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("")
  117. await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setSize(587, 800))
  118. await window.getByRole("button", { name: "打开导航", exact: true }).click()
  119. await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setSize(1280, 800))
  120. await expect(window.locator(".paas-nav-open")).toHaveCount(0)
  121. await app.evaluate(
  122. ({ dialog }, { material, saved, report }) => {
  123. dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [material] })
  124. dialog.showSaveDialog = async (options) => ({
  125. canceled: false,
  126. filePath:
  127. options.title === "导出研究报告" ? report.replace(/\.md$/, "." + options.filters[0].extensions[0]) : saved,
  128. })
  129. },
  130. { material, saved, report },
  131. )
  132. await window.getByRole("button", { name: "添加文件", exact: true }).click()
  133. await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
  134. await window.getByRole("textbox", { name: "消息", exact: true }).fill("Create a research plan")
  135. await window.reload()
  136. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan", {
  137. timeout: 30000,
  138. })
  139. await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
  140. await window.getByRole("button", { name: "代码工作区", exact: true }).click()
  141. await expect(window.locator(".paas-code-host")).toBeVisible()
  142. await window.getByRole("button", { name: "会话", exact: true }).click()
  143. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan")
  144. await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
  145. await window.locator(".paas-more-actions > summary").click()
  146. await window.getByRole("button", { name: "在开发区打开工作区", exact: true }).click()
  147. await expect(window.locator(".paas-code-host")).toBeVisible()
  148. await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toBeVisible({
  149. timeout: 30000,
  150. })
  151. await expect(window.getByText(path.basename(root), { exact: true }).first()).toBeVisible({ timeout: 10000 })
  152. await window
  153. .locator('[data-component="prompt-input"][contenteditable="true"]')
  154. .fill("检查工作目录中的成果,不自动执行")
  155. await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toContainText(
  156. "检查工作目录中的成果,不自动执行",
  157. )
  158. await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toBeInViewport()
  159. await expect(window.getByText(path.basename(root), { exact: true }).first()).toBeInViewport()
  160. await expect(window.getByLabel("λ-Agent 工作台导航")).toBeVisible()
  161. await window.getByRole("button", { name: "会话", exact: true }).click()
  162. await window.getByRole("button", { name: "代码工作区", exact: true }).click()
  163. await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toContainText("检查工作目录中的成果,不自动执行")
  164. await window.screenshot({ path: path.join(root, "developer-handoff.png") })
  165. await app.evaluate(({ Menu }) => {
  166. Menu.getApplicationMenu()
  167. .items.flatMap((item) => item.submenu?.items || [])
  168. .find((item) => item.label === "Settings")
  169. .click()
  170. })
  171. await expect(window.getByRole("dialog")).toBeVisible()
  172. await window.keyboard.press("Escape")
  173. await expect(window.getByRole("dialog")).toBeHidden()
  174. await window.getByRole("button", { name: "会话", exact: true }).click()
  175. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan")
  176. await window.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
  177. await expect(window.getByText("Native research plan completed", { exact: true }).first()).toBeVisible()
  178. await window.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
  179. await app.evaluate(({ dialog }) => {
  180. const save = dialog.showSaveDialog
  181. dialog.showSaveDialog = async (...args) => {
  182. dialog.showSaveDialog = save
  183. return { canceled: true }
  184. }
  185. })
  186. await window.getByRole("button", { name: "保存文件", exact: true }).click()
  187. await expect(window.getByText("已取消保存,文件仍保留在平台。", { exact: true })).toBeVisible()
  188. if (
  189. await fs.stat(saved).then(
  190. () => true,
  191. () => false,
  192. )
  193. )
  194. throw new Error("Cancelled download created a file")
  195. await window.getByRole("button", { name: "保存文件", exact: true }).click()
  196. await expect(window.getByText("文件已保存。", { exact: true })).toBeVisible()
  197. if ((await fs.readFile(saved, "utf8")) !== "Saved from native IPC") throw new Error("Downloaded bytes mismatch")
  198. await window.getByRole("button", { name: "预览 plan.txt", exact: true }).first().click()
  199. const preview = window.locator(".paas-preview")
  200. await expect(preview.locator("pre")).toHaveText("Saved from native IPC")
  201. await preview.getByRole("button", { name: "保存文件", exact: true }).click()
  202. await expect(preview.getByText(/已保存/)).toBeVisible()
  203. await window.screenshot({ path: path.join(root, "native-preview.png") })
  204. await window.keyboard.press("Escape")
  205. await expect(preview).toHaveCount(0)
  206. await window.getByRole("button", { name: "导出报告", exact: true }).click()
  207. await expect(window.getByText("已导出 research-report.md", { exact: true })).toBeVisible()
  208. if ((await fs.readFile(report, "utf8")) !== run.output) throw new Error("Exported report mismatch")
  209. await expect(window.getByRole("button", { name: "打开保存位置", exact: true }).first()).toBeVisible()
  210. await window.getByRole("button", { name: "基于此方案继续", exact: true }).click()
  211. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("")
  212. await expect(window.getByLabel("已引用研究报告")).toContainText(run.output)
  213. await window.getByRole("button", { name: "阅读与对比", exact: true }).click()
  214. await window.getByRole("button", { name: "导出 Word", exact: true }).click()
  215. await expect(window.getByRole("dialog").getByText("已导出 research-report.docx", { exact: true })).toBeVisible()
  216. const word = await fs.readFile(report.replace(/\.md$/, ".docx"))
  217. if (word.subarray(0, 2).toString() !== "PK") throw new Error("Invalid DOCX container")
  218. await window.getByRole("button", { name: "导出 PDF", exact: true }).click()
  219. await expect(window.getByRole("dialog").getByText("已导出 research-report.pdf", { exact: true })).toBeVisible()
  220. const pdf = await fs.readFile(report.replace(/\.md$/, ".pdf"))
  221. if (pdf.subarray(0, 5).toString() !== "%PDF-") throw new Error("Invalid PDF")
  222. await app.evaluate(({ dialog }) => {
  223. dialog.showSaveDialog = async () => ({ canceled: true })
  224. })
  225. await window.getByRole("button", { name: "导出 Word", exact: true }).click()
  226. await expect(window.getByRole("dialog").getByText("已取消导出,报告仍保留。", { exact: true })).toBeVisible()
  227. if (!(await fs.readFile(report.replace(/\.md$/, ".docx"))).equals(word))
  228. throw new Error("Cancelled export changed original file")
  229. await window.keyboard.press("Escape")
  230. const execute = calls.filter((c) => c.path.endsWith("/run/stream"))
  231. if (execute.length !== 1 || JSON.parse(execute[0].body).input_files[0].file_id !== "native_file")
  232. throw new Error("Task/file binding mismatch")
  233. if (!calls.some((c) => c.path === "/api/v1/files" && c.body === "Native desktop research material"))
  234. throw new Error("Upload bytes mismatch")
  235. if (errors.length) throw new Error(errors.join("\n"))
  236. await window.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
  237. await window.getByRole("button", { name: "预览 research-report.pdf", exact: true }).click()
  238. await expect(window.locator(".paas-preview iframe")).toBeVisible()
  239. await expect(window.locator(".paas-preview iframe")).toHaveAttribute("src", /^blob:/)
  240. // Chromium's PDF viewer paints after the iframe is attached.
  241. await window.waitForTimeout(1000)
  242. await window.screenshot({ path: path.join(root, "native-pdf-preview.png") })
  243. await window.keyboard.press("Escape")
  244. await window.screenshot({ path: path.join(root, "native-success.png"), fullPage: true })
  245. await app.evaluate(({ Menu }) => {
  246. Menu.getApplicationMenu()
  247. .items.flatMap((item) => item.submenu?.items || [])
  248. .find((item) => item.label === "Settings")
  249. .click()
  250. })
  251. await expect(window.getByRole("heading", { name: "平台连接", exact: true })).toBeVisible()
  252. await expect(window.locator(".paas-code-host")).toBeHidden()
  253. await app.evaluate(({ Menu }) => {
  254. Menu.getApplicationMenu()
  255. .items.flatMap((item) => item.submenu?.items || [])
  256. .find((item) => item.label === "New Session")
  257. .click()
  258. })
  259. await expect(window.getByRole("textbox", { name: "消息", exact: true })).toBeVisible()
  260. console.log(
  261. JSON.stringify({
  262. status: "passed",
  263. packaged: await app.evaluate(({ app }) => app.isPackaged),
  264. root,
  265. requests: calls.length,
  266. modelCalls: 0,
  267. notes: "Actual packaged Electron/preload/IPC and file IO; synthetic API; native dialog selection stubbed",
  268. }),
  269. )
  270. } catch (error) {
  271. if (app) {
  272. const win = await app.firstWindow()
  273. console.log("PAGE", await win.locator("body").innerText())
  274. await win.screenshot({ path: path.join(root, "native-failure.png"), fullPage: true })
  275. }
  276. console.log("REQUESTS", JSON.stringify(calls))
  277. throw error
  278. } finally {
  279. if (app) await app.close()
  280. await new Promise((resolve) => server.close(resolve))
  281. }
  282. })().catch((e) => {
  283. console.error(e)
  284. process.exitCode = 1
  285. })