conversation-session-automation-run-title-stable.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import {
  2. TID_AUTOMATION_CARD,
  3. TID_AUTOMATION_CREATE_MANUALLY,
  4. TID_AUTOMATION_CREATE_MENU,
  5. TID_AUTOMATION_FORM_PROMPT,
  6. TID_AUTOMATION_FORM_SUBMIT,
  7. TID_AUTOMATION_FORM_TITLE,
  8. TID_AUTOMATION_FREQUENCY_OPTION,
  9. TID_AUTOMATION_RUN_NOW,
  10. TID_AUTOMATION_SCHEDULE_ADD,
  11. TID_AUTOMATIONS_OPEN,
  12. TID_TASK_ITEM,
  13. TID_WORKSPACE_TITLE,
  14. testId,
  15. } from "@zcode/shared/test-ids";
  16. import {
  17. clearAppData,
  18. clickTestIdByDom,
  19. clickTestIdByWebDriver,
  20. seedSettings,
  21. setInputValueByTestIdDom,
  22. waitForDefaultWorkspaceReady,
  23. } from "#e2e/helpers/desktop-app";
  24. import {
  25. countUpstreamTitleRequestsContaining,
  26. getUpstreamRequestToolNames,
  27. waitForUpstreamRequest,
  28. } from "#e2e/helpers/conversation-session-network";
  29. import {
  30. prepareV4ConversationE2E,
  31. selectV4TaskById,
  32. waitForV4Pane,
  33. waitForV4TimelineContaining,
  34. } from "#e2e/helpers/v4-conversation";
  35. import { UPSTREAM_MODEL, selectUpstreamModelById } from "#e2e/helpers/upstream-provider";
  36. const INITIAL_PROMPT = "E2E_AUTOMATION_TITLE_STABLE 这条初始指令不应被执行";
  37. const RUN_PROMPT = "E2E_AUTOMATION_TITLE_STABLE 随机介绍一位红楼梦人物";
  38. const AUTOMATION_TITLE = "AUTOMATION_TITLE_STABLE_TASK";
  39. const FINAL_TOKEN = "automation-title-stable-done";
  40. const TELEMETRY_REPORT_PATH = "/api/v1/event/report";
  41. type JsonRecord = Record<string, unknown>;
  42. describe("automation run keeps the first-input session title", () => {
  43. after(async () => {
  44. await browser.electron.restoreAllMocks();
  45. await clearAppData();
  46. });
  47. it("UI 手动任务立即运行完成后不发起 session_title,标题保持原 prompt", async function () {
  48. this.timeout(150000);
  49. await waitForDefaultWorkspaceReady(90_000);
  50. // 卡片运行次数/下次运行是本 case 的可见证据;显式固定中文 locale,避免 WDIO
  51. // 继承英文系统语言后把“已运行 0 次”渲染为 “Ran 0 times”。
  52. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  53. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  54. const telemetryFetch = await browser.electron.mock("net", "fetch");
  55. await telemetryFetch.mockResolvedValue({ ok: true, status: 204 });
  56. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  57. timeoutMsg: "侧栏没有出现定时任务入口",
  58. });
  59. await clickTestIdByWebDriver(TID_AUTOMATION_CREATE_MENU, {
  60. timeoutMsg: "定时任务创建下拉没有出现",
  61. });
  62. await clickTestIdByDom(TID_AUTOMATION_CREATE_MANUALLY, {
  63. timeoutMsg: "创建下拉没有出现手动创建入口",
  64. });
  65. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_TITLE, AUTOMATION_TITLE);
  66. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_PROMPT, INITIAL_PROMPT);
  67. // 账号 mock 会提供默认 GLM;表单明确选择 case 的回放模型,不能依赖工作区默认值。
  68. await selectUpstreamModelById(UPSTREAM_MODEL, { afterModelItemClick: () => true });
  69. // 新建态默认无日程;显式添加每天,确保 case 验证的是 Run now 工具边界。
  70. await clickTestIdByWebDriver(TID_AUTOMATION_SCHEDULE_ADD, {
  71. timeoutMsg: "定时任务创建页没有添加日程入口",
  72. });
  73. await clickTestIdByDom(testId(TID_AUTOMATION_FREQUENCY_OPTION, "daily"), {
  74. timeoutMsg: "添加日程菜单没有每天选项",
  75. });
  76. await clickTestIdByDom(TID_AUTOMATION_FORM_SUBMIT, {
  77. timeoutMsg: "定时任务创建按钮不可点击",
  78. });
  79. const initialCardText = await waitForAutomationCardText(AUTOMATION_TITLE, "已运行 0 次");
  80. expect(initialCardText).toContain("下次运行");
  81. expect(initialCardText).not.toMatch(/已运行\s*0\s*\/\s*\d+\s*次/);
  82. await clickAutomationCardByTitle(AUTOMATION_TITLE);
  83. // 回归边界:编辑页 Run now 必须先保存当前未提交表单,再派发同一 payload,不能执行旧快照。
  84. await setInputValueByTestIdDom(TID_AUTOMATION_FORM_PROMPT, RUN_PROMPT);
  85. await clickTestIdByDom(TID_AUTOMATION_RUN_NOW, {
  86. timeout: 15000,
  87. timeoutMsg: "定时任务编辑页没有立即运行按钮",
  88. });
  89. const taskId = await waitForTaskItemContaining(RUN_PROMPT);
  90. await selectV4TaskById(taskId);
  91. await waitForV4TimelineContaining(RUN_PROMPT);
  92. await waitForV4TimelineContaining(FINAL_TOKEN);
  93. await waitForV4Pane(
  94. (snapshot) => snapshot.sessionId === taskId && !snapshot.canStop,
  95. "定时任务执行会话没有完成",
  96. 90000,
  97. );
  98. const telemetry = await waitForAutomationSessionTelemetry(telemetryFetch, taskId);
  99. assertAutomationSessionTelemetry(telemetry, taskId);
  100. // automation 执行轮只能读取任务定义;写工具必须在发给 provider 前被 turn-scoped
  101. // denylist 移除,避免任务在运行时自改、自删或递归创建新任务。
  102. const runRequest = { lastUserMessageIncludes: [RUN_PROMPT] };
  103. await waitForUpstreamRequest(runRequest, "没有捕获到定时任务立即运行的 provider 请求");
  104. const runToolNames = await getUpstreamRequestToolNames(runRequest);
  105. expect(runToolNames).toContain("CronList");
  106. expect(runToolNames).not.toContain("CronCreate");
  107. expect(runToolNames).not.toContain("CronUpdate");
  108. expect(runToolNames).not.toContain("CronDelete");
  109. // Bugfix 回归:旧实现会在主回复后追加 session_title 请求,并把标题改成回复里的实体。
  110. // 留出快速 sidecar 的完成窗口,再同时核对请求边界和两处用户可见标题投影。
  111. // Bug 根因:V4 task list 元数据已迁移到 taskQueryCacheStore,旧 case 仍从
  112. // zcodeSessionStore.taskListCache 读第三份副本,因此稳定得到 null 并误判产品失败。
  113. await browser.pause(1500);
  114. expect(await countUpstreamTitleRequestsContaining(RUN_PROMPT)).toBe(0);
  115. await expectHeaderTitle(RUN_PROMPT);
  116. await expectTaskItemTitle(taskId, RUN_PROMPT);
  117. await clickTestIdByDom(TID_AUTOMATIONS_OPEN, {
  118. timeoutMsg: "执行完成后无法返回定时任务列表",
  119. });
  120. const dispatchedCardText = await waitForAutomationCardText(AUTOMATION_TITLE, "已运行 1 次");
  121. expect(dispatchedCardText).toContain("下次运行");
  122. expect(dispatchedCardText).not.toMatch(/已运行\s*1\s*\/\s*\d+\s*次/);
  123. });
  124. });
  125. async function waitForAutomationSessionTelemetry(
  126. telemetryFetch: Awaited<ReturnType<typeof browser.electron.mock>>,
  127. taskId: string,
  128. ): Promise<JsonRecord[]> {
  129. let latest: JsonRecord[] = [];
  130. await browser.waitUntil(
  131. async () => {
  132. await telemetryFetch.update();
  133. latest = telemetryFetch.mock.calls
  134. .map((call) => parseTelemetryRequest(call))
  135. .filter((request): request is JsonRecord => request !== null)
  136. .filter((request) => request.talk_id === taskId);
  137. return (
  138. latest.some((request) => request.element_name === "agent_step") &&
  139. latest.some((request) => request.element_name === "session_create") &&
  140. latest.some((request) => request.element_name === "message_completion")
  141. );
  142. },
  143. {
  144. timeout: 30000,
  145. timeoutMsg: "新建定时任务立即运行后没有捕获到 agent_step / message_completion",
  146. },
  147. );
  148. return latest;
  149. }
  150. function assertAutomationSessionTelemetry(telemetry: JsonRecord[], taskId: string): void {
  151. const steps = telemetry.filter((request) => request.element_name === "agent_step");
  152. const completions = telemetry.filter((request) => request.element_name === "message_completion");
  153. const sends = telemetry.filter((request) => request.element_name === "send_btn");
  154. expect(steps.length).toBeGreaterThanOrEqual(1);
  155. expect(completions).toHaveLength(1);
  156. expect(sends).toHaveLength(0);
  157. const creations = telemetry.filter((request) => request.element_name === "session_create");
  158. expect(creations).toHaveLength(1);
  159. expect(creations[0]).toMatchObject({
  160. talk_id: taskId,
  161. event_extra_detail: {
  162. create_source: "automation_scheduled",
  163. client_kind: "desktop",
  164. workspace_kind: "local",
  165. remote_kind: "",
  166. },
  167. });
  168. expect(creations[0]!.event_id).toMatch(
  169. /^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
  170. );
  171. const completion = completions[0]!;
  172. const completionDetail = completion.event_extra_detail as JsonRecord;
  173. expect(completion.talk_id).toBe(taskId);
  174. expect(completionDetail).toMatchObject({
  175. message_source: "scheduled_task",
  176. task_trigger: "manual",
  177. });
  178. const automationId = String(completionDetail.automation_id ?? "");
  179. const messageId = String(completion.message_id ?? "");
  180. expect(creations[0]!.message_id).toBe(messageId);
  181. expect(automationId).not.toBe("");
  182. expect(messageId.startsWith(`${automationId}:manual:`)).toBe(true);
  183. for (const step of steps) {
  184. expect(step).toMatchObject({ talk_id: taskId, message_id: messageId });
  185. expect(step.event_extra_detail as JsonRecord).toMatchObject({
  186. message_source: "scheduled_task",
  187. task_trigger: "manual",
  188. automation_id: automationId,
  189. });
  190. }
  191. expect(completionDetail.agent_step_cnt).toBe(String(steps.length));
  192. }
  193. function parseTelemetryRequest(call: unknown[]): JsonRecord | null {
  194. const [input, init] = call;
  195. if (!String(input ?? "").includes(TELEMETRY_REPORT_PATH) || !isRecord(init)) return null;
  196. if (typeof init.body !== "string") return null;
  197. try {
  198. const parsed: unknown = JSON.parse(init.body);
  199. return isRecord(parsed) ? parsed : null;
  200. } catch {
  201. return null;
  202. }
  203. }
  204. function isRecord(value: unknown): value is JsonRecord {
  205. return typeof value === "object" && value !== null && !Array.isArray(value);
  206. }
  207. async function clickAutomationCardByTitle(title: string): Promise<void> {
  208. let latestTitles: string[] = [];
  209. await browser.waitUntil(
  210. async () => {
  211. const result = await browser.execute(
  212. (cardTestId, expectedTitle) => {
  213. const cards = Array.from(
  214. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  215. );
  216. const target = cards.find((card) => card.innerText.includes(expectedTitle));
  217. target?.click();
  218. return {
  219. clicked: Boolean(target),
  220. titles: cards.map((card) => card.innerText),
  221. };
  222. },
  223. TID_AUTOMATION_CARD,
  224. title,
  225. );
  226. latestTitles = result.titles;
  227. return result.clicked;
  228. },
  229. {
  230. timeout: 15000,
  231. timeoutMsg: `没有找到刚创建的定时任务卡片:${title}; latest=${latestTitles.join(" | ")}`,
  232. },
  233. );
  234. }
  235. async function waitForAutomationCardText(title: string, expectedText: string): Promise<string> {
  236. let latestText = "";
  237. await browser.waitUntil(
  238. async () => {
  239. latestText = await browser.execute(
  240. (cardTestId, expectedTitle) => {
  241. const cards = Array.from(
  242. document.querySelectorAll<HTMLElement>(`[data-testid="${cardTestId}"]`),
  243. );
  244. return cards.find((card) => card.innerText.includes(expectedTitle))?.innerText ?? "";
  245. },
  246. TID_AUTOMATION_CARD,
  247. title,
  248. );
  249. return latestText.includes(expectedText);
  250. },
  251. {
  252. timeout: 15000,
  253. timeoutMsg: `定时任务 Card 未显示“${expectedText}”:${title}; latest=${latestText}`,
  254. },
  255. );
  256. return latestText;
  257. }
  258. async function waitForTaskItemContaining(title: string): Promise<string> {
  259. let taskId: string | null = null;
  260. let latestTitles: string[] = [];
  261. await browser.waitUntil(
  262. async () => {
  263. const result = await browser.execute(
  264. (baseTestId, expectedTitle) => {
  265. const prefix = `${baseTestId}-`;
  266. const items = Array.from(
  267. document.querySelectorAll<HTMLElement>(`[data-testid^="${prefix}"]`),
  268. );
  269. const target = items.find((item) => item.innerText.includes(expectedTitle));
  270. return {
  271. taskId: target?.dataset.testid?.slice(prefix.length) ?? null,
  272. titles: items.map((item) => item.innerText),
  273. };
  274. },
  275. TID_TASK_ITEM,
  276. title,
  277. );
  278. taskId = result.taskId;
  279. latestTitles = result.titles;
  280. return Boolean(taskId);
  281. },
  282. {
  283. // 回归边界:run_now 必须由当前 host 直接派发,不能重新等待 20 秒 scheduler tick。
  284. timeout: 12000,
  285. timeoutMsg: `立即运行未直接派发,12 秒内侧栏没有出现执行会话:${title}; latest=${latestTitles.join(" | ")}`,
  286. },
  287. );
  288. if (!taskId) throw new Error("立即运行后缺少执行会话 taskId");
  289. return taskId;
  290. }
  291. async function expectHeaderTitle(expectedTitle: string): Promise<void> {
  292. const actual = await browser.execute((titleTestId) => {
  293. const header = document.querySelector<HTMLElement>(`[data-testid="${titleTestId}"]`);
  294. return header?.getAttribute("title") ?? header?.innerText.trim() ?? null;
  295. }, TID_WORKSPACE_TITLE);
  296. expect(actual).toBe(expectedTitle);
  297. }
  298. async function expectTaskItemTitle(taskId: string, expectedTitle: string): Promise<void> {
  299. const actual = await browser.execute(
  300. (taskItemTestId) => {
  301. const item = document.querySelector<HTMLElement>(`[data-testid="${taskItemTestId}"]`);
  302. return item?.innerText ?? null;
  303. },
  304. testId(TID_TASK_ITEM, taskId),
  305. );
  306. expect(actual).toContain(expectedTitle);
  307. }