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

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