PermissionDialog.tsx 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. /* eslint-disable max-lines */
  2. import {
  3. useCallback,
  4. useEffect,
  5. useMemo,
  6. useRef,
  7. useState,
  8. type KeyboardEvent as ReactKeyboardEvent,
  9. type ReactNode,
  10. } from "react";
  11. import {
  12. OFFICIAL_CUA_PERMISSION_RULE_TOOL_NAME,
  13. WORKFLOW_REFINE_PERMISSION_OPTION_ID,
  14. type ZCodePermissionOption,
  15. type ZCodePermissionRequest,
  16. type ZCodeProvider,
  17. } from "@zcode/shared";
  18. import { MAX_PERMISSION_FEEDBACK_CHARS } from "@zcode/shared/zcode-protocol-v4";
  19. import { Button } from "@/components/ui/button.js";
  20. import { cn } from "@/components/lib/utils.js";
  21. import { Textarea } from "@/components/ui/textarea.js";
  22. import { isImeComposingKeyEvent } from "@/lib/imeComposition.js";
  23. import {
  24. resolveMobileInputTextSizeClassName,
  25. shouldAvoidIosInputFocusZoom,
  26. useIsMobileTextInputViewport,
  27. } from "@/lib/mobileTextInput.js";
  28. import {
  29. getPermissionOptionDisplayKind,
  30. getPermissionRequestPreview,
  31. shouldPreferPermissionOptionName,
  32. sortPermissionOptions,
  33. type PermissionRequestScope,
  34. } from "@/lib/permissionRequest.js";
  35. import type { TaskChatToolCall } from "@/lib/taskChatMessageTypes.js";
  36. import {
  37. readRawToolCallFileSummaries,
  38. type ToolCallBlockRenderContext,
  39. } from "@/ToolCallBlocks/shared.js";
  40. import { isPlainRecord, readRawToolCallInput } from "@/ToolCallBlocks/fileSummaryTypes.js";
  41. import { ToolLayout } from "@/ToolCallBlocks/ToolLayout.js";
  42. import { EditToolCallBlock } from "@/ToolCallBlocks/renderers/edit.js";
  43. import { ExecuteToolCallBlock } from "@/ToolCallBlocks/renderers/execute.js";
  44. import { FallbackToolCallBlock } from "@/ToolCallBlocks/renderers/fallback.js";
  45. import { SearchToolCallBlock } from "@/ToolCallBlocks/renderers/search.js";
  46. import { SkillToolCallBlock } from "@/ToolCallBlocks/renderers/skill.js";
  47. import { resolveToolCallIdentity } from "@/lib/toolIdentity.js";
  48. import { InteractionRequestOriginBadge } from "@/InteractionRequestOriginBadge.js";
  49. import { WorkflowPermissionBlock } from "@/WorkflowPermissionBlock.js";
  50. import {
  51. focusLastWorkflowSettingsControl,
  52. isWorkflowSettingsCarrier,
  53. usePermissionWorkflowSettings,
  54. workflowAdjustedOptionDescriptionId,
  55. } from "@/permissionWorkflowSettings.js";
  56. import { SaveWorkflowPermissionBlock } from "@/SaveWorkflowPermissionBlock.js";
  57. import { isSaveWorkflowToolCall } from "@/lib/workflowToolNames.js";
  58. import { useZCodeStoreWithDefault } from "@/store/StoreProvider.js";
  59. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  60. import { useZCodeIntl } from "./i18n/IntlProvider.js";
  61. import { Info, LoaderIcon, WrenchIcon } from "lucide-react";
  62. const MCP_PERMISSION_TOOL_ICON = <WrenchIcon className="size-4 shrink-0 text-foreground-subtle" />;
  63. type PermissionBlockKind =
  64. | "edit"
  65. | "execute"
  66. | "mcp"
  67. | "search"
  68. | "skill"
  69. | "workflow"
  70. | "saveWorkflow"
  71. | "fallback";
  72. interface PermissionBlockInteraction {
  73. canToggle: boolean;
  74. forceOpen: boolean;
  75. }
  76. interface PermissionRuleScope {
  77. display: string;
  78. truncated: boolean;
  79. }
  80. const PERMISSION_RULE_SCOPE_MAX_DISPLAY_CHARS = 160;
  81. const NON_USER_FACING_PERMISSION_REASONS = new Set([
  82. "High risk tools require explicit approval",
  83. "Tool has side effects and requires approval",
  84. ]);
  85. function formatPermissionRuleScope(content: string): PermissionRuleScope {
  86. const lineBreakIndex = content.search(/\r?\n/);
  87. const firstLine = lineBreakIndex === -1 ? content : content.slice(0, lineBreakIndex);
  88. const truncated =
  89. lineBreakIndex !== -1 || firstLine.length > PERMISSION_RULE_SCOPE_MAX_DISPLAY_CHARS;
  90. const suffix = " …";
  91. const visible = firstLine
  92. .slice(0, PERMISSION_RULE_SCOPE_MAX_DISPLAY_CHARS - suffix.length)
  93. .trimEnd();
  94. return { display: `${visible}${suffix}`, truncated };
  95. }
  96. function readPermissionRuleScopes(option: ZCodePermissionOption): PermissionRuleScope[] {
  97. const scopes: PermissionRuleScope[] = [];
  98. for (const update of option.response?.permissionUpdates ?? []) {
  99. if (update.type !== "addRules" || update.behavior !== "allow") continue;
  100. for (const rule of update.rules) {
  101. if (rule.toolName.toLowerCase() !== "bash") continue;
  102. const content = rule.ruleContent?.trim();
  103. if (!content?.endsWith(":*")) continue;
  104. scopes.push(formatPermissionRuleScope(content.slice(0, -2)));
  105. }
  106. }
  107. return scopes.slice(0, 5);
  108. }
  109. function isOfficialCuaProjectPermission(option: ZCodePermissionOption): boolean {
  110. return (option.response?.permissionUpdates ?? []).some(
  111. (update) =>
  112. update.type === "addRules" &&
  113. update.behavior === "allow" &&
  114. update.rules.some((rule) => rule.toolName === OFFICIAL_CUA_PERMISSION_RULE_TOOL_NAME),
  115. );
  116. }
  117. /**
  118. * workflow Refine(拒绝并附修改意见)。
  119. * 该选项不渲染成按钮,而是作为反馈行的应答目标:用户在其他确认窗同一行编号输入行里写修改意见,
  120. * 提交时应答携带 freeText,CLI broker 据此把 deny 升级为带 workflow_refine_feedback 的用户反馈。
  121. */
  122. function isWorkflowRefineOption(option: ZCodePermissionOption): boolean {
  123. return option.optionId === WORKFLOW_REFINE_PERMISSION_OPTION_ID;
  124. }
  125. function InlinePermissionPrefixScopes({ scopes }: { scopes: readonly PermissionRuleScope[] }) {
  126. if (scopes.length === 0) return null;
  127. return (
  128. <span
  129. className="flex min-w-0 flex-1 basis-48 flex-col gap-1"
  130. data-permission-rule-scopes="true"
  131. data-permission-rule-prefixes="true"
  132. >
  133. {scopes.map((scope, index) => (
  134. <code
  135. key={`${scope.display}:${index}`}
  136. className="min-w-0 whitespace-pre-wrap break-all font-mono text-ui-base leading-5 text-foreground-subtle"
  137. data-permission-rule-scope="prefix"
  138. data-permission-rule-scope-truncated={scope.truncated ? "true" : undefined}
  139. >
  140. {scope.display}
  141. </code>
  142. ))}
  143. </span>
  144. );
  145. }
  146. function getOptionLabelMessageId(kind: string): string | null {
  147. switch (getPermissionOptionDisplayKind(kind)) {
  148. case "allowOnce":
  149. return "chat.permission.approve";
  150. case "allowAlways":
  151. return "chat.permission.approveAlways";
  152. case "rejectOnce":
  153. return "chat.permission.deny";
  154. case "rejectAlways":
  155. return "chat.permission.denyAlways";
  156. default:
  157. return null;
  158. }
  159. }
  160. const PROVIDER_PERMISSION_OPTION_NAME_LABELS: Partial<
  161. Record<ZCodeProvider, Record<string, string>>
  162. > = {
  163. glm: {
  164. // GLM/ZCode Agent 通过 ZCode Agent 发来的项目级记忆授权文案是英文原文。
  165. // 这里把已知 provider-native 权限文案统一归一到 i18n,避免被当成自定义选项直出英文。
  166. "always allow in this project": "chat.permission.allowForProject",
  167. },
  168. };
  169. interface PermissionOptionNameMessageIds {
  170. label: string;
  171. /** 按 name 命中时可覆盖 kind 推导的描述:会话级选项不能沿用「相同请求不再询问」的项目级文案。 */
  172. description?: string;
  173. }
  174. const GLOBAL_PERMISSION_OPTION_NAME_LABELS: Record<string, PermissionOptionNameMessageIds> = {
  175. "full access": {
  176. label: "chat.permission.fullAccess",
  177. description: "chat.permission.fullAccess.description",
  178. },
  179. "always allow in this project": { label: "chat.permission.allowForProject" },
  180. "always allow computer use in this project": { label: "chat.permission.cua.allowForProject" },
  181. // workflow 运行确认窗的会话免确认:
  182. // CLI 侧 name 是匹配键,wire kind 是 allowAlways(排序 / 样式同 always allow)。
  183. "always allow in this session": {
  184. label: "chat.permission.workflow.allowForSession",
  185. description: "chat.permission.workflow.allowForSession.description",
  186. },
  187. };
  188. function getProviderOptionNameMessageIds(
  189. provider: ZCodeProvider | undefined,
  190. name: string,
  191. ): PermissionOptionNameMessageIds | null {
  192. const normalizedName = name.trim().replace(/\s+/g, " ").toLowerCase();
  193. const global = GLOBAL_PERMISSION_OPTION_NAME_LABELS[normalizedName];
  194. if (global) {
  195. return global;
  196. }
  197. const providerLabel = provider
  198. ? PROVIDER_PERMISSION_OPTION_NAME_LABELS[provider]?.[normalizedName]
  199. : undefined;
  200. return providerLabel ? { label: providerLabel } : null;
  201. }
  202. function getOptionDescriptionMessageId(kind: string, scope: PermissionRequestScope): string | null {
  203. switch (getPermissionOptionDisplayKind(kind)) {
  204. case "allowOnce":
  205. return "chat.permission.allowOnce.description";
  206. case "allowAlways":
  207. return `chat.permission.allowAlways.description.${scope}`;
  208. case "rejectOnce":
  209. return "chat.permission.denyOnce.description";
  210. case "rejectAlways":
  211. return `chat.permission.denyAlways.description.${scope}`;
  212. default:
  213. return null;
  214. }
  215. }
  216. function readNonEmptyString(value: unknown): string | null {
  217. return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
  218. }
  219. function readUserFacingPermissionReason(value: unknown): string | null {
  220. const reason = readNonEmptyString(value);
  221. // 通用权限策略原因用于协议诊断,不是能帮助用户判断本次操作的具体说明。
  222. // 之前 UI 无差别展示 reason,导致权限弹窗重复出现和“等待确认”语义相同的英文文案。
  223. return reason && !NON_USER_FACING_PERMISSION_REASONS.has(reason) ? reason : null;
  224. }
  225. function getPermissionDisplayReason(request: ZCodePermissionRequest): string | null {
  226. const rawInput = readRawToolCallInput(request.raw);
  227. const inputReason = isPlainRecord(rawInput)
  228. ? (readUserFacingPermissionReason(rawInput.description) ??
  229. readUserFacingPermissionReason(rawInput.reason) ??
  230. readUserFacingPermissionReason(rawInput.summary))
  231. : null;
  232. const rawReason = isPlainRecord(request.raw)
  233. ? readUserFacingPermissionReason(request.raw.reason)
  234. : null;
  235. return inputReason ?? readUserFacingPermissionReason(request.description) ?? rawReason;
  236. }
  237. function getMcpPermissionToolName(toolCall: TaskChatToolCall): string | null {
  238. const rawToolName = isPlainRecord(toolCall.raw)
  239. ? (readNonEmptyString(toolCall.raw.toolName) ?? readNonEmptyString(toolCall.raw.tool_name))
  240. : null;
  241. const toolName =
  242. readNonEmptyString(toolCall.toolName) ??
  243. rawToolName ??
  244. readNonEmptyString(toolCall.kind) ??
  245. readNonEmptyString(toolCall.title);
  246. return toolName?.startsWith("mcp__") ? toolName : null;
  247. }
  248. function getMcpPermissionReason(toolCall: TaskChatToolCall): string | null {
  249. return isPlainRecord(toolCall.raw) ? readNonEmptyString(toolCall.raw.reason) : null;
  250. }
  251. function resolvePermissionBlockKind(
  252. preview: ReturnType<typeof getPermissionRequestPreview>,
  253. toolCall: TaskChatToolCall,
  254. rawFileSummaries: ToolCallBlockRenderContext["rawFileSummaries"],
  255. ): PermissionBlockKind {
  256. // SaveWorkflow 按**工具名**最先判定,早于文件摘要与 family 分流。它归一化入参里带着 `path`
  257. // 与完整 `script`,任何一条「看起来像写文件」的启发式都可能把它吸进 edit 块;而 workflow
  258. // family 一旦登记这个名字,它又会掉进运行确认块(图 + Refine,对一次写盘完全是错的语言)。
  259. if (isSaveWorkflowToolCall(toolCall)) {
  260. return "saveWorkflow";
  261. }
  262. if (rawFileSummaries.length > 0 || preview.fileChanges.length > 0) {
  263. return "edit";
  264. }
  265. const identity = resolveToolCallIdentity(toolCall);
  266. if (getMcpPermissionToolName(toolCall)) {
  267. // MCP 权限请求不是普通未知工具;以前走 fallback 会把 raw JSON 摊开,并把工具名显示两次。
  268. // 这里单独展示 MCP 名称和协议里的 reason,避免用户在审批时读调试 payload。
  269. return "mcp";
  270. }
  271. // 权限弹窗之前单独猜 kind/title/rawInput.skill,和聊天区分流规则会漂移。
  272. // 这里复用固定 tool identity,让 Skill 权限请求在确认前后都走同一套语义。
  273. if (identity.family === "skill") {
  274. return "skill";
  275. }
  276. if (identity.family === "workflow") {
  277. // 工作流确认窗的主体是因果图 + 折叠脚本,和聊天区同一 tool identity 分流;
  278. // 必须早于 search/execute 判定,否则脚本里的命令片段会把它误判成普通命令确认。
  279. return "workflow";
  280. }
  281. if (identity.family === "search") {
  282. // WebFetch/WebSearch 权限请求以前落到 fallback,会把整包 toolCall JSON 打出来。
  283. // 这里和聊天区一样走 search renderer,只展示用户关心的 URL/query 摘要。
  284. return "search";
  285. }
  286. if (preview.command) {
  287. return "execute";
  288. }
  289. return "fallback";
  290. }
  291. function getPermissionBlockInteraction(blockKind: PermissionBlockKind): PermissionBlockInteraction {
  292. switch (blockKind) {
  293. case "edit":
  294. return {
  295. canToggle: false,
  296. forceOpen: false,
  297. };
  298. case "mcp":
  299. case "skill":
  300. case "search":
  301. case "execute":
  302. case "workflow":
  303. case "saveWorkflow":
  304. case "fallback":
  305. // 这里是权限弹窗的中间态展示,不提供收起/展开交互,避免用户把关键内容藏起来。
  306. // workflow / saveWorkflow 只为穷尽性列在这里:它们由各自的专用块直接渲染,不走通用块,
  307. // 块内脚本折叠是 spec 记录的刻意例外(图、名称与落点仍不可折叠)。
  308. return {
  309. canToggle: false,
  310. forceOpen: true,
  311. };
  312. }
  313. }
  314. function buildPermissionToolCall(
  315. request: ZCodePermissionRequest,
  316. preview: ReturnType<typeof getPermissionRequestPreview>,
  317. ): TaskChatToolCall {
  318. const rawInput = readRawToolCallInput(request.raw);
  319. return {
  320. toolId: `permission:${request.requestId}`,
  321. kind: request.kind,
  322. title: request.title ?? request.description ?? preview.title,
  323. input: rawInput ?? preview.command ?? request.raw,
  324. status: "completed",
  325. raw: request.raw,
  326. };
  327. }
  328. function buildPermissionBlockContext(
  329. toolCall: TaskChatToolCall,
  330. rawFileSummaries: ToolCallBlockRenderContext["rawFileSummaries"],
  331. workspacePath: string,
  332. blockKind: PermissionBlockKind,
  333. kindLabelOverride: ReactNode,
  334. theme: ToolCallBlockRenderContext["theme"],
  335. codePreviewSettings: ToolCallBlockRenderContext["codePreviewSettings"],
  336. ): ToolCallBlockRenderContext {
  337. const { canToggle, forceOpen } = getPermissionBlockInteraction(blockKind);
  338. return {
  339. toolCallNode: {
  340. toolCall,
  341. childToolCalls: [],
  342. } as ToolCallBlockRenderContext["toolCallNode"],
  343. workspacePath,
  344. // store 耦合剥离:展示组件不再自取 store,主题/代码预览设置由对话框宿主注入。
  345. theme,
  346. codePreviewSettings,
  347. displayModel: {
  348. inlinePreview: { type: "none" },
  349. planResult: null,
  350. viewerSource: null,
  351. viewerLabelId: "codeViewer.viewCode",
  352. showSummaryFileLink: false,
  353. showInput: false,
  354. showOutput: false,
  355. showKind: false,
  356. },
  357. viewerSource: null,
  358. rawFileSummaries,
  359. // 权限弹窗等待用户确认时工具还没有执行,不能复用 running 状态。
  360. // 之前 Bash 权限会显示“执行中”并带 loading,遮住真正的申请原因。
  361. isRunning: false,
  362. // 权限预览使用合成 completed 节点,必须显式区分,避免误报“没有输出”。
  363. isPermissionPreview: true,
  364. statusLabel: "",
  365. childToolList: null,
  366. showIcon: true,
  367. kindLabelOverride,
  368. canToggle,
  369. forceOpen,
  370. onOpenCodeViewer: undefined,
  371. onOpenBrowserUrl: undefined,
  372. };
  373. }
  374. function McpPermissionBlock(context: ToolCallBlockRenderContext) {
  375. const { toolCall } = context.toolCallNode;
  376. const toolName = getMcpPermissionToolName(toolCall) ?? toolCall.title ?? toolCall.kind;
  377. const reason = getMcpPermissionReason(toolCall);
  378. const hasKindLabelOverride = context.kindLabelOverride != null;
  379. const primaryText = useMemo(
  380. () =>
  381. hasKindLabelOverride ? (
  382. <span className="min-w-0 truncate text-foreground-subtle">{toolName}</span>
  383. ) : reason ? (
  384. <span className="min-w-0 truncate text-foreground-subtle">{reason}</span>
  385. ) : null,
  386. [hasKindLabelOverride, reason, toolName],
  387. );
  388. return (
  389. <ToolLayout
  390. toolId={toolCall.toolId}
  391. icon={MCP_PERMISSION_TOOL_ICON}
  392. showIcon={context.showIcon !== false}
  393. canToggle={false}
  394. kindLabel={context.kindLabelOverride ?? toolName}
  395. primaryText={primaryText}
  396. isRunning={context.isRunning}
  397. content={null}
  398. />
  399. );
  400. }
  401. export function PermissionDialog({
  402. request,
  403. onRespond,
  404. workspacePath,
  405. workspaceIdentity,
  406. remoteSessionId,
  407. workflowSessionModel,
  408. provider,
  409. isWebRemoteControl = false,
  410. responding = false,
  411. responseError,
  412. }: {
  413. request: ZCodePermissionRequest;
  414. responding?: boolean;
  415. responseError?: string;
  416. /**
  417. * `content` 只在工作流确认窗的放行应答上出现:用户在窗里改过的设置(docs/dynamic-workflow/launch.md
  418. * 「Adjusting the settings in the window」)。没改过即不传。
  419. */
  420. onRespond: (
  421. requestId: string,
  422. option: ZCodePermissionOption,
  423. feedback?: string,
  424. content?: Record<string, unknown>,
  425. ) => void;
  426. workspacePath: string;
  427. /** 工作流确认窗的模型清单作用域与会话模型(宿主给)。 */
  428. workspaceIdentity?: string;
  429. remoteSessionId?: string;
  430. workflowSessionModel?: { providerId: string; modelId: string };
  431. provider?: ZCodeProvider;
  432. isWebRemoteControl?: boolean;
  433. }) {
  434. const { intl } = useZCodeIntl();
  435. const isMobileTextInputViewport = useIsMobileTextInputViewport();
  436. // Bug 根因:反馈输入也会渲染在手机 Web 远控的 PermissionDialog 中,14px 输入框聚焦时会触发 iOS 页面放大。
  437. // 与 composer 复用同一套视口判断和 16px 兼容 token,桌面和非远控 Web 保持原有字号。
  438. const avoidIosInputFocusZoom = shouldAvoidIosInputFocusZoom({
  439. isMobileTextInputViewport,
  440. isWebRemoteControl,
  441. });
  442. // M5②.5 store 耦合剥离:主题/代码预览设置在宿主处取 store,向下走 props/render context。
  443. const theme = useZCodeStoreWithDefault((state) => state.theme, "system");
  444. const codePreviewSettings = useZCodeStoreWithDefault(
  445. (state) => state.codePreviewSettings,
  446. DEFAULT_CODE_PREVIEW_SETTINGS,
  447. );
  448. // 工作流确认窗的 Refine 选项不进按钮列表:它就是这个窗的反馈行(见 feedbackOption)。
  449. const refineOption = useMemo(
  450. () => request.options.find(isWorkflowRefineOption),
  451. [request.options],
  452. );
  453. const orderedOptions = useMemo(
  454. () =>
  455. sortPermissionOptions(request.options).filter((option) => !isWorkflowRefineOption(option)),
  456. [request.options],
  457. );
  458. const preview = useMemo(() => getPermissionRequestPreview(request), [request]);
  459. const toolCall = useMemo(() => buildPermissionToolCall(request, preview), [preview, request]);
  460. const rawFileSummaries = useMemo(
  461. () =>
  462. // 权限弹窗之前只认 preview.fileChanges,Write 请求如果只带 file_path/content,
  463. // 这里就会丢失文件摘要;改成复用聊天区同一套 edit 解析,避免两个入口展示结果不一致。
  464. readRawToolCallFileSummaries(toolCall.raw, {
  465. kind: toolCall.kind,
  466. title: toolCall.title,
  467. input: toolCall.input,
  468. output: toolCall.output,
  469. raw: toolCall.raw,
  470. }),
  471. [toolCall],
  472. );
  473. const blockKind = useMemo(
  474. () => resolvePermissionBlockKind(preview, toolCall, rawFileSummaries),
  475. [preview, rawFileSummaries, toolCall],
  476. );
  477. const blockContext = useMemo(
  478. () =>
  479. buildPermissionBlockContext(
  480. toolCall,
  481. rawFileSummaries,
  482. workspacePath,
  483. blockKind,
  484. intl.formatMessage({ id: "chat.permission.awaitingApproval" }),
  485. theme,
  486. codePreviewSettings,
  487. ),
  488. [blockKind, codePreviewSettings, intl, rawFileSummaries, theme, toolCall, workspacePath],
  489. );
  490. const displayReason = useMemo(() => getPermissionDisplayReason(request), [request]);
  491. // 工作流确认窗的两项 run 设置(WorkflowPermissionBlock 画,这里只存改过的值与「模型不可用」)。
  492. const isWorkflowAsk = blockKind === "workflow";
  493. const workflowSettings = usePermissionWorkflowSettings(request.requestId);
  494. const workflowSettingsContent = isWorkflowAsk ? workflowSettings.content : undefined;
  495. const isOptionBlocked = useCallback(
  496. (option: ZCodePermissionOption) =>
  497. isWorkflowAsk && workflowSettings.blocked && isWorkflowSettingsCarrier(option),
  498. [isWorkflowAsk, workflowSettings.blocked],
  499. );
  500. const rootRef = useRef<HTMLDivElement | null>(null);
  501. const [selectedIndex, setSelectedIndex] = useState(0);
  502. const [feedback, setFeedback] = useState("");
  503. const optionRefs = useRef<Array<HTMLButtonElement | null>>([]);
  504. const feedbackInputRef = useRef<HTMLTextAreaElement | null>(null);
  505. const feedbackCompositionActiveRef = useRef(false);
  506. const feedbackInputFocusedRef = useRef(false);
  507. const denyOption = useMemo(
  508. () =>
  509. orderedOptions.find((option) =>
  510. getPermissionOptionDisplayKind(option.kind).startsWith("reject"),
  511. ),
  512. [orderedOptions],
  513. );
  514. // 反馈行的应答目标:工作流确认窗是 Refine(拒绝 + 修改意见升级为真实 user message),
  515. // 其他确认窗是 Deny(拒绝 + 反馈)。两种确认窗共用同一行输入,只换应答目标与文案,
  516. // 不再各画一套输入框——同一停靠区里两种反馈输入长得不一样是设计债。
  517. // 原因:复用 Deny 索引会让拒绝按钮和输入框同时高亮;输入行独立导航,提交才用目标选项。
  518. const feedbackOption = refineOption ?? (request.freeText === true ? denyOption : undefined);
  519. const hasFeedbackInput = Boolean(feedbackOption);
  520. const feedbackIndex = orderedOptions.length;
  521. const selectableCount = orderedOptions.length + (hasFeedbackInput ? 1 : 0);
  522. const isFeedbackSelected = hasFeedbackInput && selectedIndex === feedbackIndex;
  523. useEffect(() => {
  524. setSelectedIndex(0);
  525. // 草稿按 requestId 归零,避免一个请求的反馈(或工作流修改意见)泄漏进下一个确认窗。
  526. setFeedback("");
  527. }, [request.requestId]);
  528. useEffect(() => {
  529. if (orderedOptions.length === 0) {
  530. return;
  531. }
  532. if (feedbackInputFocusedRef.current) {
  533. return;
  534. }
  535. // 反馈输入框新增后,旧的 RAF 可能在用户获得输入焦点后才回调,重新抢回选项焦点。
  536. // 回调执行时再次确认焦点状态,避免打断用户输入。
  537. const frameId = requestAnimationFrame(() => {
  538. if (!feedbackInputFocusedRef.current) {
  539. if (isFeedbackSelected) feedbackInputRef.current?.focus();
  540. else optionRefs.current[selectedIndex]?.focus();
  541. }
  542. });
  543. return () => {
  544. cancelAnimationFrame(frameId);
  545. };
  546. }, [isFeedbackSelected, orderedOptions.length, request.requestId, selectedIndex]);
  547. const moveSelection = useCallback(
  548. (direction: 1 | -1) => {
  549. if (selectableCount === 0) {
  550. return;
  551. }
  552. feedbackInputFocusedRef.current = false;
  553. setSelectedIndex(
  554. (currentIndex) => (currentIndex + direction + selectableCount) % selectableCount,
  555. );
  556. },
  557. [selectableCount],
  558. );
  559. const respondWithOption = useCallback(
  560. (option: ZCodePermissionOption) => {
  561. // 所选子代理模型已不可用:放行要等用户换一个,与「配置」弹层的 Apply 同一条规则。
  562. if (responding || isOptionBlocked(option)) return;
  563. const selectedKind = getPermissionOptionDisplayKind(option.kind);
  564. // 通用确认窗里 Deny 顺带把反馈行草稿作为拒绝理由发出;工作流确认窗的草稿属于 Refine,
  565. // 点 Deny 就是普通拒绝——否则一段修改意见会以普通拒绝理由的身份发出,
  566. // 模型收不到 workflow_refine_feedback 的升级递送。
  567. const trimmedFeedback =
  568. !refineOption && selectedKind.startsWith("reject") ? feedback.trim() : "";
  569. const content =
  570. workflowSettingsContent !== undefined && isWorkflowSettingsCarrier(option)
  571. ? { ...workflowSettingsContent }
  572. : undefined;
  573. if (content === undefined) {
  574. onRespond(request.requestId, option, trimmedFeedback || undefined);
  575. } else {
  576. onRespond(request.requestId, option, trimmedFeedback || undefined, content);
  577. }
  578. },
  579. [
  580. feedback,
  581. isOptionBlocked,
  582. onRespond,
  583. refineOption,
  584. request.requestId,
  585. responding,
  586. workflowSettingsContent,
  587. ],
  588. );
  589. const submitFeedback = useCallback(() => {
  590. // 提交前 trim:CLI broker 对空白 freeText 落普通 deny,不能把纯空白当反馈。
  591. const trimmedFeedback = feedback.trim();
  592. if (responding || !feedbackOption || !trimmedFeedback) {
  593. return;
  594. }
  595. onRespond(request.requestId, feedbackOption, trimmedFeedback);
  596. }, [feedback, feedbackOption, onRespond, request.requestId, responding]);
  597. const confirmSelection = useCallback(() => {
  598. if (isFeedbackSelected) {
  599. submitFeedback();
  600. return;
  601. }
  602. const selectedOption = orderedOptions[selectedIndex];
  603. if (selectedOption) respondWithOption(selectedOption);
  604. }, [isFeedbackSelected, orderedOptions, respondWithOption, selectedIndex, submitFeedback]);
  605. const handleFeedbackKeyDown = useCallback(
  606. (event: ReactKeyboardEvent<HTMLTextAreaElement>) => {
  607. event.stopPropagation();
  608. if (
  609. isImeComposingKeyEvent({
  610. compositionActive: feedbackCompositionActiveRef.current,
  611. nativeEvent: event.nativeEvent,
  612. })
  613. ) {
  614. return;
  615. }
  616. if (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Tab") {
  617. event.preventDefault();
  618. moveSelection(event.key === "ArrowUp" || (event.key === "Tab" && event.shiftKey) ? -1 : 1);
  619. return;
  620. }
  621. if (event.key === "Enter") {
  622. event.preventDefault();
  623. submitFeedback();
  624. return;
  625. }
  626. if (event.key === "Escape") {
  627. event.preventDefault();
  628. feedbackInputRef.current?.blur();
  629. }
  630. },
  631. [moveSelection, submitFeedback],
  632. );
  633. const handleOptionKeyDown = useCallback(
  634. (event: ReactKeyboardEvent<HTMLButtonElement>) => {
  635. if (hasFeedbackInput && event.key === String(feedbackIndex + 1)) {
  636. event.preventDefault();
  637. setSelectedIndex(feedbackIndex);
  638. return;
  639. }
  640. if (event.key === "1" || event.key === "2" || event.key === "3") {
  641. const shortcutIndex = Number(event.key) - 1;
  642. const shortcutOption = orderedOptions[shortcutIndex];
  643. if (!shortcutOption) {
  644. return;
  645. }
  646. event.preventDefault();
  647. setSelectedIndex(shortcutIndex);
  648. respondWithOption(shortcutOption);
  649. return;
  650. }
  651. switch (event.key) {
  652. case "ArrowUp":
  653. case "ArrowLeft":
  654. event.preventDefault();
  655. moveSelection(-1);
  656. return;
  657. case "ArrowDown":
  658. case "ArrowRight":
  659. event.preventDefault();
  660. moveSelection(1);
  661. return;
  662. case "Tab":
  663. // 长命令新增了阅读按钮,旧的选项循环会困住焦点;第一项反向 Tab 交还浏览器,
  664. // 按 DOM 顺序进入上方命令按钮,其正向 Tab 自然回到当前第一项,不触发授权。
  665. if (
  666. event.shiftKey &&
  667. optionRefs.current.indexOf(event.currentTarget) === 0 &&
  668. rootRef.current?.querySelector("[data-command-preview-toggle]")
  669. ) {
  670. return;
  671. }
  672. // 工作流确认窗:第一个选项上的 Shift+Tab 离开列表、回到上方的设置控件(阅读次序即焦点次序)。
  673. // 按事件落在哪个按钮上判,不读 selectedIndex:聚焦与按键可能在同一帧,状态还没提交。
  674. if (
  675. event.shiftKey &&
  676. optionRefs.current.indexOf(event.currentTarget) === 0 &&
  677. isWorkflowAsk &&
  678. focusLastWorkflowSettingsControl(rootRef.current)
  679. ) {
  680. event.preventDefault();
  681. return;
  682. }
  683. event.preventDefault();
  684. moveSelection(event.shiftKey ? -1 : 1);
  685. return;
  686. case "Enter":
  687. event.preventDefault();
  688. confirmSelection();
  689. return;
  690. default:
  691. return;
  692. }
  693. },
  694. [
  695. confirmSelection,
  696. feedbackIndex,
  697. hasFeedbackInput,
  698. isWorkflowAsk,
  699. moveSelection,
  700. orderedOptions,
  701. respondWithOption,
  702. ],
  703. );
  704. const PermissionBlock =
  705. blockKind === "edit"
  706. ? EditToolCallBlock
  707. : blockKind === "mcp"
  708. ? McpPermissionBlock
  709. : blockKind === "skill"
  710. ? SkillToolCallBlock
  711. : blockKind === "search"
  712. ? SearchToolCallBlock
  713. : blockKind === "execute"
  714. ? ExecuteToolCallBlock
  715. : FallbackToolCallBlock;
  716. // 当前 ZCode Agent 的 ExitPlanMode 权限请求不再传 legacy switch_mode。
  717. // 这里复用 tool identity,避免审批弹窗和聊天区的计划模式工具分流再次漂移。
  718. const shouldUseSwitchModePlaceholder = resolveToolCallIdentity(toolCall).family === "switch-mode";
  719. // 工作流确认窗自带本地化标题(「运行此工作流?」)和图主体,走独立块而不是通用预览块。
  720. const shouldUseWorkflowBlock = isWorkflowAsk;
  721. // 保存确认窗同理,但问句、内容与选项都不同:没有图、没有 Refine,主体是落点 + 元数据 + 脚本。
  722. const shouldUseSaveWorkflowBlock = blockKind === "saveWorkflow";
  723. return (
  724. <div ref={rootRef} className="w-full shrink-0 relative z-1">
  725. <div className="w-full overflow-hidden rounded-2xl border border-border bg-popover shadow-xs">
  726. <div className="flex flex-col gap-3 p-3">
  727. <div className="space-y-4">
  728. <div className="flex flex-wrap items-center gap-2">
  729. <p className="text-ui-base font-medium leading-tight text-foreground-subtle">
  730. {intl.formatMessage({ id: "chat.permission.title" })}
  731. </p>
  732. <InteractionRequestOriginBadge origin={request.origin} />
  733. </div>
  734. {!shouldUseSwitchModePlaceholder &&
  735. !shouldUseWorkflowBlock &&
  736. !shouldUseSaveWorkflowBlock &&
  737. displayReason ? (
  738. <p className="text-ui-base leading-5 text-foreground">{displayReason}</p>
  739. ) : null}
  740. {shouldUseSwitchModePlaceholder ? (
  741. <div className="flex items-center gap-2 text-ui-base text-foreground">
  742. <LoaderIcon className="size-4 shrink-0 animate-spin text-foreground-subtle" />
  743. <span className="animated-gradient-text font-medium">
  744. {intl.formatMessage({
  745. id: "chat.permission.switchMode.placeholder",
  746. })}
  747. </span>
  748. </div>
  749. ) : shouldUseWorkflowBlock ? (
  750. // CLI 侧的 reason 是给协议诊断用的("createWorkflow.runConfirmation: ..."),
  751. // 这里刻意不渲染 displayReason:块内的本地化标题才是给用户看的那句问句。
  752. <WorkflowPermissionBlock
  753. onSettingsBlockedChange={workflowSettings.onBlockedChange}
  754. onSettingsChange={workflowSettings.onContentChange}
  755. request={request}
  756. settingsDisabled={responding}
  757. workspacePath={workspacePath}
  758. {...(workspaceIdentity === undefined ? {} : { workspaceIdentity })}
  759. {...(remoteSessionId === undefined ? {} : { remoteSessionId })}
  760. {...(workflowSessionModel === undefined
  761. ? {}
  762. : { sessionModel: workflowSessionModel })}
  763. />
  764. ) : shouldUseSaveWorkflowBlock ? (
  765. // 同上:保存 gate 的问句(保存 / 覆盖两句)由块自己给出,不复用协议 reason。
  766. <SaveWorkflowPermissionBlock request={request} />
  767. ) : (
  768. <PermissionBlock {...blockContext} />
  769. )}
  770. </div>
  771. {/* 反馈行曾被外层 gap-3 隔开;用同一 4px 视觉分组,保留 listbox 的权限选项边界。 */}
  772. <div className="space-y-1">
  773. <div
  774. role="listbox"
  775. aria-label={intl.formatMessage({ id: "chat.permission.title" })}
  776. className="space-y-1"
  777. >
  778. {orderedOptions.map((option, index) => {
  779. const isSelected = index === selectedIndex;
  780. const officialCuaProjectPermission = isOfficialCuaProjectPermission(option);
  781. const labelMessageId = officialCuaProjectPermission
  782. ? "chat.permission.cua.allowForProject"
  783. : option.name.trim().toLowerCase() === "always allow in this project" &&
  784. preview.scope === "command"
  785. ? "chat.permission.allowCommand"
  786. : getOptionLabelMessageId(option.kind);
  787. const nameMessageIds = getProviderOptionNameMessageIds(provider, option.name);
  788. const baseDescriptionMessageId = officialCuaProjectPermission
  789. ? "chat.permission.cua.allowForProject.description"
  790. : labelMessageId === "chat.permission.allowCommand"
  791. ? "chat.permission.allowCommand.description"
  792. : (nameMessageIds?.description ??
  793. getOptionDescriptionMessageId(option.kind, preview.scope));
  794. // 工作流确认窗改过设置:放行的两项改口说「按调整后的设置」(docs/dynamic-workflow/launch.md
  795. // 「The options」)。
  796. const descriptionMessageId =
  797. workflowSettingsContent === undefined
  798. ? baseDescriptionMessageId
  799. : workflowAdjustedOptionDescriptionId(baseDescriptionMessageId);
  800. const blocked = isOptionBlocked(option);
  801. const fallbackLabel = labelMessageId
  802. ? intl.formatMessage({ id: labelMessageId })
  803. : null;
  804. const knownNameLabel = nameMessageIds
  805. ? intl.formatMessage({ id: nameMessageIds.label })
  806. : null;
  807. // ZCode Agent 协议里 option.name 才是给用户看的真实选项文案,kind 只表示按钮语义。
  808. // 之前这里一律按 kind 本地化,像 switch_mode 这类不同语义但同属 allow_always 的选项,
  809. // 会被错误压成两条一模一样的“始终允许”。
  810. const preferOptionName = shouldPreferPermissionOptionName(option);
  811. const label =
  812. (labelMessageId === "chat.permission.allowCommand"
  813. ? fallbackLabel
  814. : knownNameLabel) ??
  815. (preferOptionName ? option.name : (fallbackLabel ?? option.name));
  816. const description =
  817. (preferOptionName && !knownNameLabel) || !descriptionMessageId
  818. ? null
  819. : intl.formatMessage({ id: descriptionMessageId });
  820. const ruleScopes =
  821. getPermissionOptionDisplayKind(option.kind) === "allowAlways"
  822. ? readPermissionRuleScopes(option)
  823. : [];
  824. return (
  825. <button
  826. key={option.optionId}
  827. // exact rule 按产品语义不展示后,E2E 不能再靠可见规则文本猜 option;
  828. // 暴露规范化语义供无障碍自动化稳定选择,不泄露原始命令内容。
  829. data-permission-option-kind={getPermissionOptionDisplayKind(option.kind)}
  830. ref={(node) => {
  831. optionRefs.current[index] = node;
  832. }}
  833. type="button"
  834. role="option"
  835. aria-label={label}
  836. aria-selected={isSelected}
  837. {...(blocked ? { "aria-disabled": true } : {})}
  838. tabIndex={isSelected ? 0 : -1}
  839. onClick={() => {
  840. if (isSelected) {
  841. respondWithOption(option);
  842. } else {
  843. setSelectedIndex(index);
  844. }
  845. }}
  846. onFocus={() => setSelectedIndex(index)}
  847. onKeyDown={handleOptionKeyDown}
  848. className={cn(
  849. "flex w-full items-center gap-3 rounded-xl px-3 py-2 text-left outline-none transition-colors focus-visible:bg-selected",
  850. isSelected ? "bg-selected" : "hover:bg-hover",
  851. blocked && "cursor-not-allowed opacity-50",
  852. )}
  853. >
  854. <span
  855. className={cn(
  856. "w-5 shrink-0 text-ui-base font-medium self-center",
  857. isSelected ? "text-foreground" : "text-foreground-subtlest",
  858. )}
  859. >
  860. {index + 1}.
  861. </span>
  862. <span className="min-w-0 flex flex-1 flex-col">
  863. <span className="flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-1">
  864. <span className="text-ui-base font-medium text-foreground">{label}</span>
  865. {ruleScopes.length > 0 ? (
  866. <InlinePermissionPrefixScopes scopes={ruleScopes} />
  867. ) : description ? (
  868. <span className="text-ui-base leading-4 text-foreground-subtle">
  869. {description}
  870. </span>
  871. ) : null}
  872. </span>
  873. </span>
  874. </button>
  875. );
  876. })}
  877. </div>
  878. {feedbackOption ? (
  879. <div
  880. onClick={(event) => {
  881. if (event.target !== feedbackInputRef.current) {
  882. feedbackInputRef.current?.focus();
  883. }
  884. }}
  885. className={cn(
  886. "flex w-full cursor-text items-center gap-3 rounded-xl px-3 py-2 transition-colors",
  887. isFeedbackSelected ? "bg-selected" : "hover:bg-hover",
  888. )}
  889. >
  890. <span
  891. className={cn(
  892. // 匹配 textarea 的首行行高和 1px 边框;手机输入行高不同,但序号字号不变。
  893. "mt-px w-5 shrink-0 self-start text-ui-base font-medium md:leading-relaxed",
  894. avoidIosInputFocusZoom ? "leading-6" : "leading-5",
  895. isFeedbackSelected ? "text-foreground" : "text-foreground-subtlest",
  896. )}
  897. >
  898. {feedbackIndex + 1}.
  899. </span>
  900. <Textarea
  901. ref={feedbackInputRef}
  902. rows={1}
  903. wrap="soft"
  904. value={feedback}
  905. maxLength={MAX_PERMISSION_FEEDBACK_CHARS}
  906. // Refine 行的文案按稳定 optionId 本地化:协议里的 name 是服务端英文兜底。
  907. aria-label={intl.formatMessage({
  908. id: refineOption
  909. ? "chat.permission.workflow.refine"
  910. : "chat.permission.feedback.ariaLabel",
  911. })}
  912. placeholder={intl.formatMessage({
  913. id: refineOption
  914. ? "chat.permission.workflow.refine.placeholder"
  915. : "chat.permission.feedback.placeholder",
  916. })}
  917. data-permission-feedback-option={feedbackOption.optionId}
  918. onFocus={() => {
  919. feedbackInputFocusedRef.current = true;
  920. setSelectedIndex(feedbackIndex);
  921. }}
  922. onBlur={() => {
  923. feedbackInputFocusedRef.current = false;
  924. }}
  925. onChange={(event) => {
  926. setFeedback(event.target.value);
  927. }}
  928. onCompositionStart={() => {
  929. feedbackCompositionActiveRef.current = true;
  930. }}
  931. onCompositionEnd={() => {
  932. feedbackCompositionActiveRef.current = false;
  933. }}
  934. onKeyDown={handleFeedbackKeyDown}
  935. className={cn(
  936. // Bugfix: 拒绝反馈自动换行,但限制为 5 行并在输入框内滚动,避免窄屏遮住权限选项和确认按钮。
  937. "h-auto !min-h-5 max-h-[5lh] min-w-0 max-w-full overflow-y-auto rounded-none border-transparent bg-transparent !px-0 !py-0 font-medium shadow-none hover:border-transparent focus-visible:border-transparent focus-visible:bg-transparent focus-visible:ring-0",
  938. resolveMobileInputTextSizeClassName({ avoidIosInputFocusZoom }),
  939. )}
  940. />
  941. </div>
  942. ) : null}
  943. </div>
  944. {responseError ? (
  945. <p role="alert" className="text-ui-base text-destructive">
  946. {responseError}
  947. </p>
  948. ) : null}
  949. <div className="flex items-center justify-between gap-2 px-1">
  950. <p className="flex gap-2 text-ui-base items-center text-foreground-subtle">
  951. <Info className="text-foreground size-4 shrink-0" />
  952. {intl.formatMessage({ id: "chat.permission.keyboardHint" })}
  953. </p>
  954. <Button
  955. type="button"
  956. aria-label={intl.formatMessage({ id: "common.confirm" })}
  957. size="lg"
  958. onClick={confirmSelection}
  959. disabled={
  960. responding ||
  961. (isFeedbackSelected
  962. ? !feedback.trim()
  963. : orderedOptions[selectedIndex] === undefined ||
  964. isOptionBlocked(orderedOptions[selectedIndex]))
  965. }
  966. className="bg-brand text-foreground-inverse hover:bg-brand/80"
  967. >
  968. {intl.formatMessage({ id: "common.confirm" })}
  969. </Button>
  970. </div>
  971. </div>
  972. </div>
  973. </div>
  974. );
  975. }