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

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