workflowPermissionBlock.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. it("opens the script by default when there is no graph to show", () => {
  144. renderDialog(
  145. buildWorkflowRequest({
  146. display: { kind: "create_workflow", ok: true, errorCount: 0, diagnostics: [] },
  147. }),
  148. );
  149. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  150. // 零 step 脚本没有图可看,代码就是唯一内容。
  151. expect(screen.getByTestId("code-block").textContent).toContain('await agent("a")');
  152. expect(screen.getByText("Hide full script")).toBeTruthy();
  153. });
  154. it("treats a participant-less graph as no graph", () => {
  155. renderDialog(
  156. buildWorkflowRequest({
  157. display: {
  158. kind: "create_workflow",
  159. ok: true,
  160. errorCount: 0,
  161. diagnostics: [],
  162. causalityGraph: { steps: [], lanes: [], participants: [], handoffs: [] },
  163. },
  164. }),
  165. );
  166. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  167. expect(screen.getByTestId("code-block")).toBeTruthy();
  168. });
  169. it("degrades to an open script when the ask carries no preview at all", () => {
  170. // 失败路径:prepareApproval 抛错 → 无 preview 的普通 ask。gate 仍然成立,
  171. // 只是没有图,脚本就成了唯一可审计内容。
  172. renderDialog(buildWorkflowRequest({ display: undefined }));
  173. expect(screen.queryByTestId("workflow-timeline")).toBeNull();
  174. expect(screen.getByTestId("code-block").textContent).toContain('await agent("a")');
  175. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  176. });
  177. it("renders header and question without crashing when the input has no script", () => {
  178. renderDialog(buildWorkflowRequest({ display: undefined, raw: { name: "Broken input" } }));
  179. expect(screen.getByText("Run this workflow?")).toBeTruthy();
  180. expect(screen.getByText("Broken input")).toBeTruthy();
  181. expect(screen.queryByTestId("code-block")).toBeNull();
  182. expect(screen.queryByText("Show full script")).toBeNull();
  183. });
  184. // ── 修订的确认窗(docs/dynamic-workflow/launch.md「The `AmendWorkflow` tool」;presentation.md
  185. // 「The confirmation window」)──只对别的会话的 run 出现:问句换词,多一行 lineage。事实从**工具
  186. // 入参**渲染(`run_id` 与 CLI 回填的 `predecessor`),display 一个字节都不变——图仍是 create_workflow。
  187. function buildAmendRequest(raw: Record<string, unknown>): ZCodePermissionRequest {
  188. return buildWorkflowRequest({
  189. kind: "AmendWorkflow",
  190. title: "AmendWorkflow",
  191. description: "amendWorkflow.runConfirmation: user must confirm running the revised script",
  192. raw,
  193. });
  194. }
  195. it("asks 'Amend this workflow?' with the lineage line for an AmendWorkflow ask", () => {
  196. renderDialog(
  197. buildAmendRequest({
  198. name: "Research pipeline",
  199. script: SCRIPT,
  200. run_id: "dwfrun-prev",
  201. predecessor: { status: "completed", owned_by_this_session: false },
  202. }),
  203. );
  204. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("Amend this workflow?");
  205. expect(document.body.textContent).not.toContain("Run this workflow?");
  206. const lineage = document.querySelector('[data-workflow-amends="true"]');
  207. expect(lineage).toBeTruthy();
  208. expect(lineage?.textContent).toContain("Amends run");
  209. expect(lineage?.textContent).toContain("dwfrun-prev");
  210. // 前驱已结算:没有「将被停止」那一句。
  211. expect(lineage?.getAttribute("data-workflow-amends-live")).toBeNull();
  212. expect(lineage?.textContent).not.toContain("still running");
  213. // 图仍是主体,脚本仍是折叠的审计层:lineage 只是多一行。
  214. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  215. expect(screen.queryByTestId("code-block")).toBeNull();
  216. });
  217. it.each(["running", "pending"] as const)(
  218. "says the predecessor will be stopped when it is still in flight (%s)",
  219. (status) => {
  220. renderDialog(
  221. buildAmendRequest({
  222. script: SCRIPT,
  223. run_id: "dwfrun-live",
  224. predecessor: { status, owned_by_this_session: false },
  225. }),
  226. );
  227. const lineage = document.querySelector('[data-workflow-amends="true"]');
  228. expect(lineage?.getAttribute("data-workflow-amends-live")).toBe("true");
  229. expect(lineage?.textContent).toContain("still running, will be stopped");
  230. },
  231. );
  232. it("localizes the amend title and lineage", () => {
  233. renderDialog(
  234. buildAmendRequest({
  235. name: "Research pipeline",
  236. script: SCRIPT,
  237. run_id: "dwfrun-prev",
  238. predecessor: { status: "running", owned_by_this_session: false },
  239. }),
  240. "zh-CN",
  241. );
  242. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("调整此工作流?");
  243. const lineage = document.querySelector('[data-workflow-amends="true"]');
  244. expect(lineage?.textContent).toContain("调整 run");
  245. expect(lineage?.textContent).toContain("dwfrun-prev");
  246. expect(lineage?.textContent).toContain("仍在运行,将被停止");
  247. });
  248. // 省略 script 的修订(docs/dynamic-workflow/launch.md「Keeping the predecessor's script」):CLI 已把
  249. // 前驱的脚本回填进入参并盖上 `predecessor.script_inherited`。窗上照常画图、照常可展开脚本——审的
  250. // 就是将要跑的那一份——lineage 行多说一句「脚本不变」,让用户知道这次改的只是设定。
  251. it("says 'script unchanged' on the lineage line when the amend keeps the predecessor's script", () => {
  252. renderDialog(
  253. buildAmendRequest({
  254. script: SCRIPT,
  255. run_id: "dwfrun-prev",
  256. max_concurrency: 2,
  257. predecessor: { status: "running", owned_by_this_session: false, script_inherited: true },
  258. }),
  259. );
  260. const lineage = document.querySelector('[data-workflow-amends="true"]');
  261. expect(lineage?.getAttribute("data-workflow-amends-script-inherited")).toBe("true");
  262. expect(lineage?.textContent).toContain("dwfrun-prev");
  263. expect(lineage?.textContent).toContain("script unchanged");
  264. expect(lineage?.textContent).toContain("still running, will be stopped");
  265. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  266. expect(screen.getByText("Show full script")).toBeTruthy();
  267. expect(screen.getByTestId("workflow-permission-max-concurrency").textContent).toBe(
  268. "At most 2 subagents at once",
  269. );
  270. });
  271. it("says nothing about the script when the amend passes one", () => {
  272. renderDialog(
  273. buildAmendRequest({
  274. script: SCRIPT,
  275. run_id: "dwfrun-prev",
  276. predecessor: { status: "completed", owned_by_this_session: false },
  277. }),
  278. );
  279. const lineage = document.querySelector('[data-workflow-amends="true"]');
  280. expect(lineage?.getAttribute("data-workflow-amends-script-inherited")).toBeNull();
  281. expect(lineage?.textContent).not.toContain("script unchanged");
  282. });
  283. it("localizes 'script unchanged'", () => {
  284. renderDialog(
  285. buildAmendRequest({
  286. script: SCRIPT,
  287. run_id: "dwfrun-prev",
  288. predecessor: { status: "completed", owned_by_this_session: false, script_inherited: true },
  289. }),
  290. "zh-CN",
  291. );
  292. const lineage = document.querySelector('[data-workflow-amends="true"]');
  293. expect(lineage?.textContent).toContain("脚本不变");
  294. });
  295. it("omits the lineage line entirely for a CreateWorkflow ask", () => {
  296. // CreateWorkflow 没有前驱(也不再有 resume_from):不留空行、不留占位词、问句照旧。
  297. renderDialog();
  298. expect(screen.getByTestId("workflow-card-kind").textContent).toBe("Run this workflow?");
  299. expect(document.querySelector('[data-workflow-amends="true"]')).toBeNull();
  300. expect(document.body.textContent).not.toContain("Amends run");
  301. });
  302. it("ignores a blank run_id instead of rendering an empty lineage", () => {
  303. renderDialog(buildAmendRequest({ script: SCRIPT, run_id: " " }));
  304. expect(document.querySelector('[data-workflow-amends="true"]')).toBeNull();
  305. });
  306. // ── 并发上限(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)──
  307. // 模型只在用户要求时才写 `max_concurrency`,所以这一行在场就是用户自己提的条件。
  308. // 与 lineage 同一条纪律:事实从**工具入参**读,display 一个字节都不变。
  309. function queryMaxConcurrency(): HTMLElement | null {
  310. return screen.queryByTestId("workflow-permission-max-concurrency");
  311. }
  312. it("says how many subagents may run at once when the input carries max_concurrency", () => {
  313. renderDialog(
  314. buildWorkflowRequest({
  315. raw: { name: "Research pipeline", script: SCRIPT, max_concurrency: 3 },
  316. }),
  317. );
  318. expect(queryMaxConcurrency()?.textContent).toBe("At most 3 subagents at once");
  319. });
  320. it("shows the same row for an AmendWorkflow ask, right after the lineage row", () => {
  321. renderDialog(
  322. buildAmendRequest({
  323. script: SCRIPT,
  324. run_id: "dwfrun-prev",
  325. predecessor: { status: "completed", owned_by_this_session: false },
  326. max_concurrency: 2,
  327. }),
  328. );
  329. expect(queryMaxConcurrency()?.textContent).toBe("At most 2 subagents at once");
  330. const blockText =
  331. document.querySelector('[data-workflow-permission-block="true"]')?.textContent ?? "";
  332. expect(blockText.indexOf("Amends run")).toBeLessThan(blockText.indexOf("At most 2"));
  333. });
  334. it("localizes the row", () => {
  335. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, max_concurrency: 4 } }), "zh-CN");
  336. expect(queryMaxConcurrency()?.textContent).toBe("最多 4 个子代理同时运行");
  337. });
  338. it.each([
  339. ["omitted", {}],
  340. // 修订的 `null` = 去掉上限:没有上限可说,与缺席同处理。
  341. ["null (the amend 'remove the limit' value)", { max_concurrency: null }],
  342. ["not a positive integer", { max_concurrency: 0 }],
  343. ["not an integer", { max_concurrency: 2.5 }],
  344. ])("renders no row when max_concurrency is %s", (_case, extra) => {
  345. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, ...extra } }));
  346. expect(queryMaxConcurrency()).toBeNull();
  347. expect(document.body.textContent).not.toContain("subagents at once");
  348. });
  349. // ── 子代理模型(docs/dynamic-workflow/presentation.md)──
  350. // 模型只在用户开口要求时才写 `subagent_model`,所以这一行在场就是用户自己提的条件。
  351. // 到窗前的值已被 CLI 的 resolveInput 解析成规范串 `providerId/modelId[$level]`——但规范串是
  352. // 给机器回填用的:屏幕上说模型名与强度词,规范串只住在这一行的 tooltip 里。
  353. // 团队套餐的 provider id 是一串十六进制:这次改动要挡的就是它。
  354. const TEAM_PLAN_MODEL = "4fc7f541-2382-4c32-be11-f021b8d7ed1d/GLM-5.3-Flash$high";
  355. function querySubagentModel(): HTMLElement | null {
  356. return screen.queryByTestId("workflow-permission-subagent-model");
  357. }
  358. it("says which model the subagents run on, by name and not by canonical string", () => {
  359. renderDialog(
  360. buildWorkflowRequest({
  361. raw: {
  362. name: "Research pipeline",
  363. script: SCRIPT,
  364. subagent_model: "zhipu/glm-5.3-flash",
  365. },
  366. }),
  367. );
  368. expect(querySubagentModel()?.textContent).toBe("Subagents run on glm-5.3-flash");
  369. });
  370. it("never shows the provider id, even when it is a team-plan UUID", () => {
  371. renderDialog(
  372. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: TEAM_PLAN_MODEL } }),
  373. );
  374. const row = querySubagentModel();
  375. expect(row?.textContent).toContain("GLM-5.3-Flash");
  376. expect(row?.textContent).not.toContain("4fc7f541");
  377. // 规范串没有丢,它在 tooltip 里——回填与排障都还读得到。
  378. expect(row?.getAttribute("title")).toContain(TEAM_PLAN_MODEL);
  379. });
  380. it("keeps the reasoning level, as a word: the level is part of the choice being approved", () => {
  381. renderDialog(
  382. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: "anthropic/opus-5$high" } }),
  383. );
  384. expect(querySubagentModel()?.textContent).toBe("Subagents run on opus-5 · thinking High");
  385. });
  386. // 与可调的两句同一个次序(docs/dynamic-workflow/presentation.md「The confirmation window」):模型在上、上界在下。
  387. it("sits directly above the concurrency row, and shows on an AmendWorkflow ask too", () => {
  388. renderDialog(
  389. buildAmendRequest({
  390. script: SCRIPT,
  391. run_id: "dwfrun-prev",
  392. predecessor: { status: "completed", owned_by_this_session: false },
  393. max_concurrency: 2,
  394. subagent_model: "zhipu/glm-5.3-flash",
  395. }),
  396. );
  397. expect(querySubagentModel()?.textContent).toBe("Subagents run on glm-5.3-flash");
  398. const blockText =
  399. document.querySelector('[data-workflow-permission-block="true"]')?.textContent ?? "";
  400. expect(blockText.indexOf("Subagents run on")).toBeLessThan(blockText.indexOf("At most 2"));
  401. });
  402. it("localizes the subagent-model row, leaving the model name untranslated", () => {
  403. renderDialog(
  404. buildWorkflowRequest({ raw: { script: SCRIPT, subagent_model: "anthropic/opus-5$high" } }),
  405. "zh-CN",
  406. );
  407. expect(querySubagentModel()?.textContent).toBe("子代理运行在 opus-5 · 思考 高");
  408. });
  409. it.each([
  410. ["omitted", {}],
  411. // 修订的 `null` = 退回会话模型:没有第二个模型可说,与缺席同处理。
  412. ["null (the amend 'back to the session model' value)", { subagent_model: null }],
  413. ["blank", { subagent_model: " " }],
  414. ["not a string", { subagent_model: { providerId: "zhipu", modelId: "glm-5.3-flash" } }],
  415. ])("renders no row when subagent_model is %s", (_case, extra) => {
  416. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT, ...extra } }));
  417. expect(querySubagentModel()).toBeNull();
  418. expect(document.body.textContent).not.toContain("Subagents run on");
  419. });
  420. });
  421. describe("PermissionDialog workflow dispatch", () => {
  422. it("renders the workflow block instead of the fallback JSON dump", () => {
  423. renderDialog();
  424. expect(document.querySelector('[data-workflow-permission-block="true"]')).toBeTruthy();
  425. expect(document.body.textContent).not.toContain('"script"');
  426. expect(document.body.textContent).not.toContain("toolName");
  427. });
  428. it("suppresses the diagnostic CLI reason", () => {
  429. renderDialog();
  430. expect(document.body.textContent).not.toContain(CLI_REASON);
  431. expect(document.body.textContent).not.toContain("createWorkflow.runConfirmation");
  432. });
  433. it("renders Run / Always allow in this session / Deny, in that order", () => {
  434. renderDialog();
  435. const options = screen.getAllByRole("option");
  436. expect(options).toHaveLength(3);
  437. expect(options.map((option) => option.getAttribute("data-permission-option-kind"))).toEqual([
  438. "allowOnce",
  439. "allowAlways",
  440. "rejectOnce",
  441. ]);
  442. expect(document.body.textContent).toContain("Allow");
  443. expect(document.body.textContent).toContain("Deny");
  444. });
  445. // 会话免确认(docs/dynamic-workflow/launch.md「Always allow in this session」):name 命中本地化,描述不沿用项目级文案。
  446. it.each([
  447. ["en-US", "Always allow in this session", "Do not ask again for workflows in this session"],
  448. ["zh-CN", "本会话内始终允许", "本会话内运行工作流不再询问"],
  449. ] as const)("localizes the session option in %s", (locale, label, description) => {
  450. renderDialog(buildWorkflowRequest(), locale);
  451. const option = document.querySelector('[data-permission-option-kind="allowAlways"]')!;
  452. expect(option.textContent).toContain(label);
  453. expect(option.textContent).toContain(description);
  454. expect(option.textContent).not.toContain("same permission request");
  455. expect(option.textContent).not.toContain("相同权限请求");
  456. });
  457. it("clicking the session option responds with optionId allowSession and no feedback", () => {
  458. const onRespond = vi.fn();
  459. renderDialog(buildWorkflowRequest(), "en-US", onRespond);
  460. const session = document.querySelector('[data-permission-option-kind="allowAlways"]')!;
  461. // 未选中的选项第一次点击只做选中,第二次点击应答(既有语义)。
  462. fireEvent.click(session);
  463. expect(onRespond).not.toHaveBeenCalled();
  464. fireEvent.click(session);
  465. expect(onRespond).toHaveBeenCalledTimes(1);
  466. expect(onRespond).toHaveBeenCalledWith(
  467. "perm-workflow",
  468. expect.objectContaining({ optionId: "allowSession" }),
  469. undefined,
  470. );
  471. });
  472. it("the session option is not rendered when the CLI does not offer it (no-always-allow tools)", () => {
  473. const base = buildWorkflowRequest();
  474. renderDialog({
  475. ...base,
  476. options: base.options.filter((option) => option.optionId !== "allowSession"),
  477. });
  478. expect(screen.getAllByRole("option")).toHaveLength(2);
  479. expect(document.querySelectorAll('[data-permission-option-kind="allowAlways"]')).toHaveLength(
  480. 0,
  481. );
  482. });
  483. it("still renders the graph when the ask carries no workflow name", () => {
  484. renderDialog(buildWorkflowRequest({ raw: { script: SCRIPT } }));
  485. expect(screen.getByTestId("workflow-timeline")).toBeTruthy();
  486. // 名称缺失时回退到聊天区同一兜底名。
  487. expect(screen.getByText("Workflow script")).toBeTruthy();
  488. });
  489. });
  490. // ── Refine 选项(docs/dynamic-workflow/launch.md「Refine」)──
  491. // v4 投影对 CreateWorkflow 追加第三选项 workflowRefine;GUI 不把它画成按钮,而是复用其他
  492. // 确认窗同一行编号的行内反馈输入行,提交把 freeText 连同该选项交给应答。
  493. const REFINE_OPTION = {
  494. optionId: "workflowRefine",
  495. kind: "custom",
  496. name: "Refine",
  497. response: { decision: "deny" as const, reason: "Denied" },
  498. };
  499. function buildRefineRequest(): ZCodePermissionRequest {
  500. const base = buildWorkflowRequest();
  501. return { ...base, options: [...base.options, REFINE_OPTION] };
  502. }
  503. function queryRefineInput(): HTMLTextAreaElement | null {
  504. return document.querySelector<HTMLTextAreaElement>(
  505. '[data-permission-feedback-option="workflowRefine"]',
  506. );
  507. }
  508. describe("PermissionDialog workflow refine", () => {
  509. it("Refine 渲染为紧随 Run/Deny 的编号反馈行,而不是第三个选项按钮", () => {
  510. renderDialog(buildRefineRequest(), "en-US");
  511. // 只有 Run / Session / Deny 三个 option 按钮;Refine 不占 listbox 位置。
  512. const options = screen.getAllByRole("option");
  513. expect(options).toHaveLength(3);
  514. expect(screen.queryByRole("option", { name: "Refine" })).toBeNull();
  515. const input = queryRefineInput();
  516. expect(input).toBeTruthy();
  517. expect(input!.closest('[role="listbox"]')).toBeNull();
  518. // 与通用反馈行同一结构:编号 + textarea,编号紧随三个按钮之后(第 7 轮起顺延为 4)。
  519. expect(input!.previousElementSibling?.textContent).toBe("4.");
  520. expect(input!.placeholder).toBe("Describe how the workflow should change…");
  521. expect(input!.getAttribute("aria-label")).toBe("Refine");
  522. // 通用「拒绝并附反馈」行不再额外出现:Refine 就是这个窗的反馈行。
  523. expect(screen.getAllByRole("textbox")).toHaveLength(1);
  524. });
  525. it.each(["Enter", "confirm"])(
  526. "通过 %s 提交把 trim 后的 freeText 连同 Refine 选项交给 onRespond;空白禁发",
  527. (method) => {
  528. const onRespond = vi.fn();
  529. renderDialog(buildRefineRequest(), "en-US", onRespond);
  530. const input = queryRefineInput()!;
  531. const confirm = screen.getByRole("button", { name: "Confirm" }) as HTMLButtonElement;
  532. act(() => input.focus());
  533. // 空白:确认按钮禁用,Enter 也不产生应答。
  534. fireEvent.change(input, { target: { value: " " } });
  535. expect(confirm.disabled).toBe(true);
  536. fireEvent.keyDown(input, { key: "Enter" });
  537. expect(onRespond).not.toHaveBeenCalled();
  538. fireEvent.change(input, { target: { value: " 只保留三个 finder " } });
  539. expect(confirm.disabled).toBe(false);
  540. if (method === "Enter") fireEvent.keyDown(input, { key: "Enter" });
  541. else fireEvent.click(confirm);
  542. expect(onRespond).toHaveBeenCalledTimes(1);
  543. expect(onRespond).toHaveBeenCalledWith(
  544. "perm-workflow",
  545. expect.objectContaining({ optionId: "workflowRefine" }),
  546. // 提交前 trim:CLI broker 对空白 freeText 落普通 deny,不能把纯空白当反馈。
  547. "只保留三个 finder",
  548. );
  549. },
  550. );
  551. it("Esc 只让输入行失焦并保留草稿(同通用反馈行,不再收起什么)", () => {
  552. const onRespond = vi.fn();
  553. renderDialog(buildRefineRequest(), "en-US", onRespond);
  554. const input = queryRefineInput()!;
  555. act(() => input.focus());
  556. fireEvent.change(input, { target: { value: "先跑 lint 再 fan out" } });
  557. fireEvent.keyDown(input, { key: "Escape" });
  558. expect(document.activeElement).not.toBe(input);
  559. expect(queryRefineInput()!.value).toBe("先跑 lint 再 fan out");
  560. expect(onRespond).not.toHaveBeenCalled();
  561. });
  562. it("方向键在 Run / Session / Deny 与 Refine 行之间循环,数字 4 直达 Refine 行", async () => {
  563. renderDialog(buildRefineRequest(), "en-US");
  564. const options = screen.getAllByRole("option");
  565. const input = queryRefineInput()!;
  566. const row = input.parentElement!;
  567. await waitFor(() => {
  568. expect(document.activeElement).toBe(options[0]);
  569. });
  570. fireEvent.keyDown(options[0]!, { key: "ArrowUp" });
  571. await waitFor(() => {
  572. expect(document.activeElement).toBe(input);
  573. });
  574. expect(row.classList.contains("bg-selected")).toBe(true);
  575. expect(options.every((option) => option.getAttribute("aria-selected") === "false")).toBe(true);
  576. fireEvent.keyDown(input, { key: "ArrowDown" });
  577. await waitFor(() => {
  578. expect(document.activeElement).toBe(options[0]);
  579. });
  580. expect(row.classList.contains("bg-selected")).toBe(false);
  581. fireEvent.keyDown(options[0]!, { key: "4" });
  582. await waitFor(() => {
  583. expect(document.activeElement).toBe(input);
  584. });
  585. });
  586. it("Run / Deny 的即时应答语义不受 Refine 行影响;Deny 不携带 Refine 草稿", () => {
  587. const onRespond = vi.fn();
  588. renderDialog(buildRefineRequest(), "en-US", onRespond);
  589. // 草稿属于 Refine:点 Deny 就是普通拒绝,不能让修改意见以普通拒绝理由的身份发出。
  590. const input = queryRefineInput()!;
  591. fireEvent.change(input, { target: { value: "把 fan out 改成串行" } });
  592. const deny = screen.getByRole("option", { name: "Deny" });
  593. // 未选中的选项第一次点击只做选中,第二次点击应答(既有语义)。
  594. fireEvent.click(deny);
  595. expect(onRespond).not.toHaveBeenCalled();
  596. fireEvent.click(deny);
  597. expect(onRespond).toHaveBeenCalledWith(
  598. "perm-workflow",
  599. expect.objectContaining({ optionId: "deny" }),
  600. undefined,
  601. );
  602. });
  603. it("双语渲染 Refine 行文案", () => {
  604. renderDialog(buildRefineRequest(), "zh-CN");
  605. expect(queryRefineInput()!.placeholder).toBe("描述这个工作流应该怎么改…");
  606. expect(queryRefineInput()!.getAttribute("aria-label")).toBe("提出修改");
  607. cleanup();
  608. renderDialog(buildRefineRequest(), "en-US");
  609. expect(queryRefineInput()!.placeholder).toBe("Describe how the workflow should change…");
  610. });
  611. });