conversation-session-dynamic-workflow-gray-always-on-restart.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  4. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  5. import { TID_LOGIN_USE_API_KEY_BUTTON, TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  6. import { DEFAULT_WORKSPACE, clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  7. import {
  8. approveV4Permission,
  9. getV4PaneSnapshot,
  10. loginWithApiKey,
  11. prepareV4ConversationE2E,
  12. selectV4TaskById,
  13. sendV4Prompt,
  14. waitForV4AssistantMessageContaining,
  15. waitForV4Pane,
  16. } from "#e2e/helpers/v4-conversation";
  17. // 重启与重载(docs/dynamic-workflow/presentation.md「Cold replay」「Joining cards to runs」、
  18. // docs/dynamic-workflow/transcript-and-notifications.md「The pipeline and cold restore」「What a run
  19. // leaves behind」、apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Engine ownership」)
  20. // 的三条桌面链路:
  21. // - renderer 重载不碰 Host 与 CLI:run 继续跑,重载后卡仍是 running,并且自己走到终态;
  22. // - 完整重启 Electron / Host / CLI:已完成的 run 由 CLI 冷回放进投影,卡、完成卡与侧板与重启前一致;
  23. // - 完整重启时 run 还在跑:App 关闭前引擎自己写下 stopped(interrupted),终态通知随运行时关闭被丢弃,
  24. // 重开后经冷回放显示为已停止、可恢复,且没有终态通知行。
  25. //
  26. // case-local 回放只决定主模型与子代理的回答;Skill、编译、审批、引擎、关闭收口与冷回放都走产品链路。
  27. // 运行 A 停在一个只看放行文件的 `world.run("node", …)` 上,由测试写文件放行,不靠定时等待。
  28. const RELEASE_FILE = join(DEFAULT_WORKSPACE, ".e2e-dwp-release");
  29. const DIGEST = '[data-workflow-run-digest="true"]';
  30. const NOTIFICATION_ROW = '[data-testid^="chat-workflow-notification-row-"]';
  31. const COMPLETION_CARD = '[data-workflow-completion-card="true"]';
  32. interface DigestSnapshot {
  33. runId: string | null;
  34. status: string | null;
  35. kind: string;
  36. stations: { status: string | null; text: string }[];
  37. pills: { status: string | null; text: string }[];
  38. }
  39. interface CompletedSurfaces {
  40. digest: DigestSnapshot;
  41. notification: string;
  42. figures: Record<string, string>;
  43. phases: { id: string | null; status: string | null; text: string }[];
  44. }
  45. let sessionA = "";
  46. let runA = "";
  47. let completedBefore: CompletedSurfaces | undefined;
  48. function digestFor(runId: string) {
  49. return `${DIGEST}[data-workflow-run-id="${runId}"]`;
  50. }
  51. function readDigest(runId: string): Promise<DigestSnapshot | null> {
  52. return browser.execute((selector) => {
  53. const root = document.querySelector<HTMLElement>(selector);
  54. if (!root) return null;
  55. const text = (element: Element | null) =>
  56. ((element as HTMLElement | null)?.innerText ?? "").replace(/\s+/g, " ").trim();
  57. return {
  58. runId: root.dataset.workflowRunId ?? null,
  59. status: root.dataset.workflowRunStatus ?? null,
  60. kind: text(root.querySelector('[data-testid="workflow-card-kind"]')),
  61. stations: Array.from(
  62. root.querySelectorAll<HTMLElement>('[data-testid="workflow-timeline-station"]'),
  63. ).map((station) => ({ status: station.dataset.stationStatus ?? null, text: text(station) })),
  64. pills: Array.from(
  65. root.querySelectorAll<HTMLElement>('[data-testid="workflow-agent-pill"]'),
  66. ).map((pill) => ({ status: pill.dataset.agentStatus ?? null, text: text(pill) })),
  67. };
  68. }, digestFor(runId));
  69. }
  70. async function waitForDigest(
  71. runId: string,
  72. accept: (snapshot: DigestSnapshot) => boolean,
  73. timeoutMsg: string,
  74. timeout = 120_000,
  75. ): Promise<DigestSnapshot> {
  76. let latest: DigestSnapshot | null = null;
  77. await browser.waitUntil(
  78. async () => {
  79. latest = await readDigest(runId);
  80. return latest !== null && accept(latest);
  81. },
  82. { timeout, timeoutMsg: `${timeoutMsg};最后一次读到 ${JSON.stringify(latest)}` },
  83. );
  84. return latest!;
  85. }
  86. /** 卡上最新一张 run 卡的 run id(本会话只有一张)。 */
  87. async function waitForOnlyRunId(): Promise<string> {
  88. let runId: string | null = null;
  89. await browser.waitUntil(
  90. async () => {
  91. runId = await browser.execute((selector) => {
  92. const cards = document.querySelectorAll<HTMLElement>(selector);
  93. return cards.length === 1 ? (cards[0]!.dataset.workflowRunId ?? null) : null;
  94. }, DIGEST);
  95. return Boolean(runId);
  96. },
  97. { timeout: 120_000, timeoutMsg: "会话里没有长出唯一一张带 run id 的 run 卡" },
  98. );
  99. return runId!;
  100. }
  101. /** 重开 run 侧板(⤢),读出阶段列表与状态行。 */
  102. async function readRunPane(runId: string) {
  103. await $(digestFor(runId)).$('[data-testid="workflow-card-open-details"]').click();
  104. await $('[data-testid="workflow-run-status-row"]').waitForDisplayed({ timeout: 60_000 });
  105. await $('[data-testid="workflow-run-phase"]').waitForExist({ timeout: 60_000 });
  106. return browser.execute(() => {
  107. const text = (element: Element | null) =>
  108. ((element as HTMLElement | null)?.innerText ?? "").replace(/\s+/g, " ").trim();
  109. const toggle = (phase: HTMLElement) =>
  110. phase.querySelector('[data-testid="workflow-run-phase-toggle"]');
  111. return {
  112. status: text(document.querySelector('[data-testid="workflow-run-status-row"]')),
  113. reason: text(document.querySelector('[data-testid="workflow-run-status-reason"]')),
  114. resumable: Boolean(document.querySelector('[data-testid="workflow-run-status-resumable"]')),
  115. phases: Array.from(
  116. document.querySelectorAll<HTMLElement>('[data-testid="workflow-run-phase"]'),
  117. ).map((phase) => ({
  118. id: phase.dataset.phaseId ?? null,
  119. status: phase.dataset.phaseStatus ?? null,
  120. text: text(toggle(phase)),
  121. })),
  122. };
  123. });
  124. }
  125. async function readCompletedSurfaces(runId: string): Promise<CompletedSurfaces> {
  126. const digest = await waitForDigest(
  127. runId,
  128. (snapshot) => snapshot.status === "completed" && snapshot.stations.length > 0,
  129. "run 卡没有显示为已完成",
  130. );
  131. const row = $(NOTIFICATION_ROW);
  132. await row.waitForDisplayed({ timeout: 60_000 });
  133. const card = $(COMPLETION_CARD);
  134. await card.waitForDisplayed({ timeout: 60_000 });
  135. // 四格数字刚挂载时会从 0 翻上来(640 ms,prefers-reduced-motion: no-preference 下);
  136. // 首轮在翻动中途取值,读到的是半程数。等相邻两次读数一致,读的才是终值。
  137. let figures: Record<string, string> = {};
  138. let previous = "";
  139. await browser.waitUntil(
  140. async () => {
  141. figures = await browser.execute((selector) => {
  142. const root = document.querySelector(selector);
  143. const values: Record<string, string> = {};
  144. for (const key of ["time", "tokens", "subagents", "phases"]) {
  145. values[key] =
  146. root
  147. ?.querySelector<HTMLElement>(`[data-testid="workflow-completion-figure-${key}"]`)
  148. ?.getAttribute("data-value") ?? "—";
  149. }
  150. return values;
  151. }, COMPLETION_CARD);
  152. const current = JSON.stringify(figures);
  153. const settled = current === previous;
  154. previous = current;
  155. return settled;
  156. },
  157. { timeout: 30_000, interval: 1_000, timeoutMsg: "完成卡的四格数字没有停下来" },
  158. );
  159. const pane = await readRunPane(runId);
  160. return { digest, notification: await row.getText(), figures, phases: pane.phases };
  161. }
  162. /** renderer 重载:Host 与 CLI 不动,只换一份新的 renderer。 */
  163. async function reloadRenderer(sessionId: string) {
  164. await browser.refresh();
  165. const login = $(`[data-testid="${TID_LOGIN_USE_API_KEY_BUTTON}"]`);
  166. const task = $(`[data-testid="${testId(TID_TASK_ITEM, sessionId)}"]`);
  167. await browser.waitUntil(async () => (await login.isDisplayed()) || (await task.isExisting()), {
  168. timeout: 60_000,
  169. timeoutMsg: "renderer 重载后既没有登录页也没有任务项",
  170. });
  171. if (await login.isDisplayed()) await loginWithApiKey();
  172. // 语言固定只在内存里;新 renderer 要重新固定。
  173. await pinE2ELocale("zh-CN");
  174. await reopenSession(sessionId);
  175. }
  176. /** 完整重启:Electron、Host 与 CLI 都换新进程,会话只能从持久数据冷物化。 */
  177. async function relaunchApp(sessionId: string) {
  178. await reloadElectronSessionSafely(browser);
  179. await pinE2ELocale("zh-CN");
  180. await reopenSession(sessionId);
  181. }
  182. async function reopenSession(sessionId: string) {
  183. if ((await getV4PaneSnapshot()).sessionId !== sessionId) {
  184. await selectV4TaskById(sessionId, 60_000);
  185. }
  186. await waitForV4Pane(
  187. (snapshot) => snapshot.sessionId === sessionId,
  188. `没有重新打开会话 ${sessionId}`,
  189. 60_000,
  190. );
  191. }
  192. async function launchWorkflow(tag: "A" | "B", prompt: string) {
  193. await sendV4Prompt(`E2E_DWP_${tag}_START ${prompt}`);
  194. await approveV4Permission();
  195. const toolCallId = `toolu_dwp_${tag.toLowerCase()}_create`;
  196. await browser.waitUntil(
  197. async () => (await getLatestUpstreamToolResultByToolCallId(toolCallId))?.isError === false,
  198. { timeout: 60_000, timeoutMsg: `${tag}: CreateWorkflow 未执行成功` },
  199. );
  200. await waitForV4AssistantMessageContaining(`E2E_DWP_${tag}_STARTED`, 60_000);
  201. const sessionId = (await getV4PaneSnapshot()).sessionId;
  202. if (!sessionId || sessionId === "draft") throw new Error(`${tag}: 没有真实 sessionId`);
  203. return { sessionId, runId: await waitForOnlyRunId() };
  204. }
  205. describe("动态工作流 · 重启与重载", () => {
  206. before(async () => {
  207. await rm(RELEASE_FILE, { force: true });
  208. await prepareV4ConversationE2E();
  209. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  210. await pinE2ELocale("zh-CN");
  211. });
  212. after(async () => {
  213. await rm(RELEASE_FILE, { force: true });
  214. await browser.electron.restoreAllMocks();
  215. await clearAppData();
  216. });
  217. it("DWP-01 renderer 重载时 run 在跑:重载后卡仍是 running,放行后自己走到已完成并长出通知与完成卡", async function () {
  218. this.timeout(360_000);
  219. ({ sessionId: sessionA, runId: runA } = await launchWorkflow(
  220. "A",
  221. "使用工作流:记录员先写一句记录,再等待放行。",
  222. ));
  223. // 子代理答完、run 停在第二站的 world.run 上:此时重载才是「run 在跑」。
  224. const running = await waitForDigest(
  225. runA,
  226. (snapshot) => snapshot.status === "running" && snapshot.stations[1]?.status === "running",
  227. "run 没有停在「等待放行」站上",
  228. );
  229. expect(running.stations[0]?.text).toContain("准备");
  230. expect(running.pills.some((pill) => pill.text.includes("记录员"))).toBe(true);
  231. await reloadRenderer(sessionA);
  232. const afterReload = await waitForDigest(
  233. runA,
  234. (snapshot) => snapshot.status === "running" && snapshot.stations.length > 0,
  235. "renderer 重载后 run 卡没有显示为 running",
  236. 60_000,
  237. );
  238. expect(afterReload.stations.map((station) => station.status)).toEqual(
  239. running.stations.map((station) => station.status),
  240. );
  241. await expect($$(NOTIFICATION_ROW)).toBeElementsArrayOfSize(0);
  242. // 放行:run 不需要任何用户动作就走到终态;终态通知唤醒主代理,回复尾部长出完成卡。
  243. await writeFile(RELEASE_FILE, "go\n");
  244. await waitForDigest(
  245. runA,
  246. (snapshot) => snapshot.status === "completed",
  247. "放行后 run 卡没有走到已完成",
  248. );
  249. await waitForV4AssistantMessageContaining("E2E_DWP_A_DONE", 120_000);
  250. await waitForV4Pane((pane) => !pane.canStop, "终态通知轮没有结束", 60_000);
  251. const row = $(NOTIFICATION_ROW);
  252. await row.waitForDisplayed({ timeout: 60_000 });
  253. expect(await row.getText()).toContain("工作流已完成");
  254. await $(COMPLETION_CARD).waitForDisplayed({ timeout: 60_000 });
  255. });
  256. it("DWP-02 完整重启后冷回放:run 卡、通知行、完成卡与侧板阶段和重启前一致", async function () {
  257. this.timeout(300_000);
  258. if (!sessionA || !runA) throw new Error("DWP-01 没有留下会话与 run");
  259. completedBefore = await readCompletedSurfaces(runA);
  260. expect(completedBefore.digest.stations.map((station) => station.text).join(" ")).toContain(
  261. "等待放行",
  262. );
  263. expect(completedBefore.digest.pills.map((pill) => pill.text).join(" ")).toContain("记录员");
  264. expect(completedBefore.phases.length).toBeGreaterThanOrEqual(2);
  265. // 阶段格是进入过的阶段数,子代理格是 actors 数(docs「Where the numbers come from」)。
  266. expect(completedBefore.figures.phases).toBe("2");
  267. expect(completedBefore.figures.subagents).toBe("1");
  268. await relaunchApp(sessionA);
  269. const after = await readCompletedSurfaces(runA);
  270. expect(after.digest).toEqual(completedBefore.digest);
  271. expect(after.notification).toBe(completedBefore.notification);
  272. expect(after.figures).toEqual(completedBefore.figures);
  273. expect(after.phases).toEqual(completedBefore.phases);
  274. // 冷回放不给已完成的 run 补出恢复按钮或 Stop。
  275. await expect($(digestFor(runA)).$('[data-testid="workflow-digest-resume"]')).not.toBeExisting();
  276. });
  277. it("DWP-03 完整重启时 run 在跑:重开后 run 已停止(进程已退出)、可恢复,且没有终态通知行", async function () {
  278. this.timeout(360_000);
  279. await prepareV4ConversationE2E();
  280. const { sessionId, runId } = await launchWorkflow("B", "使用工作流:长时间等待。");
  281. await waitForDigest(
  282. runId,
  283. (snapshot) => snapshot.status === "running" && snapshot.stations[0]?.status === "running",
  284. "run B 没有进入 running",
  285. );
  286. // App 关闭前引擎自己写下 stopped(interrupted);运行时已在关闭,终态通知被丢弃,不唤醒模型。
  287. await relaunchApp(sessionId);
  288. const stopped = await waitForDigest(
  289. runId,
  290. (snapshot) => snapshot.status === "stopped",
  291. "重启后 run B 没有显示为已停止",
  292. );
  293. expect(stopped.kind).toContain("已停止");
  294. await expect($(digestFor(runId)).$('[data-testid="workflow-digest-resume"]')).toBeDisplayed();
  295. const pane = await readRunPane(runId);
  296. expect(pane.status).toContain("已停止");
  297. expect(pane.reason).toContain("进程已退出");
  298. expect(pane.resumable).toBe(true);
  299. await expect($$(NOTIFICATION_ROW)).toBeElementsArrayOfSize(0);
  300. expect((await getV4PaneSnapshot()).canStop).toBe(false);
  301. });
  302. });