workflowPermissionBlock.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. // @vitest-environment jsdom
  2. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  3. import type { ZCodePermissionRequest } from "@zcode/shared";
  4. import { createElement, type ReactNode } from "react";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  7. vi.mock("@/components/ai-elements/code-block.js", () => ({
  8. CodeBlock: ({ code }: { code: string }) =>
  9. createElement("pre", { "data-testid": "code-block" }, code),
  10. }));
  11. // ControlHintTooltip 依赖应用根部的 TooltipProvider;测试里按既有惯例替换为透传桩。
  12. vi.mock("@/ControlHintTooltip.js", () => ({
  13. ControlHintTooltip: ({ children }: { children?: ReactNode }) => children,
  14. }));
  15. // eslint-disable-next-line import/first -- 必须在 mock 之后再引入被测组件。
  16. import { PermissionDialog } from "@/PermissionDialog.js";
  17. const SCRIPT = 'const x = 1;\nconst r = await agent("a").ask<string>("do");';
  18. // CLI 侧的 ask reason 是协议诊断文案,确认窗必须不展示它。
  19. const CLI_REASON = "createWorkflow.runConfirmation: user must confirm running the analyzed script";
  20. const CAUSALITY_GRAPH = {
  21. steps: [
  22. {
  23. id: "ask#1",
  24. kind: "ask" as const,
  25. label: "a",
  26. line: 2,
  27. column: 21,
  28. lane: "actor#1",
  29. },
  30. ],
  31. lanes: [{ id: "actor#1", name: "a", line: 2, column: 11 }],
  32. // 参与者层:无标记脚本的卡归 `unphased`(UI 合成隐式模块)。
  33. participants: [{ id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] }],
  34. handoffs: [],
  35. sink: ["ask#1"],
  36. };
  37. const SESSION_OPTION = {
  38. optionId: "allowSession",
  39. kind: "allowAlways",
  40. name: "Always allow in this session",
  41. response: { decision: "allow" as const, reason: "Approved for this session" },
  42. };
  43. function buildWorkflowRequest(
  44. overrides: Partial<ZCodePermissionRequest> = {},
  45. ): ZCodePermissionRequest {
  46. return {
  47. type: "permission_request",
  48. taskId: "task-1",
  49. traceId: "trace-1",
  50. requestId: "perm-workflow",
  51. description: CLI_REASON,
  52. kind: "CreateWorkflow",
  53. title: "CreateWorkflow",
  54. options: [
  55. {
  56. optionId: "allowOnce",
  57. kind: "allowOnce",
  58. name: "Allow",
  59. response: { decision: "allow" },
  60. },
  61. // 第 7 轮:会话免确认。v4 投影把 kind 映为 allowAlways,GUI 按 name 本地化。
  62. SESSION_OPTION,
  63. {
  64. optionId: "deny",
  65. kind: "deny",
  66. name: "Deny",
  67. response: { decision: "deny" },
  68. },
  69. ],
  70. display: {
  71. kind: "create_workflow",
  72. ok: true,
  73. errorCount: 0,
  74. diagnostics: [],
  75. causalityGraph: CAUSALITY_GRAPH,
  76. },
  77. raw: { name: "Research pipeline", script: SCRIPT },
  78. ...overrides,
  79. };
  80. }
  81. function renderDialog(
  82. request: ZCodePermissionRequest = buildWorkflowRequest(),
  83. locale: "en-US" | "zh-CN" = "en-US",
  84. onRespond: (requestId: string, option: unknown, feedback?: string) => void = () => {},
  85. ) {
  86. return render(
  87. createElement(
  88. ZCodeIntlProvider,
  89. { initialLocale: locale },
  90. createElement(PermissionDialog, {
  91. request,
  92. onRespond,
  93. workspacePath: "/workspace",
  94. }),
  95. ),
  96. );
  97. }
  98. afterEach(() => {
  99. cleanup();
  100. });
  101. describe("WorkflowPermissionBlock", () => {
  102. it("renders the timeline as the primary body and keeps the script folded", () => {
  103. renderDialog();
  104. // 时间线(docs/dynamic-workflow/presentation.md「The confirmation window」):无标记脚本是一个隐式站「Workflow」,
  105. // 药丸是那条车道的作者原名。没有放大入口、没有弹窗。
  106. const timeline = screen.getByTestId("workflow-timeline");
  107. expect(timeline.textContent).toContain("Workflow");
  108. expect(screen.getByTestId("workflow-agent-pill").textContent).toContain("a");
  109. expect(screen.queryByLabelText("Expand graph")).toBeNull();
  110. expect(screen.getByText("Research pipeline")).toBeTruthy();
  111. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  112. // 表头右侧:静态状态 + 计数细节。
  113. expect(screen.getByTestId("workflow-card-detail").textContent).toBe("1 phase");
  114. // 脚本是审计细节层:默认收起,Radix Collapsible 关闭时内容不进 DOM。
  115. expect(screen.queryByTestId("code-block")).toBeNull();
  116. expect(document.body.textContent).not.toContain('await agent("a")');
  117. expect(screen.getByText("Show full script")).toBeTruthy();
  118. });
  119. it("renders the localized question in both locales", () => {
  120. renderDialog(buildWorkflowRequest(), "zh-CN");
  121. expect(screen.getByText("运行此工作流?")).toBeTruthy();
  122. expect(screen.getByText("显示完整脚本")).toBeTruthy();
  123. cleanup();
  124. renderDialog(buildWorkflowRequest(), "en-US");
  125. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  126. });
  127. it("asks the question above the workflow name", () => {
  128. renderDialog();
  129. // 刻意的顺序:弹窗通用标题「需要权限」+ 问句连读才是完整提问,名称行是它下方那张图的标题。
  130. const blockText =
  131. document.querySelector('[data-workflow-permission-block="true"]')?.textContent ?? "";
  132. expect(blockText.indexOf("Run this workflow?")).toBeGreaterThanOrEqual(0);
  133. expect(blockText.indexOf("Run this workflow?")).toBeLessThan(
  134. blockText.indexOf("Research pipeline"),
  135. );
  136. });
  137. it("shows the full script after the fold is toggled open", () => {
  138. renderDialog();
  139. fireEvent.click(screen.getByText("Show full script"));
  140. expect(screen.getByTestId("code-block").textContent).toContain('await agent("a")');
  141. expect(screen.getByText("Hide full script")).toBeTruthy();
  142. });
  143. // 长脚本不再把弹窗撑高:脚本区限高 + 滚动。
  144. it("bounds the script region with a max height and makes it scrollable", () => {
  145. renderDialog();
  146. fireEvent.click(screen.getByText("Show full script"));
  147. const scroller = screen.getByTestId("workflow-script-scroll");
  148. expect(scroller.className).toMatch(/max-h-/u);
  149. expect(scroller.className).toMatch(/overflow-auto/u);
  150. });
  151. it("opens the script by default when there is no graph to show", () => {
  152. renderDialog(
  153. buildWorkflowRequest({
  154. display: { kind: "create_workflow", ok: true, errorCount: 0, diagnostics: [] },
  155. }),
  156. );
  157. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  158. // 零 step 脚本没有图可看,代码就是唯一内容。
  159. expect(screen.getByTestId("code-block").textContent).toContain('await agent("a")');
  160. expect(screen.getByText("Hide full script")).toBeTruthy();
  161. });
  162. it("treats a participant-less graph as no graph", () => {
  163. renderDialog(
  164. buildWorkflowRequest({
  165. display: {
  166. kind: "create_workflow",
  167. ok: true,
  168. errorCount: 0,
  169. diagnostics: [],
  170. causalityGraph: { steps: [], lanes: [], participants: [], handoffs: [] },
  171. },
  172. }),
  173. );
  174. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  175. expect(screen.getByTestId("code-block")).toBeTruthy();
  176. });
  177. it("degrades to an open script when the ask carries no preview at all", () => {
  178. // 失败路径:prepareApproval 抛错 → 无 preview 的普通 ask。gate 仍然成立,
  179. // 只是没有图,脚本就成了唯一可审计内容。
  180. renderDialog(buildWorkflowRequest({ display: undefined }));
  181. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  182. expect(screen.getByTestId("code-block").textContent).toContain('await agent("a")');
  183. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  184. });
  185. it("renders header and question without crashing when the input has no script", () => {
  186. renderDialog(buildWorkflowRequest({ display: undefined, raw: { name: "Broken input" } }));
  187. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  188. expect(screen.getByText("Broken input")).toBeTruthy();
  189. expect(screen.queryByTestId("code-block")).toBeNull();
  190. expect(screen.queryByText("Show full script")).toBeNull();
  191. });
  192. // ── 修订的确认窗(docs/dynamic-workflow/launch.md「The `AmendWorkflow` tool」;presentation.md
  193. // 「The confirmation window」)──只对别的会话的 run 出现:问句换词,多一行 lineage。事实从**工具
  194. // 入参**渲染(`run_id` 与 CLI 回填的 `predecessor`),display 一个字节都不变——图仍是 create_workflow。
  195. function buildAmendRequest(raw: Record<string, unknown>): ZCodePermissionRequest {
  196. return buildWorkflowRequest({
  197. kind: "AmendWorkflow",
  198. title: "AmendWorkflow",
  199. description: "amendWorkflow.runConfirmation: user must confirm running the revised script",
  200. raw,
  201. });
  202. }
  203. it("asks 'Amend this workflow?' with the lineage line for an AmendWorkflow ask", () => {
  204. renderDialog(
  205. buildAmendRequest({
  206. name: "Research pipeline",
  207. script: SCRIPT,
  208. run_id: "dwfrun-prev",
  209. predecessor: { status: "completed", owned_by_this_session: false },
  210. }),
  211. );
  212. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("Amend this workflow?");
  213. expect(document.body.textContent).not.toContain("Run this workflow?");
  214. const lineage = document.querySelector('[data-workflow-amends="true"]');
  215. expect(lineage).toBeTruthy();
  216. expect(lineage?.textContent).toContain("Amends run");
  217. expect(lineage?.textContent).toContain("dwfrun-prev");
  218. // 前驱已结算:没有「将被停止」那一句。
  219. expect(lineage?.getAttribute("data-workflow-amends-live")).toBeNull();
  220. expect(lineage?.textContent).not.toContain("still running");
  221. // 图仍是主体,脚本仍是折叠的审计层:lineage 只是多一行。
  222. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  223. expect(screen.queryByTestId("code-block")).toBeNull();
  224. });
  225. it.each(["running", "pending"] as const)(
  226. "says the predecessor will be stopped when it is still in flight (%s)",
  227. (status) => {
  228. renderDialog(
  229. buildAmendRequest({
  230. script: SCRIPT,
  231. run_id: "dwfrun-live",
  232. predecessor: { status, owned_by_this_session: false },
  233. }),
  234. );
  235. const lineage = document.querySelector('[data-workflow-amends="true"]');
  236. expect(lineage?.getAttribute("data-workflow-amends-live")).toBe("true");
  237. expect(lineage?.textContent).toContain("still running, will be stopped");
  238. },
  239. );
  240. it("localizes the amend title and lineage", () => {
  241. renderDialog(
  242. buildAmendRequest({
  243. name: "Research pipeline",
  244. script: SCRIPT,
  245. run_id: "dwfrun-prev",
  246. predecessor: { status: "running", owned_by_this_session: false },
  247. }),
  248. "zh-CN",
  249. );
  250. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("调整此工作流?");
  251. const lineage = document.querySelector('[data-workflow-amends="true"]');
  252. expect(lineage?.textContent).toContain("调整 run");
  253. expect(lineage?.textContent).toContain("dwfrun-prev");
  254. expect(lineage?.textContent).toContain("仍在运行,将被停止");
  255. });
  256. // 省略 script 的修订(docs/dynamic-workflow/launch.md「Keeping the predecessor's script」):CLI 已把
  257. // 前驱的脚本回填进入参并盖上 `predecessor.script_inherited`。窗上照常画图、照常可展开脚本——审的
  258. // 就是将要跑的那一份——lineage 行多说一句「脚本不变」,让用户知道这次改的只是设定。
  259. it("says 'script unchanged' on the lineage line when the amend keeps the predecessor's script", () => {
  260. renderDialog(
  261. buildAmendRequest({
  262. script: SCRIPT,
  263. run_id: "dwfrun-prev",
  264. max_concurrency: 2,
  265. predecessor: { status: "running", owned_by_this_session: false, script_inherited: true },
  266. }),
  267. );
  268. const lineage = document.querySelector('[data-workflow-amends="true"]');
  269. expect(lineage?.getAttribute("data-workflow-amends-script-inherited")).toBe("true");
  270. expect(lineage?.textContent).toContain("dwfrun-prev");
  271. expect(lineage?.textContent).toContain("script unchanged");
  272. expect(lineage?.textContent).toContain("still running, will be stopped");
  273. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  274. expect(screen.getByText("Show full script")).toBeTruthy();
  275. expect(screen.getByTestId("workflow-permission-max-concurrency").textContent).toBe(
  276. "At most 2 subagents at once",
  277. );
  278. });
  279. it("says nothing about the script when the amend passes one", () => {
  280. renderDialog(
  281. buildAmendRequest({
  282. script: SCRIPT,
  283. run_id: "dwfrun-prev",
  284. predecessor: { status: "completed", owned_by_this_session: false },
  285. }),
  286. );
  287. const lineage = document.querySelector('[data-workflow-amends="true"]');
  288. expect(lineage?.getAttribute("data-workflow-amends-script-inherited")).toBeNull();
  289. expect(lineage?.textContent).not.toContain("script unchanged");
  290. });
  291. it("localizes 'script unchanged'", () => {
  292. renderDialog(
  293. buildAmendRequest({
  294. script: SCRIPT,
  295. run_id: "dwfrun-prev",
  296. predecessor: { status: "completed", owned_by_this_session: false, script_inherited: true },
  297. }),
  298. "zh-CN",
  299. );
  300. const lineage = document.querySelector('[data-workflow-amends="true"]');
  301. expect(lineage?.textContent).toContain("脚本不变");
  302. });
  303. it("omits the lineage line entirely for a CreateWorkflow ask", () => {
  304. // CreateWorkflow 没有前驱(也不再有 resume_from):不留空行、不留占位词、问句照旧。
  305. renderDialog();
  306. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("Run this workflow?");
  307. expect(document.querySelector('[data-workflow-amends="true"]')).toBeNull();
  308. expect(document.body.textContent).not.toContain("Amends run");
  309. });
  310. it("ignores a blank run_id instead of rendering an empty lineage", () => {
  311. renderDialog(buildAmendRequest({ script: SCRIPT, run_id: " " }));
  312. expect(document.querySelector('[data-workflow-amends="true"]')).toBeNull();
  313. });
  314. // ── 并发上限(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)──
  315. // 模型只在用户要求时才写 `max_concurrency`,所以这一行在场就是用户自己提的条件。
  316. // 与 lineage 同一条纪律:事实从**工具入参**读,display 一个字节都不变。
  317. function queryMaxConcurrency(): HTMLElement | null {
  318. return screen.queryByTestId("workflow-permission-max-concurrency");
  319. }
  320. it("says how many subagents may run at once when the input carries max_concurrency", () => {
  321. renderDialog(
  322. buildWorkflowRequest({
  323. raw: { name: "Research pipeline", script: SCRIPT, max_concurrency: 3 },
  324. }),
  325. );
  326. expect(queryMaxConcurrency()?.textContent).toBe("At most 3 subagents at once");
  327. });
  328. it("shows the same row for an AmendWorkflow ask, right after the lineage row", () => {
  329. renderDialog(
  330. buildAmendRequest({
  331. script: SCRIPT,
  332. run_id: "dwfrun-prev",
  333. predecessor: { status: "completed", owned_by_this_session: false },
  334. max_concurrency: 2,
  335. }),
  336. );
  337. expect(queryMaxConcurrency()?.textContent).toBe("At most 2 subagents at once");
  338. const blockText =
  339. document.querySelector('[data-workflow-permission-block="true"]')?.textContent ?? "";
  340. expect(blockText.indexOf("Amends run")).toBeLessThan(blockText.indexOf("At most 2"));
  341. });
  342. it("localizes the row", () => {
  343. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, max_concurrency: 4 } }), "zh-CN");
  344. expect(queryMaxConcurrency()?.textContent).toBe("最多 4 个子代理同时运行");
  345. });
  346. it.each([
  347. ["omitted", {}],
  348. // 修订的 `null` = 去掉上限:没有上限可说,与缺席同处理。
  349. ["null (the amend 'remove the limit' value)", { max_concurrency: null }],
  350. ["not a positive integer", { max_concurrency: 0 }],
  351. ["not an integer", { max_concurrency: 2.5 }],
  352. ])("renders no row when max_concurrency is %s", (_case, extra) => {
  353. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, ...extra } }));
  354. expect(queryMaxConcurrency()).toBeNull();
  355. expect(document.body.textContent).not.toContain("subagents at once");
  356. });
  357. // ── 子代理模型(docs/dynamic-workflow/presentation.md)──
  358. // 模型只在用户开口要求时才写 `subagent_model`,所以这一行在场就是用户自己提的条件。
  359. // 到窗前的值已被 CLI 的 resolveInput 解析成规范串 `providerId/modelId[$level]`——但规范串是
  360. // 给机器回填用的:屏幕上说模型名与强度词,规范串只住在这一行的 tooltip 里。
  361. // 团队套餐的 provider id 是一串十六进制:这次改动要挡的就是它。
  362. const TEAM_PLAN_MODEL = "4fc7f541-2382-4c32-be11-f021b8d7ed1d/GLM-5.3-Flash$high";
  363. function querySubagentModel(): HTMLElement | null {
  364. return screen.queryByTestId("workflow-permission-subagent-model");
  365. }
  366. it("says which model the subagents run on, by name and not by canonical string", () => {
  367. renderDialog(
  368. buildWorkflowRequest({
  369. raw: {
  370. name: "Research pipeline",
  371. script: SCRIPT,
  372. subagent_model: "zhipu/glm-5.3-flash",
  373. },
  374. }),
  375. );
  376. expect(querySubagentModel()?.textContent).toBe("Subagents run on glm-5.3-flash");
  377. });
  378. it("never shows the provider id, even when it is a team-plan UUID", () => {
  379. renderDialog(
  380. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: TEAM_PLAN_MODEL } }),
  381. );
  382. const row = querySubagentModel();
  383. expect(row?.textContent).toContain("GLM-5.3-Flash");
  384. expect(row?.textContent).not.toContain("4fc7f541");
  385. // 规范串没有丢,它在 tooltip 里——回填与排障都还读得到。
  386. expect(row?.getAttribute("title")).toContain(TEAM_PLAN_MODEL);
  387. });
  388. it("keeps the reasoning level, as a word: the level is part of the choice being approved", () => {
  389. renderDialog(
  390. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: "anthropic/opus-5$high" } }),
  391. );
  392. expect(querySubagentModel()?.textContent).toBe("Subagents run on opus-5 · thinking High");
  393. });
  394. // 与可调的两句同一个次序(docs/dynamic-workflow/presentation.md「The confirmation window」):模型在上、上界在下。
  395. it("sits directly above the concurrency row, and shows on an AmendWorkflow ask too", () => {
  396. renderDialog(
  397. buildAmendRequest({
  398. script: SCRIPT,
  399. run_id: "dwfrun-prev",
  400. predecessor: { status: "completed", owned_by_this_session: false },
  401. max_concurrency: 2,
  402. subagent_model: "zhipu/glm-5.3-flash",
  403. }),
  404. );
  405. expect(querySubagentModel()?.textContent).toBe("Subagents run on glm-5.3-flash");
  406. const blockText =
  407. document.querySelector('[data-workflow-permission-block="true"]')?.textContent ?? "";
  408. expect(blockText.indexOf("Subagents run on")).toBeLessThan(blockText.indexOf("At most 2"));
  409. });
  410. it("localizes the subagent-model row, leaving the model name untranslated", () => {
  411. renderDialog(
  412. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: "anthropic/opus-5$high" } }),
  413. "zh-CN",
  414. );
  415. expect(querySubagentModel()?.textContent).toBe("子代理运行在 opus-5 · 思考 高");
  416. });
  417. it.each([
  418. ["omitted", {}],
  419. // 修订的 `null` = 退回会话模型:没有第二个模型可说,与缺席同处理。
  420. ["null (the amend 'back to the session model' value)", { subagent_model: null }],
  421. ["blank", { subagent_model: " " }],
  422. ["not a string", { subagent_model: { providerId: "zhipu", modelId: "glm-5.3-flash" } }],
  423. ])("renders no row when subagent_model is %s", (_case, extra) => {
  424. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, ...extra } }));
  425. expect(querySubagentModel()).toBeNull();
  426. expect(document.body.textContent).not.toContain("Subagents run on");
  427. });
  428. it("never paints the waiting ask with the success color, and says nothing about compiling", () => {
  429. renderDialog();
  430. // DESIGN.md 把绿色留给等待确认态。表头曾有一枚「compiled」空环灯;2026-09-09 起去掉——
  431. // 能走到确认窗就说明脚本过了校验,这个词对用户没有信息量。
  432. expect(document.body.innerHTML).not.toContain("text-success");
  433. expect(screen.queryByTestId("workflow-card-static-status")).toBeNull();
  434. expect(document.body.textContent).not.toContain("compiled");
  435. });
  436. });
  437. describe("PermissionDialog workflow dispatch", () => {
  438. it("renders the workflow block instead of the fallback JSON dump", () => {
  439. renderDialog();
  440. expect(document.querySelector('[data-workflow-permission-block="true"]')).toBeTruthy();
  441. expect(document.body.textContent).not.toContain('"script"');
  442. expect(document.body.textContent).not.toContain("toolName");
  443. });
  444. it("suppresses the diagnostic CLI reason", () => {
  445. renderDialog();
  446. expect(document.body.textContent).not.toContain(CLI_REASON);
  447. expect(document.body.textContent).not.toContain("createWorkflow.runConfirmation");
  448. });
  449. it("renders Run / Always allow in this session / Deny, in that order", () => {
  450. renderDialog();
  451. const options = screen.getAllByRole("option");
  452. expect(options).toHaveLength(3);
  453. expect(options.map((option) => option.getAttribute("data-permission-option-kind"))).toEqual([
  454. "allowOnce",
  455. "allowAlways",
  456. "rejectOnce",
  457. ]);
  458. expect(document.body.textContent).toContain("Allow");
  459. expect(document.body.textContent).toContain("Deny");
  460. });
  461. // 会话免确认(docs/dynamic-workflow/launch.md「Always allow in this session」):name 命中本地化,描述不沿用项目级文案。
  462. it.each([
  463. ["en-US", "Always allow in this session", "Do not ask again for workflows in this session"],
  464. ["zh-CN", "本会话内始终允许", "本会话内运行工作流不再询问"],
  465. ] as const)("localizes the session option in %s", (locale, label, description) => {
  466. renderDialog(buildWorkflowRequest(), locale);
  467. const option = document.querySelector('[data-permission-option-kind="allowAlways"]')!;
  468. expect(option.textContent).toContain(label);
  469. expect(option.textContent).toContain(description);
  470. expect(option.textContent).not.toContain("same permission request");
  471. expect(option.textContent).not.toContain("相同权限请求");
  472. });
  473. it("clicking the session option responds with optionId allowSession and no feedback", () => {
  474. const onRespond = vi.fn();
  475. renderDialog(buildWorkflowRequest(), "en-US", onRespond);
  476. const session = document.querySelector('[data-permission-option-kind="allowAlways"]')!;
  477. // 未选中的选项第一次点击只做选中,第二次点击应答(既有语义)。
  478. fireEvent.click(session);
  479. expect(onRespond).not.toHaveBeenCalled();
  480. fireEvent.click(session);
  481. expect(onRespond).toHaveBeenCalledTimes(1);
  482. expect(onRespond).toHaveBeenCalledWith(
  483. "perm-workflow",
  484. expect.objectContaining({ optionId: "allowSession" }),
  485. undefined,
  486. );
  487. });
  488. it("the session option is not rendered when the CLI does not offer it (no-always-allow tools)", () => {
  489. const base = buildWorkflowRequest();
  490. renderDialog({
  491. ...base,
  492. options: base.options.filter((option) => option.optionId !== "allowSession"),
  493. });
  494. expect(screen.getAllByRole("option")).toHaveLength(2);
  495. expect(document.querySelectorAll('[data-permission-option-kind="allowAlways"]')).toHaveLength(
  496. 0,
  497. );
  498. });
  499. it("still renders the graph when the ask carries no workflow name", () => {
  500. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT } }));
  501. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  502. // 名称缺失时回退到聊天区同一兜底名。
  503. expect(screen.getByText("Workflow script")).toBeTruthy();
  504. });
  505. });
  506. // ── Refine 选项(docs/dynamic-workflow/launch.md「Refine」)──
  507. // v4 投影对 CreateWorkflow 追加第三选项 workflowRefine;GUI 不把它画成按钮,而是复用其他
  508. // 确认窗同一行编号的行内反馈输入行,提交把 freeText 连同该选项交给应答。
  509. const REFINE_OPTION = {
  510. optionId: "workflowRefine",
  511. kind: "custom",
  512. name: "Refine",
  513. response: { decision: "deny" as const, reason: "Denied" },
  514. };
  515. function buildRefineRequest(): ZCodePermissionRequest {
  516. const base = buildWorkflowRequest();
  517. return { ...base, options: [...base.options, REFINE_OPTION] };
  518. }
  519. function queryRefineInput(): HTMLTextAreaElement | null {
  520. return document.querySelector<HTMLTextAreaElement>(
  521. '[data-permission-feedback-option="workflowRefine"]',
  522. );
  523. }
  524. describe("PermissionDialog workflow refine", () => {
  525. it("Refine 渲染为紧随 Run/Deny 的编号反馈行,而不是第三个选项按钮", () => {
  526. renderDialog(buildRefineRequest(), "en-US");
  527. // 只有 Run / Session / Deny 三个 option 按钮;Refine 不占 listbox 位置。
  528. const options = screen.getAllByRole("option");
  529. expect(options).toHaveLength(3);
  530. expect(screen.queryByRole("option", { name: "Refine" })).toBeNull();
  531. const input = queryRefineInput();
  532. expect(input).toBeTruthy();
  533. expect(input!.closest('[role="listbox"]')).toBeNull();
  534. // 与通用反馈行同一结构:编号 + textarea,编号紧随三个按钮之后(第 7 轮起顺延为 4)。
  535. expect(input!.previousElementSibling?.textContent).toBe("4.");
  536. expect(input!.placeholder).toBe("Describe how the workflow should change…");
  537. expect(input!.getAttribute("aria-label")).toBe("Refine");
  538. // 通用「拒绝并附反馈」行不再额外出现:Refine 就是这个窗的反馈行。
  539. expect(screen.getAllByRole("textbox")).toHaveLength(1);
  540. });
  541. it.each(["Enter", "confirm"])(
  542. "通过 %s 提交把 trim 后的 freeText 连同 Refine 选项交给 onRespond;空白禁发",
  543. (method) => {
  544. const onRespond = vi.fn();
  545. renderDialog(buildRefineRequest(), "en-US", onRespond);
  546. const input = queryRefineInput()!;
  547. const confirm = screen.getByRole("button", { name: "Confirm" }) as HTMLButtonElement;
  548. act(() => input.focus());
  549. // 空白:确认按钮禁用,Enter 也不产生应答。
  550. fireEvent.change(input, { target: { value: " " } });
  551. expect(confirm.disabled).toBe(true);
  552. fireEvent.keyDown(input, { key: "Enter" });
  553. expect(onRespond).not.toHaveBeenCalled();
  554. fireEvent.change(input, { target: { value: " 只保留三个 finder " } });
  555. expect(confirm.disabled).toBe(false);
  556. if (method === "Enter") fireEvent.keyDown(input, { key: "Enter" });
  557. else fireEvent.click(confirm);
  558. expect(onRespond).toHaveBeenCalledTimes(1);
  559. expect(onRespond).toHaveBeenCalledWith(
  560. "perm-workflow",
  561. expect.objectContaining({ optionId: "workflowRefine" }),
  562. // 提交前 trim:CLI broker 对空白 freeText 落普通 deny,不能把纯空白当反馈。
  563. "只保留三个 finder",
  564. );
  565. },
  566. );
  567. it("Esc 只让输入行失焦并保留草稿(同通用反馈行,不再收起什么)", () => {
  568. const onRespond = vi.fn();
  569. renderDialog(buildRefineRequest(), "en-US", onRespond);
  570. const input = queryRefineInput()!;
  571. act(() => input.focus());
  572. fireEvent.change(input, { target: { value: "先跑 lint 再 fan out" } });
  573. fireEvent.keyDown(input, { key: "Escape" });
  574. expect(document.activeElement).not.toBe(input);
  575. expect(queryRefineInput()!.value).toBe("先跑 lint 再 fan out");
  576. expect(onRespond).not.toHaveBeenCalled();
  577. });
  578. it("方向键在 Run / Session / Deny 与 Refine 行之间循环,数字 4 直达 Refine 行", async () => {
  579. renderDialog(buildRefineRequest(), "en-US");
  580. const options = screen.getAllByRole("option");
  581. const input = queryRefineInput()!;
  582. const row = input.parentElement!;
  583. await waitFor(() => {
  584. expect(document.activeElement).toBe(options[0]);
  585. });
  586. fireEvent.keyDown(options[0]!, { key: "ArrowUp" });
  587. await waitFor(() => {
  588. expect(document.activeElement).toBe(input);
  589. });
  590. expect(row.classList.contains("bg-selected")).toBe(true);
  591. expect(options.every((option) => option.getAttribute("aria-selected") === "false")).toBe(true);
  592. fireEvent.keyDown(input, { key: "ArrowDown" });
  593. await waitFor(() => {
  594. expect(document.activeElement).toBe(options[0]);
  595. });
  596. expect(row.classList.contains("bg-selected")).toBe(false);
  597. fireEvent.keyDown(options[0]!, { key: "4" });
  598. await waitFor(() => {
  599. expect(document.activeElement).toBe(input);
  600. });
  601. });
  602. it("Run / Deny 的即时应答语义不受 Refine 行影响;Deny 不携带 Refine 草稿", () => {
  603. const onRespond = vi.fn();
  604. renderDialog(buildRefineRequest(), "en-US", onRespond);
  605. // 草稿属于 Refine:点 Deny 就是普通拒绝,不能让修改意见以普通拒绝理由的身份发出。
  606. const input = queryRefineInput()!;
  607. fireEvent.change(input, { target: { value: "把 fan out 改成串行" } });
  608. const deny = screen.getByRole("option", { name: "Deny" });
  609. // 未选中的选项第一次点击只做选中,第二次点击应答(既有语义)。
  610. fireEvent.click(deny);
  611. expect(onRespond).not.toHaveBeenCalled();
  612. fireEvent.click(deny);
  613. expect(onRespond).toHaveBeenCalledWith(
  614. "perm-workflow",
  615. expect.objectContaining({ optionId: "deny" }),
  616. undefined,
  617. );
  618. });
  619. it("双语渲染 Refine 行文案", () => {
  620. renderDialog(buildRefineRequest(), "zh-CN");
  621. expect(queryRefineInput()!.placeholder).toBe("描述这个工作流应该怎么改…");
  622. expect(queryRefineInput()!.getAttribute("aria-label")).toBe("提出修改");
  623. cleanup();
  624. renderDialog(buildRefineRequest(), "en-US");
  625. expect(queryRefineInput()!.placeholder).toBe("Describe how the workflow should change…");
  626. });
  627. });