conversation-session-runtime-restart.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import { chromium, type Browser, type Page } from "playwright-core";
  2. import { createServer, type Server } from "node:http";
  3. import type { AddressInfo } from "node:net";
  4. import { basename, join } from "node:path";
  5. import {
  6. TID_WORKSPACE_MORE_BUTTON,
  7. TID_TASK_ITEM,
  8. TID_V4_COMPOSER_INPUT,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import {
  12. getUpstreamRequestRecordCount,
  13. getUpstreamRequestEvidence,
  14. } from "#e2e/helpers/conversation-session-network";
  15. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  16. import { obtainUnreadPairingUrl } from "#e2e/helpers/web-remote-unread";
  17. import { DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  18. import { clearAppData } from "#e2e/helpers/desktop-app";
  19. import {
  20. waitForUpstreamNetworkCapture,
  21. waitForUpstreamNetworkRequestStarted,
  22. } from "#e2e/helpers/upstream-capture";
  23. import {
  24. prepareV4ConversationE2E,
  25. sendV4Prompt,
  26. waitForV4ConversationState,
  27. waitForV4ComposerText,
  28. getV4ConversationState,
  29. setV4ComposerText,
  30. getV4Messages,
  31. getV4ComposerAttachments,
  32. getV4ComposerBackgroundWorkCounts,
  33. pasteV4ComposerImageAttachment,
  34. E2E_REPLY_TOKEN,
  35. waitForV4AssistantMessageContaining,
  36. waitForV4PermissionDialog,
  37. approveV4Permission,
  38. } from "#e2e/helpers/v4-conversation";
  39. describe("单任务运行实例重启", () => {
  40. let webBrowser: Browser | undefined;
  41. let mobile: Page | undefined;
  42. let fixtureServer: Server;
  43. let fixtureUrl: string;
  44. before(async () => {
  45. fixtureServer = createServer((_request, response) => {
  46. response.setHeader("content-type", "text/html; charset=utf-8");
  47. response.end(
  48. '<!doctype html><title>Session Browser Restart</title><label>State <input id="state"></label>',
  49. );
  50. });
  51. await new Promise<void>((resolve) => fixtureServer.listen(0, "127.0.0.1", resolve));
  52. fixtureUrl = `http://127.0.0.1:${(fixtureServer.address() as AddressInfo).port}/restart`;
  53. });
  54. after(async () => {
  55. if (mobile && process.env.ZCODE_E2E_ARTIFACT_DIR)
  56. await mobile
  57. .screenshot({ path: join(process.env.ZCODE_E2E_ARTIFACT_DIR, "SLR-mobile.png") })
  58. .catch(() => undefined);
  59. await webBrowser?.close();
  60. await browser.electron.execute((electron, url) => {
  61. for (const guest of electron.webContents.getAllWebContents()) {
  62. if (!guest.isDestroyed() && guest.getURL() === url)
  63. guest.close({ waitForBeforeUnload: false });
  64. }
  65. }, fixtureUrl);
  66. if (fixtureServer?.listening)
  67. await new Promise<void>((resolve, reject) =>
  68. fixtureServer.close((error) => (error ? reject(error) : resolve())),
  69. );
  70. await browser.electron.restoreAllMocks();
  71. await clearAppData();
  72. });
  73. it("SLR01–03/05/06/09–11 菜单、/reload 与手机重启保留历史和网页,关闭所属工作", async function () {
  74. this.timeout(480000);
  75. await prepareV4ConversationE2E();
  76. const marker = `E2E_SESSION_RESTART_${Date.now()}`;
  77. await sendV4Prompt(`${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`);
  78. await waitForUpstreamNetworkCapture(marker);
  79. await waitForV4ConversationState((s) => s.state === "idle", "首轮未完成", 90000);
  80. const sessionId = (await getV4ConversationState()).taskId;
  81. if (!sessionId) throw new Error("缺少持久任务身份");
  82. const selector = `[data-session-id="${sessionId}"]`;
  83. const pairingUrl = await obtainUnreadPairingUrl(
  84. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  85. );
  86. webBrowser = await chromium.launch({
  87. executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE,
  88. headless: true,
  89. args: ["--no-sandbox"],
  90. });
  91. const context = await webBrowser.newContext({
  92. viewport: { width: 390, height: 844 },
  93. isMobile: true,
  94. hasTouch: true,
  95. locale: "zh-CN",
  96. });
  97. await seedMobileFixtureLogin(context);
  98. mobile = await context.newPage();
  99. const project = `[data-project-name="${basename(DEFAULT_WORKSPACE)}"]`;
  100. await openMobilePairingPage(mobile, pairingUrl, {
  101. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  102. caseMarker: "SLR03",
  103. phase: "restart",
  104. readySelector: project,
  105. });
  106. const toggle = mobile.locator(project).getByTestId("virtual-project-toggle");
  107. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.tap();
  108. await mobile.getByTestId(testId(TID_TASK_ITEM, sessionId)).first().tap();
  109. await mobile.locator(selector).waitFor();
  110. await browser.execute(observeLifecycleBanners);
  111. await mobile.evaluate(observeLifecycleBanners);
  112. // 标题入口保留已有草稿;两个真实客户端都必须切到新实例。
  113. await setV4ComposerText("重启期间保留的草稿");
  114. await $(`[data-testid="${TID_WORKSPACE_MORE_BUTTON}"]`).click();
  115. // 必须确实命中标题仍在飞的窗口,不能把正常结束后的重启算作取消覆盖。
  116. const titleRequests = await getUpstreamRequestEvidence({
  117. includeTitle: true,
  118. includes: [marker, "Generate a concise title"],
  119. });
  120. expect(titleRequests).toHaveLength(1);
  121. expect(titleRequests[0]?.status).toBe("pending");
  122. expect(titleRequests[0]?.fixtureId).toBe("conversation-session-stop-empty-title-sidecar");
  123. await $('[data-testid="task-restart"]').click();
  124. await browser.waitUntil(
  125. async () =>
  126. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  127. Number(await $(selector).getAttribute("data-session-generation")) >= 2,
  128. { timeout: 60000 },
  129. );
  130. await waitForV4ComposerText("重启期间保留的草稿", "菜单重启丢失草稿");
  131. await mobile.waitForFunction((query) => {
  132. const pane = document.querySelector(query);
  133. return (
  134. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  135. Number(pane.getAttribute("data-session-generation")) >= 2
  136. );
  137. }, selector);
  138. // AppSlashCommand 是操作菜单:正文与附件不作为参数,不应隐藏重启选项。
  139. const userRows = await getV4Messages("user");
  140. const requestsBeforeReload = await getUpstreamRequestRecordCount();
  141. await pasteV4ComposerImageAttachment("e2e-reload-draft.png");
  142. await browser.waitUntil(
  143. async () => (await getV4ComposerAttachments())[0]?.uploadStatus === "ready",
  144. { timeout: 30000 },
  145. );
  146. const attachments = await getV4ComposerAttachments();
  147. await setV4ComposerText("保留正文 /reload");
  148. const reloadOption = $('[data-option-id="app-slash:reload"]');
  149. await reloadOption.waitForDisplayed({ timeout: 10000 });
  150. expect(await reloadOption.getText()).toContain("/reload");
  151. expect(await reloadOption.getText()).toContain(
  152. "Reload the task runtime, preserving history and stopping current execution.",
  153. );
  154. await reloadOption.click();
  155. await browser.waitUntil(
  156. async () =>
  157. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  158. Number(await $(selector).getAttribute("data-session-generation")) >= 3,
  159. { timeout: 60000 },
  160. );
  161. await waitForV4ComposerText("保留正文 ", "面板重启没有保留正文");
  162. expect(await getV4ComposerAttachments()).toEqual(attachments);
  163. expect(await getV4Messages("user")).toEqual(userRows);
  164. await setV4ComposerText("键盘保留正文 /reload");
  165. await reloadOption.waitForDisplayed({ timeout: 10000 });
  166. await browser.keys("Enter");
  167. await browser.waitUntil(
  168. async () =>
  169. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  170. Number(await $(selector).getAttribute("data-session-generation")) >= 4,
  171. { timeout: 60000 },
  172. );
  173. await waitForV4ComposerText("键盘保留正文 ", "键盘选择重启没有保留正文");
  174. expect(await getV4ComposerAttachments()).toEqual(attachments);
  175. await $("[data-composer-attachment-remove]").click();
  176. await setV4ComposerText("");
  177. await sendV4Prompt("/reload");
  178. await waitForV4ComposerText("", "本地重启命令未消费");
  179. await browser.waitUntil(
  180. async () => {
  181. const current = await $(selector);
  182. return (
  183. (await current.getAttribute("data-session-id")) === sessionId &&
  184. (await current.getAttribute("data-session-lifecycle")) === "ready" &&
  185. Number(await current.getAttribute("data-session-generation")) >= 5
  186. );
  187. },
  188. { timeout: 60000, timeoutMsg: "同一任务的新实例没有就绪" },
  189. );
  190. await mobile.waitForFunction((query) => {
  191. const pane = document.querySelector(query);
  192. return (
  193. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  194. Number(pane.getAttribute("data-session-generation")) >= 5
  195. );
  196. }, selector);
  197. // 手机使用真实触屏选择同一 AppSlashCommand;草稿属于手机,不应同步到桌面。
  198. const mobileInput = mobile.getByTestId(TID_V4_COMPOSER_INPUT);
  199. await mobileInput.fill("手机保留正文 /reload");
  200. const mobileReload = mobile.locator('[data-option-id="app-slash:reload"]');
  201. await mobileReload.waitFor();
  202. expect(await mobileReload.innerText()).toContain("/reload");
  203. expect(await mobileReload.innerText()).toContain(
  204. "Reload the task runtime, preserving history and stopping current execution.",
  205. );
  206. await mobileReload.tap();
  207. await mobile.waitForFunction((query) => {
  208. const pane = document.querySelector(query);
  209. return (
  210. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  211. Number(pane.getAttribute("data-session-generation")) >= 6
  212. );
  213. }, selector);
  214. expect(await mobileInput.innerText()).toBe("手机保留正文 ");
  215. await mobileInput.fill("");
  216. await browser.waitUntil(
  217. async () =>
  218. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  219. Number(await $(selector).getAttribute("data-session-generation")) >= 6,
  220. { timeout: 60000 },
  221. );
  222. expect(await getV4Messages("user")).toEqual(userRows);
  223. expect(await getUpstreamRequestRecordCount()).toBe(requestsBeforeReload);
  224. // 真实运行中的模型流和队列都属于旧实例;由手机发起重启,桌面被动恢复。
  225. await sendV4Prompt(`E2E_SESSION_RESTART_RUNNING: Keep streaming until cancelled.`);
  226. await waitForUpstreamNetworkRequestStarted("E2E_SESSION_RESTART_RUNNING");
  227. await waitForV4ConversationState((s) => s.state === "streaming", "没有进入生成中", 30000);
  228. await sendV4Prompt("E2E_SESSION_RESTART_QUEUED: this input must be discarded by restart.");
  229. await waitForV4ConversationState((s) => s.queueCount === 1, "输入没有排队", 30000);
  230. await mobile.getByTestId(TID_WORKSPACE_MORE_BUTTON).tap();
  231. await mobile.getByTestId("task-restart").tap();
  232. await browser.waitUntil(
  233. async () =>
  234. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  235. Number(await $(selector).getAttribute("data-session-generation")) >= 7,
  236. { timeout: 60000 },
  237. );
  238. await waitForV4ConversationState(
  239. (s) => s.state === "idle" && s.queueCount === 0,
  240. "重启后旧执行或队列仍然活跃",
  241. 30000,
  242. );
  243. await mobile.waitForFunction((query) => {
  244. const pane = document.querySelector(query);
  245. return (
  246. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  247. Number(pane.getAttribute("data-session-generation")) >= 7
  248. );
  249. }, selector);
  250. const next = `${marker}_NEXT`;
  251. await sendV4Prompt(`${next}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`);
  252. const nextRequest = await waitForUpstreamNetworkCapture(next);
  253. expect(JSON.stringify(nextRequest.requestJson)).not.toContain("/reload");
  254. expect(JSON.stringify(nextRequest.requestJson)).not.toContain("E2E_SESSION_RESTART_QUEUED");
  255. await waitForV4ConversationState((s) => s.state === "idle", "重启后续发失败", 90000);
  256. await expect($("body")).toHaveText(expect.stringContaining(marker));
  257. // 父 turn 已结束不代表后台子代理已结束;两种客户端入口都必须关闭它。
  258. for (const [index, source] of ["desktop", "mobile"].entries()) {
  259. const ownerMarker = `E2E_OWNED_RESTART_${source.toUpperCase()}`;
  260. await sendV4Prompt(`${ownerMarker}: start the requested background agent.`);
  261. await waitForUpstreamNetworkRequestStarted(`${ownerMarker}_CHILD`);
  262. await waitForV4ConversationState((state) => state.state === "idle", "父任务未结束", 60000);
  263. await browser.waitUntil(
  264. async () => (await getV4ComposerBackgroundWorkCounts())?.subagentCount === 1,
  265. { timeout: 30000, timeoutMsg: "后台子代理未保持运行" },
  266. );
  267. // row id 是投影序号,重建快照后可变化;验证用户可见正文及顺序。
  268. const history = (await getV4Messages("user")).map(({ text }) => text);
  269. if (source === "desktop") {
  270. await $(`[data-testid="${TID_WORKSPACE_MORE_BUTTON}"]`).click();
  271. await $('[data-testid="task-restart"]').click();
  272. } else {
  273. await mobile.getByTestId(TID_WORKSPACE_MORE_BUTTON).tap();
  274. await mobile.getByTestId("task-restart").tap();
  275. }
  276. const generation = 8 + index;
  277. await browser.waitUntil(
  278. async () =>
  279. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  280. Number(await $(selector).getAttribute("data-session-generation")) >= generation,
  281. { timeout: 60000, timeoutMsg: "所属工作关闭后未恢复" },
  282. );
  283. await browser.waitUntil(
  284. async () => ((await getV4ComposerBackgroundWorkCounts())?.subagentCount ?? 0) === 0,
  285. { timeout: 30000, timeoutMsg: "重启后仍显示运行中的子代理" },
  286. );
  287. await mobile.waitForFunction(
  288. ({ query, generation }) => {
  289. const pane = document.querySelector(query);
  290. const counter = pane?.querySelector("[data-background-subagent-count]");
  291. return (
  292. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  293. Number(pane.getAttribute("data-session-generation")) >= generation &&
  294. Number(counter?.getAttribute("data-background-subagent-count") ?? 0) === 0
  295. );
  296. },
  297. { query: selector, generation },
  298. );
  299. expect((await getV4Messages("user")).map(({ text }) => text)).toEqual(history);
  300. const previousReply = (await getV4Messages("assistant")).at(-1)?.id;
  301. await sendV4Prompt(`${marker}_NEXT: Reply with exactly "${E2E_REPLY_TOKEN}".`);
  302. // 发送入队之前也可能短暂 idle;必须观察新回复,不能把旧 idle 当作续发完成。
  303. await browser.waitUntil(
  304. async () => {
  305. const reply = (await getV4Messages("assistant")).at(-1);
  306. return Boolean(
  307. reply && reply.id !== previousReply && reply.text.includes(E2E_REPLY_TOKEN),
  308. );
  309. },
  310. { timeout: 60000, timeoutMsg: "关闭子代理后没有收到新回复" },
  311. );
  312. await waitForV4ConversationState(
  313. (state) => state.state === "idle",
  314. "关闭子代理后不能续发",
  315. 60000,
  316. );
  317. }
  318. // 三次真实 Browser JS 调用跨过桌面、手机重启,证明网页保留且新实例能继续控制。
  319. let guestId: number | undefined;
  320. for (const source of ["desktop", "mobile", "after"] as const) {
  321. const browserMarker = `E2E_BROWSER_RESTART_${source.toUpperCase()}`;
  322. await sendV4Prompt(
  323. `${browserMarker}: use the browser. E2E_BROWSER_FIXTURE_URL:${fixtureUrl}`,
  324. );
  325. await waitForV4PermissionDialog();
  326. await approveV4Permission();
  327. await waitForV4AssistantMessageContaining(`${browserMarker}_DONE`, 90000);
  328. await waitForV4ConversationState(
  329. (state) => state.state === "idle",
  330. "浏览器操作未完成",
  331. 60000,
  332. );
  333. const before = await readRestartBrowser(fixtureUrl);
  334. expect(before).toHaveLength(1);
  335. expect(before[0]?.value).toBe(source);
  336. if (guestId !== undefined) expect(before[0]?.id).toBe(guestId);
  337. guestId = before[0]?.id;
  338. if (source === "desktop") {
  339. // 必须在重启/释放之前续发;显式重新认领 user tab 无法覆盖受控页的 ambient 查询。
  340. const ambientMarker = "E2E_BROWSER_AMBIENT_NEXT";
  341. await sendV4Prompt(`${ambientMarker}: report browser context.`);
  342. await waitForV4AssistantMessageContaining(`${ambientMarker}_DONE`, 60000);
  343. await waitForV4ConversationState(
  344. (state) => state.state === "idle",
  345. "ambient 续发未完成",
  346. 60000,
  347. );
  348. await waitForUpstreamNetworkCapture(ambientMarker);
  349. const requests = await getUpstreamRequestEvidence({
  350. lastUserMessageIncludes: [ambientMarker],
  351. });
  352. const request = requests.find((entry) => entry.fixtureId === "browser-ambient-next");
  353. expect(request).toBeDefined();
  354. const wire = JSON.stringify(request!.requestJson);
  355. expect(wire).toContain("ambient-ui-state");
  356. expect(wire).toContain("browser open with 1 tab");
  357. expect(wire).toContain(`Current URL: ${fixtureUrl}`);
  358. expect(await readRestartBrowser(fixtureUrl)).toEqual(before);
  359. }
  360. if (source === "after") break;
  361. const generation = Number(await $(selector).getAttribute("data-session-generation"));
  362. if (source === "desktop") {
  363. await $(`[data-testid="${TID_WORKSPACE_MORE_BUTTON}"]`).click();
  364. await $('[data-testid="task-restart"]').click();
  365. } else {
  366. await mobile.getByTestId(TID_WORKSPACE_MORE_BUTTON).tap();
  367. await mobile.getByTestId("task-restart").tap();
  368. }
  369. await browser.waitUntil(
  370. async () =>
  371. (await $(selector).getAttribute("data-session-lifecycle")) === "ready" &&
  372. Number(await $(selector).getAttribute("data-session-generation")) > generation,
  373. { timeout: 60000, timeoutMsg: "浏览器控制资源释放失败" },
  374. );
  375. await mobile.waitForFunction(
  376. ({ query, generation }) => {
  377. const pane = document.querySelector(query);
  378. return (
  379. pane?.getAttribute("data-session-lifecycle") === "ready" &&
  380. Number(pane.getAttribute("data-session-generation")) > generation
  381. );
  382. },
  383. { query: selector, generation },
  384. );
  385. expect(await readRestartBrowser(fixtureUrl)).toEqual(before);
  386. }
  387. await setV4ComposerText("/plan");
  388. const planOption = $('[data-option-id="app-slash:plan"]');
  389. await planOption.waitForDisplayed();
  390. expect(await planOption.getText()).toContain("/plan");
  391. await browser.keys("Escape");
  392. await setV4ComposerText("");
  393. expect(await browser.execute(readLifecycleBannerCount)).toBe(0);
  394. expect(await mobile.evaluate(readLifecycleBannerCount)).toBe(0);
  395. for (const theme of ["light", "dark"]) {
  396. await browser.execute((value) => {
  397. const actions = (
  398. window as typeof window & { __testActions?: { setTheme?: (theme: string) => void } }
  399. ).__testActions;
  400. if (!actions?.setTheme) throw new Error("缺少主题测试入口");
  401. actions.setTheme(value);
  402. }, theme);
  403. await $(`[data-testid="${TID_WORKSPACE_MORE_BUTTON}"]`).click();
  404. await $('[data-testid="task-restart"]').waitForDisplayed();
  405. await browser.saveScreenshot(
  406. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `SLR-menu-${theme}.png`),
  407. );
  408. // 模态菜单会禁用页面命中;通过真实指针点击菜单外关闭,再等待关闭状态。
  409. await browser.action("pointer").move({ x: 1100, y: 400 }).down().up().perform();
  410. await $('[data-testid="task-restart"]').waitForDisplayed({ reverse: true });
  411. await setV4ComposerText("/reload");
  412. await reloadOption.waitForDisplayed();
  413. await browser.saveScreenshot(
  414. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `SLR-reload-${theme}.png`),
  415. );
  416. await browser.keys("Escape");
  417. await setV4ComposerText("");
  418. }
  419. });
  420. });
  421. // 观察整个真实重启过程,不能只在 ready 后断言提示已消失。
  422. function observeLifecycleBanners() {
  423. const target = window as typeof window & { __lifecycleBannerCount?: number };
  424. target.__lifecycleBannerCount = 0;
  425. new MutationObserver(() => {
  426. if (document.querySelector('[data-testid="session-restarting"]'))
  427. target.__lifecycleBannerCount! += 1;
  428. }).observe(document.body, { childList: true, subtree: true });
  429. if (document.querySelector('[data-testid="session-restarting"]'))
  430. target.__lifecycleBannerCount! += 1;
  431. }
  432. function readLifecycleBannerCount() {
  433. return (window as typeof window & { __lifecycleBannerCount?: number }).__lifecycleBannerCount;
  434. }
  435. function readRestartBrowser(url: string): Promise<Array<{ id: number; value: string }>> {
  436. return browser.electron.execute(async (electron, targetUrl) => {
  437. const guests = electron.webContents
  438. .getAllWebContents()
  439. .filter((guest) => !guest.isDestroyed() && guest.getURL() === targetUrl);
  440. return await Promise.all(
  441. guests.map(async (guest) => ({
  442. id: guest.id,
  443. value: (await guest.executeJavaScript("document.querySelector('#state')?.value")) as string,
  444. })),
  445. );
  446. }, url) as unknown as Promise<Array<{ id: number; value: string }>>;
  447. }