conversation-session-dynamic-workflow-gray-always-on-snippet.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { dirname } from "node:path";
  3. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  4. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  5. import { readDynamicWorkflowGrayMockStatus } from "#e2e/helpers/dynamic-workflow-gray";
  6. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  7. import {
  8. approveV4Permission,
  9. getV4ConfigProjection,
  10. prepareV4ConversationE2E,
  11. sendV4Prompt,
  12. startNewV4Draft,
  13. switchV4Mode,
  14. waitForV4AssistantMessageContaining,
  15. waitForV4Pane,
  16. waitForV4PermissionDialogInComposerDock,
  17. } from "#e2e/helpers/v4-conversation";
  18. import {
  19. getLatestUpstreamToolResultByToolCallId,
  20. type UpstreamToolResultSnapshot,
  21. } from "#e2e/helpers/conversation-session-network";
  22. import { withoutTotalTokensReminderText } from "#e2e/helpers/total-tokens-evidence";
  23. import {
  24. isOutsideClosedHistory,
  25. openClosedHistoryFolds,
  26. revealOutsideClosedHistory,
  27. } from "#e2e/helpers/v4-history-folds";
  28. // EvalWorkflowSnippet:工作流创作的试验台(docs/dynamic-workflow/authoring.md「EvalWorkflowSnippet」
  29. // 「The skill gate」;编译反馈卡见 docs/dynamic-workflow/presentation.md「Compiler feedback」)。
  30. //
  31. // 文件名带 `gray-always-on`:配置 mock 网关按文件名下发 alwaysOn,工作流工具才在工具集里。
  32. // case-local 回放只固定模型的 Skill / EvalWorkflowSnippet 选择与收尾文本;真实 Skill 加载、技能门、
  33. // 片段编译、沙箱执行、world 读写、确认门与工具结果都走产品链路。片段完全瞬态,不起 run。
  34. // 每个 it 开一个新会话:技能是否加载按会话历史判定。
  35. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  36. const OK_SNIPPET = "dwy-ok-snippet.ts";
  37. const BAD_SNIPPET = "dwy-bad-snippet.ts";
  38. const GATE_OUTPUT = "dwy-gate-output.txt";
  39. const RUNNING_GATE = "dwy-gate-running";
  40. const NOT_EXECUTED_NOTE =
  41. "NOTE: The snippet was NOT executed — fix the errors above and call the tool again.";
  42. const triggerOf = (toolCallId: string) => `[data-testid="tool-summary-trigger-${toolCallId}"]`;
  43. interface SnippetCardState {
  44. /** 摘要行文字(折叠动画期间 getText 可能为空,读 textContent)。 */
  45. row: string;
  46. /** 摘要行有没有展开入口:不可展开的行没有 aria-expanded。 */
  47. expanded: string | null;
  48. hasBody: boolean;
  49. bodyText: string;
  50. headings: string[];
  51. result: string | null;
  52. resultLanguage: string | null;
  53. runningCode: string | null;
  54. logs: string | null;
  55. hasCodeFold: boolean;
  56. codeText: string | null;
  57. feedbackCount: string | null;
  58. feedbackLede: string | null;
  59. feedbackLines: string[];
  60. }
  61. function readSnippetCard(toolCallId: string): Promise<SnippetCardState | null> {
  62. return browser.execute((selector: string) => {
  63. const trigger = document.querySelector<HTMLElement>(selector);
  64. if (!trigger) return null;
  65. const root = trigger.parentElement;
  66. const body = root?.querySelector<HTMLElement>('[data-testid="workflow-snippet-body"]') ?? null;
  67. // 代码块由 @pierre/diffs 画在 shadow DOM 里,textContent 读不到:连 shadow root 一起走,跳过样式节点。
  68. const collect = (node: Node): string => {
  69. if (node.nodeType === Node.TEXT_NODE) return node.textContent ?? "";
  70. if (node.nodeName === "STYLE" || node.nodeName === "SCRIPT") return "";
  71. const shadow = node instanceof Element ? (node.shadowRoot?.childNodes ?? []) : [];
  72. return [...Array.from(shadow), ...Array.from(node.childNodes)].map(collect).join("");
  73. };
  74. const text = (element: Element | null | undefined) =>
  75. element ? collect(element).replace(/\s+/g, " ").trim() : null;
  76. const within = (testId: string) => body?.querySelector(`[data-testid="${testId}"]`) ?? null;
  77. const feedback = within("workflow-compiler-feedback");
  78. const result = within("snippet-result");
  79. return {
  80. row: text(trigger) ?? "",
  81. expanded: trigger.getAttribute("aria-expanded"),
  82. hasBody: body !== null,
  83. bodyText: text(body) ?? "",
  84. headings: Array.from(body?.querySelectorAll("h4, summary") ?? []).map(
  85. (element) => text(element) ?? "",
  86. ),
  87. result: text(result),
  88. resultLanguage:
  89. result?.querySelector("[data-language]")?.getAttribute("data-language") ?? null,
  90. runningCode: text(within("snippet-running-code")),
  91. logs: text(within("snippet-logs")?.querySelector("pre")),
  92. hasCodeFold: within("snippet-code") !== null,
  93. codeText: text(within("snippet-code")),
  94. feedbackCount: text(
  95. feedback?.querySelector('[data-testid="workflow-compiler-feedback-count"]'),
  96. ),
  97. feedbackLede: text(
  98. feedback?.querySelector('[data-testid="workflow-compiler-feedback-lede"]'),
  99. ),
  100. feedbackLines: Array.from(
  101. feedback?.querySelectorAll('[data-testid="workflow-compiler-feedback-line"]') ?? [],
  102. )
  103. // 坐标、正文、码是三个相邻元素:逐个读再用空格连。
  104. .map((line) =>
  105. Array.from(line.children)
  106. .map((part) => text(part) ?? "")
  107. .join(" "),
  108. ),
  109. };
  110. }, triggerOf(toolCallId));
  111. }
  112. // 已结束一轮的工具行收在「已处理」折叠里(默认收起),行不在展开处就展开所有收起的折叠直到它出现。
  113. async function revealToolRow(toolCallId: string) {
  114. await revealOutsideClosedHistory(triggerOf(toolCallId), `工具行没有出现:${toolCallId}`);
  115. await browser.execute((selector: string) => {
  116. document.querySelector(selector)?.scrollIntoView({ block: "center" });
  117. }, triggerOf(toolCallId));
  118. }
  119. /** 展开片段卡并等到满足条件的内容(终态切换时卡片会换 key 重挂,不能只点一次)。 */
  120. async function openSnippetCard(
  121. toolCallId: string,
  122. accept: (card: SnippetCardState) => boolean,
  123. timeoutMsg: string,
  124. ): Promise<SnippetCardState> {
  125. await revealToolRow(toolCallId);
  126. let last: SnippetCardState | null = null;
  127. await browser
  128. .waitUntil(
  129. async () => {
  130. // 轮次结束时折叠原地收起(见 helpers/v4-history-folds.ts):收起中的卡不算,补开折叠再读。
  131. if (!(await isOutsideClosedHistory(triggerOf(toolCallId)))) await openClosedHistoryFolds();
  132. last = await readSnippetCard(toolCallId);
  133. if (last?.hasBody && accept(last)) return true;
  134. await browser.execute((selector: string) => {
  135. const trigger = document.querySelector<HTMLElement>(selector);
  136. if (trigger?.getAttribute("aria-expanded") === "false") trigger.click();
  137. }, triggerOf(toolCallId));
  138. return false;
  139. },
  140. { timeout: 30000 },
  141. )
  142. .catch((error: unknown) => {
  143. throw new Error(`${timeoutMsg};最后读到 ${JSON.stringify(last)}`, { cause: error });
  144. });
  145. return last as unknown as SnippetCardState;
  146. }
  147. async function waitForToolResult(toolCallId: string): Promise<UpstreamToolResultSnapshot> {
  148. let result: UpstreamToolResultSnapshot | null = null;
  149. await browser.waitUntil(
  150. async () => {
  151. result = await getLatestUpstreamToolResultByToolCallId(toolCallId);
  152. return result !== null;
  153. },
  154. { timeout: 90000, timeoutMsg: `${toolCallId} 的工具结果没有回到模型请求里` },
  155. );
  156. // 修复原因:工具批次后的 token 预算提醒(bef446ae1f)以 `\n\n` 段并进 tool_result,
  157. // 排在片段结果之后,锚定结尾的匹配与返回值的 JSON 解析都会读到它。片段的模型面只看去掉提醒后的文字。
  158. const snapshot = result as unknown as UpstreamToolResultSnapshot;
  159. return { ...snapshot, content: withoutTotalTokensReminderText(snapshot.content) };
  160. }
  161. /** 模型面的返回值段:序列化方式与完成通知相同(带缩进),按值比较。 */
  162. function returnValueOf(content: string): unknown {
  163. const start = content.indexOf("Return value:\n") + "Return value:\n".length;
  164. const end = content.indexOf("\n\nLogs:\n");
  165. return JSON.parse(end === -1 ? content.slice(start) : content.slice(start, end));
  166. }
  167. async function waitForTurnIdle(timeoutMsg: string) {
  168. await waitForV4Pane((pane) => !pane.canStop, timeoutMsg, 60000);
  169. }
  170. async function startSession(mode: "build" | "yolo") {
  171. await startNewV4Draft();
  172. await switchV4Mode(mode);
  173. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === mode, {
  174. timeout: 30000,
  175. timeoutMsg: `composer 没有切到 mode=${mode}`,
  176. });
  177. await watchPermissionDialogs();
  178. }
  179. // 「不弹窗」是一段时间里的否定:发送前装上观察器,数权限弹窗从无到有出现了几次,不靠固定等待去抽样。
  180. async function watchPermissionDialogs() {
  181. await browser.execute(() => {
  182. const probe = window as Window & {
  183. __dwyDialogs?: number;
  184. __dwyObserver?: MutationObserver;
  185. };
  186. probe.__dwyObserver?.disconnect();
  187. probe.__dwyDialogs = 0;
  188. const seen = () =>
  189. Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some((element) => {
  190. const label = (element.getAttribute("aria-label") ?? "").trim();
  191. return label === "Permission required" || label === "需要权限";
  192. });
  193. let present = seen();
  194. const observer = new MutationObserver(() => {
  195. const now = seen();
  196. if (now && !present) probe.__dwyDialogs = (probe.__dwyDialogs ?? 0) + 1;
  197. present = now;
  198. });
  199. observer.observe(document.body, { childList: true, subtree: true, attributes: true });
  200. probe.__dwyObserver = observer;
  201. });
  202. }
  203. function permissionDialogCount(): Promise<number> {
  204. return browser.execute(() => (window as Window & { __dwyDialogs?: number }).__dwyDialogs ?? 0);
  205. }
  206. async function writeRuntimeFile(name: string, content: string) {
  207. const path = resolveE2ERuntimePath(name);
  208. await mkdir(dirname(path), { recursive: true });
  209. await writeFile(path, content);
  210. }
  211. describe("动态工作流 · EvalWorkflowSnippet", () => {
  212. before(async () => {
  213. await prepareV4ConversationE2E();
  214. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  215. await pinE2ELocale("zh-CN");
  216. await Promise.all(
  217. [GATE_OUTPUT, RUNNING_GATE].map((name) => rm(resolveE2ERuntimePath(name), { force: true })),
  218. );
  219. await writeRuntimeFile(OK_SNIPPET, 'log("E2E_DWY_PATH_LOG");\nreturn "E2E_DWY_PATH_VALUE";\n');
  220. await writeRuntimeFile(
  221. BAD_SNIPPET,
  222. '// 第 1 行是注释\nconst broken: number = "x";\nreturn broken;\n',
  223. );
  224. });
  225. after(async () => {
  226. await browser.electron.restoreAllMocks();
  227. await clearAppData();
  228. });
  229. it("DWY-01 只读片段:不弹窗不起 run;模型拿到返回值与日志;卡片只画「工作流片段 · N ms」和返回值,没有返回值的片段行不可展开", async function () {
  230. this.timeout(240000);
  231. expect((await readDynamicWorkflowGrayMockStatus()).scenario).toBe("alwaysOn");
  232. await startSession("build");
  233. await sendV4Prompt("E2E_DWY_VALUE_START 先试一段片段。");
  234. await waitForV4AssistantMessageContaining("E2E_DWY_VALUE_DONE", 120000);
  235. await waitForTurnIdle("片段那一轮没有结束");
  236. const value = await waitForToolResult("toolu_dwy_value_eval");
  237. expect(value.isError).toBe(false);
  238. expect(value.content).toMatch(/^The snippet completed in \d+ms\.\nReturn value:\n/);
  239. expect(returnValueOf(value.content)).toEqual({
  240. marker: "E2E_DWY_VALUE",
  241. sum: 3,
  242. });
  243. expect(value.content).toContain("\n\nLogs:\n- E2E_DWY_LOG_FIRST\n- E2E_DWY_LOG_SECOND");
  244. const empty = await waitForToolResult("toolu_dwy_value_empty");
  245. expect(empty.isError).toBe(false);
  246. expect(empty.content).toMatch(
  247. /^The snippet completed in \d+ms\.\nIt returned no value\.\n\nLogs:\n- E2E_DWY_LOG_ONLY$/,
  248. );
  249. // 只读片段静默放行;片段不进 run 列表。
  250. expect(await permissionDialogCount()).toBe(0);
  251. expect(await $(RUN_DIGEST).isExisting()).toBe(false);
  252. // 完成:只显示返回值(JSON 美化),无标题、日志与代码折叠,不重复耗时、PASS 与给模型的那段话。
  253. const card = await openSnippetCard(
  254. "toolu_dwy_value_eval",
  255. (state) => state.result?.includes("E2E_DWY_VALUE") === true,
  256. "片段卡没有画出返回值",
  257. );
  258. expect(card.row).toMatch(/工作流片段.*\d+ms/);
  259. expect(card.row).not.toContain("执行失败");
  260. expect(card.resultLanguage).toBe("json");
  261. expect(card.headings).toEqual([]);
  262. expect(card.logs).toBeNull();
  263. expect(card.hasCodeFold).toBe(false);
  264. expect(card.feedbackCount).toBeNull();
  265. expect(card.bodyText).not.toMatch(/E2E_DWY_LOG_|completed in|Return value:|\d+ms|PASS|通过/);
  266. // 没有返回值:行上只有耗时,没有展开入口,不留空面板;日志只给模型。
  267. await revealToolRow("toolu_dwy_value_empty");
  268. const emptyCard = await readSnippetCard("toolu_dwy_value_empty");
  269. expect(emptyCard?.row).toMatch(/工作流片段.*\d+ms/);
  270. expect(emptyCard?.expanded).toBeNull();
  271. expect(emptyCard?.hasBody).toBe(false);
  272. });
  273. it("DWY-02 失败:抛错带日志、编不过(facade 没有 agent)、返回值超限、读工作区外、墙钟超时都以结构化形式回到模型;卡片走通用失败摘要或编译反馈卡", async function () {
  274. this.timeout(240000);
  275. await startSession("build");
  276. await sendV4Prompt("E2E_DWY_FAIL_START 试几段会失败的片段。");
  277. await waitForV4AssistantMessageContaining("E2E_DWY_FAIL_DONE", 120000);
  278. await waitForTurnIdle("失败片段那一轮没有结束");
  279. const thrown = await waitForToolResult("toolu_dwy_fail_throw");
  280. expect(thrown.content).toMatch(/^The snippet failed \(\w+\): .*E2E_DWY_BOOM/);
  281. expect(thrown.content).toContain("\n\nLogs:\n- E2E_DWY_BEFORE_THROW");
  282. const compile = await waitForToolResult("toolu_dwy_fail_compile");
  283. expect(compile.content).toMatch(/^The snippet has errors:\nL2:C\d+ Cannot find name 'agent'\./);
  284. expect(compile.content).toContain(NOT_EXECUTED_NOTE);
  285. // 编不过就什么都没跑:第一行的 log 没有留下。
  286. expect(compile.content).not.toContain("E2E_DWY_NEVER_LOGGED");
  287. const large = await waitForToolResult("toolu_dwy_fail_large");
  288. expect(large.content).toMatch(/^The snippet failed \(ArtifactTooLarge\): /);
  289. expect(large.content).toContain("Return a summary");
  290. // 与真实 run 同一条 world 读:工作区外的路径被拒。
  291. const outside = await waitForToolResult("toolu_dwy_fail_outside");
  292. expect(outside.content).toMatch(/^The snippet failed \(\w+\): .*is outside the workspace/);
  293. const timedOut = await waitForToolResult("toolu_dwy_fail_timeout");
  294. expect(timedOut.content).toMatch(/^The snippet failed \(\w+\): .*1000ms/);
  295. expect(await permissionDialogCount()).toBe(0);
  296. expect(await $(RUN_DIGEST).isExisting()).toBe(false);
  297. // 抛错:通用失败摘要(不写耗时),展开依次是错误、日志、代码折叠,错误信息只出现一次。
  298. const thrownCard = await openSnippetCard(
  299. "toolu_dwy_fail_throw",
  300. (state) => state.result?.includes("E2E_DWY_BOOM") === true,
  301. "抛错的片段卡没有展开出错误",
  302. );
  303. expect(thrownCard.row).toContain("执行失败");
  304. expect(thrownCard.row).not.toMatch(/\d+ms/);
  305. expect(thrownCard.logs).toBe("E2E_DWY_BEFORE_THROW");
  306. expect(thrownCard.hasCodeFold).toBe(true);
  307. expect(thrownCard.codeText).toContain("代码");
  308. // 日志只在日志段:错误段里解包掉了给模型的 Logs 尾巴。
  309. expect(thrownCard.result).not.toContain("E2E_DWY_BEFORE_THROW");
  310. // 编不过:编译反馈卡(与 CreateWorkflow 同一张),诊断不再以错误文本重复一遍。
  311. const compileCard = await openSnippetCard(
  312. "toolu_dwy_fail_compile",
  313. (state) => state.feedbackCount !== null,
  314. "编不过的片段卡没有展开出编译反馈",
  315. );
  316. expect(compileCard.row).toContain("执行失败");
  317. expect(compileCard.feedbackCount).toBe("1 条");
  318. expect(compileCard.feedbackLede).toBe(
  319. "类型检查未通过,脚本未运行;反馈已交回模型,由它修改后重新提交。",
  320. );
  321. expect(compileCard.feedbackLines).toHaveLength(1);
  322. expect(compileCard.feedbackLines[0]).toMatch(/^L2:C\d+ Cannot find name 'agent'.*TS2304$/);
  323. expect(compileCard.result).toBeNull();
  324. expect(compileCard.logs).toBeNull();
  325. expect(compileCard.hasCodeFold).toBe(true);
  326. const largeCard = await openSnippetCard(
  327. "toolu_dwy_fail_large",
  328. (state) => state.result?.includes("ArtifactTooLarge") === true,
  329. "超限的片段卡没有展开出错误",
  330. );
  331. expect(largeCard.row).toContain("执行失败");
  332. const timeoutCard = await openSnippetCard(
  333. "toolu_dwy_fail_timeout",
  334. (state) => state.result?.includes("1000ms") === true,
  335. "超时的片段卡没有展开出错误",
  336. );
  337. expect(timeoutCard.row).toContain("执行失败");
  338. });
  339. it("DWY-03 技能门:没加载技能时片段被拒(工具错误点名技能),不弹窗、不执行;加载后同一片段带 world.run,确认门询问,批准后才执行", async function () {
  340. this.timeout(240000);
  341. await startSession("build");
  342. await sendV4Prompt("E2E_DWY_GATE_START 跑一段会写文件的片段。");
  343. const refused = await waitForToolResult("toolu_dwy_gate_eval_1");
  344. expect(refused.isError).toBe(true);
  345. expect(refused.content).toContain(
  346. "EvalWorkflowSnippet needs the `dynamic-workflows` skill loaded in this session before it accepts a script.",
  347. );
  348. expect(refused.content).toContain('Call the Skill tool with skill "dynamic-workflows" first');
  349. expect(refused.content).toContain("then call EvalWorkflowSnippet again. Nothing was started.");
  350. // 模型加载技能后重发:第一个、也是唯一一个窗属于第二次调用;批准前片段没有执行。
  351. await waitForV4PermissionDialogInComposerDock(120000);
  352. expect((await waitForToolResult("toolu_dwy_gate_skill")).isError).toBe(false);
  353. expect(await permissionDialogCount()).toBe(1);
  354. await expect(readFile(resolveE2ERuntimePath(GATE_OUTPUT), "utf8")).rejects.toMatchObject({
  355. code: "ENOENT",
  356. });
  357. await approveV4Permission();
  358. const ran = await waitForToolResult("toolu_dwy_gate_eval_2");
  359. expect(ran.isError).toBe(false);
  360. expect(returnValueOf(ran.content)).toEqual({ marker: "E2E_DWY_GATE_VALUE", exitCode: 0 });
  361. expect(await readFile(resolveE2ERuntimePath(GATE_OUTPUT), "utf8")).toBe("ran\n");
  362. await waitForV4AssistantMessageContaining("E2E_DWY_GATE_DONE", 60000);
  363. await waitForTurnIdle("技能门那一轮没有结束");
  364. expect(await permissionDialogCount()).toBe(1);
  365. // 被门拒绝的行走通用失败摘要:展开是拒绝文本,没有日志与编译反馈。
  366. const refusedCard = await openSnippetCard(
  367. "toolu_dwy_gate_eval_1",
  368. (state) => state.result?.includes("dynamic-workflows") === true,
  369. "被技能门拒绝的行没有展开出错误",
  370. );
  371. expect(refusedCard.row).toContain("执行失败");
  372. expect(refusedCard.logs).toBeNull();
  373. expect(refusedCard.feedbackCount).toBeNull();
  374. const ranCard = await openSnippetCard(
  375. "toolu_dwy_gate_eval_2",
  376. (state) => state.result?.includes("E2E_DWY_GATE_VALUE") === true,
  377. "批准后的片段卡没有画出返回值",
  378. );
  379. expect(ranCard.row).toMatch(/工作流片段.*\d+ms/);
  380. });
  381. it("DWY-04 运行中:完全访问下带 world.run 的片段不询问;行写「正在运行工作流片段 · N s」,展开是代码;闸文件放行后变成「工作流片段 · N ms」和返回值", async function () {
  382. this.timeout(240000);
  383. await startSession("yolo");
  384. await sendV4Prompt("E2E_DWY_RUNNING_START 跑一段要等的片段。");
  385. const running = await openSnippetCard(
  386. "toolu_dwy_running_eval",
  387. (state) => state.runningCode?.includes("E2E_DWY_RUNNING_VALUE") === true,
  388. "运行中的片段卡展开后没有代码",
  389. );
  390. expect(running.row).toMatch(/正在运行工作流片段.*\d+s/);
  391. expect(running.row).not.toMatch(/\d+ms/);
  392. expect(running.result).toBeNull();
  393. expect(await getLatestUpstreamToolResultByToolCallId("toolu_dwy_running_eval")).toBeNull();
  394. await writeRuntimeFile(RUNNING_GATE, "open\n");
  395. const done = await waitForToolResult("toolu_dwy_running_eval");
  396. expect(done.isError).toBe(false);
  397. expect(returnValueOf(done.content)).toEqual({
  398. marker: "E2E_DWY_RUNNING_VALUE",
  399. out: "E2E_DWY_RUNNING_STDOUT",
  400. // 片段的 world.run 与 files.* 落在同一个工作区:命令写下的文件,glob 给相对路径,read 读得到。
  401. found: ["dwy-running.txt"],
  402. written: "E2E_DWY_WRITTEN",
  403. });
  404. await waitForV4AssistantMessageContaining("E2E_DWY_RUNNING_DONE", 60000);
  405. await waitForTurnIdle("运行中片段那一轮没有结束");
  406. expect(await permissionDialogCount()).toBe(0);
  407. const card = await openSnippetCard(
  408. "toolu_dwy_running_eval",
  409. (state) => state.result?.includes("E2E_DWY_RUNNING_STDOUT") === true,
  410. "片段完成后卡片没有换成返回值",
  411. );
  412. expect(card.row).toMatch(/工作流片段.*\d+ms/);
  413. expect(card.row).not.toContain("正在运行");
  414. expect(card.runningCode).toBeNull();
  415. });
  416. it("DWY-05 来源:path 读文件当片段跑,诊断按文件行且点名文件;文件读不了、code 与 path 都给、都不给各有自己的拒绝", async function () {
  417. this.timeout(240000);
  418. await startSession("build");
  419. await sendV4Prompt("E2E_DWY_PATH_START 按文件跑片段。");
  420. await waitForV4AssistantMessageContaining("E2E_DWY_PATH_DONE", 120000);
  421. await waitForTurnIdle("path 片段那一轮没有结束");
  422. const ok = await waitForToolResult("toolu_dwy_path_ok");
  423. expect(ok.isError).toBe(false);
  424. expect(ok.content).toContain("Return value:\n");
  425. expect(ok.content).toContain("E2E_DWY_PATH_VALUE");
  426. expect(ok.content).toContain("Logs:\n- E2E_DWY_PATH_LOG");
  427. const bad = await waitForToolResult("toolu_dwy_path_bad");
  428. expect(bad.content).toContain("The snippet has errors:");
  429. expect(bad.content).toMatch(
  430. new RegExp(`${BAD_SNIPPET.replace(".", "\\.")}:L2:C7 Type 'string' is not assignable`),
  431. );
  432. expect(bad.content).toContain(NOT_EXECUTED_NOTE);
  433. const missing = await waitForToolResult("toolu_dwy_path_missing");
  434. expect(missing.isError).toBe(true);
  435. expect(missing.content).toContain("dwy-absent.ts");
  436. expect(missing.content).toContain("could not be read");
  437. const both = await waitForToolResult("toolu_dwy_path_both");
  438. expect(both.isError).toBe(true);
  439. expect(both.content).toContain(
  440. "Provide exactly one snippet source: `code` for the snippet inline, or `path` for a file holding it. Passing both is ambiguous.",
  441. );
  442. const neither = await waitForToolResult("toolu_dwy_path_neither");
  443. expect(neither.isError).toBe(true);
  444. expect(neither.content).toContain(
  445. "No snippet source arrived. Pass `code` for the snippet inline, or `path` for a file holding it.",
  446. );
  447. expect(await permissionDialogCount()).toBe(0);
  448. // path 编不过:与内联同一张编译反馈卡,坐标是文件行。
  449. const badCard = await openSnippetCard(
  450. "toolu_dwy_path_bad",
  451. (state) => state.feedbackCount !== null,
  452. "path 编不过的片段卡没有展开出编译反馈",
  453. );
  454. expect(badCard.feedbackLines[0]).toMatch(/^L2:C7 .*TS2322$/);
  455. // 诊断只归编译反馈卡:这里曾把给模型的全文连同本机绝对路径又画一遍。
  456. expect(badCard.bodyText).not.toContain("The snippet has errors");
  457. expect(badCard.bodyText).not.toContain(BAD_SNIPPET);
  458. });
  459. });