permission-full-access.fixture.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { V4InteractionDialogs } from "@/v4/V4InteractionDialogs.js";
  2. import {
  3. V4ConversationContext,
  4. type V4ConversationContextValue,
  5. } from "@/v4/V4ConversationContext.js";
  6. import { initializeNewTaskDraft } from "@/v4/composer/newTaskDraft.js";
  7. import type { ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  8. import { useState } from "react";
  9. import { createRoot } from "react-dom/client";
  10. import { ConfirmDialogHost } from "@/ConfirmDialog.js";
  11. import { PermissionDialog } from "@/PermissionDialog.js";
  12. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  13. import { isLocale, type ZCodePermissionRequest } from "@zcode/shared";
  14. import "@/styles.css";
  15. import { pendingCommandRegistry } from "@/v4/pendingCommandRegistry.js";
  16. import type { CommandAck } from "@zcode/shared/zcode-protocol-v4";
  17. const params = new URLSearchParams(location.search);
  18. const requestedLocale = params.get("locale");
  19. const scopeGate = Promise.withResolvers<void>();
  20. document.documentElement.classList.add(
  21. params.get("theme") === "light" ? "theme-zai-light" : "theme-zai-dark",
  22. );
  23. const request: ZCodePermissionRequest = {
  24. type: "permission_request",
  25. taskId: "s",
  26. traceId: "trace",
  27. requestId: "p",
  28. kind: "Bash",
  29. title: "Bash",
  30. description: "Run command",
  31. raw: {
  32. command:
  33. params.get("command") === "long"
  34. ? `printf "%s" "${"long/path/".repeat(160)}COMMAND_END"`
  35. : "ping -c 4 www.baidu.com",
  36. },
  37. freeText: true,
  38. options: [
  39. { optionId: "allowOnce", kind: "allow_once", name: "Allow", response: { decision: "allow" } },
  40. {
  41. optionId: "allowAlways",
  42. kind: "allow_always",
  43. name: "Always allow in this project",
  44. response: {
  45. decision: "allow",
  46. permissionUpdates: [
  47. {
  48. type: "addRules",
  49. behavior: "allow",
  50. rules: [{ toolName: "Bash", ruleContent: "ping -c 4 www.baidu.com" }],
  51. },
  52. ],
  53. },
  54. },
  55. { optionId: "fullAccess", kind: "custom", name: "Full access", response: { decision: "deny" } },
  56. { optionId: "deny", kind: "deny", name: "Deny", response: { decision: "deny" } },
  57. ],
  58. };
  59. // 使用移动端同一审批组件、回执账本和新建草稿入口。传输替身只控制是否真的获得授权。
  60. function MobileProjectApproval() {
  61. const scope = {
  62. clientNamespace: innerWidth < 600 ? "mobile" : "desktop",
  63. hostId: "local",
  64. projectId: "project-a",
  65. };
  66. const [settled, setSettled] = useState(false);
  67. const [mode, setMode] = useState("");
  68. const snapshot = {
  69. sessionId: "s",
  70. config: { mode: params.get("current") ?? "build", provider: "example", model: "test" },
  71. pendingInteractions: [
  72. {
  73. interactionId: "p",
  74. payload: {
  75. kind: "permission",
  76. toolName: "Bash",
  77. summary: "Run command",
  78. detail: { command: "pwd" },
  79. options: [{ optionId: "allowOnce", label: "Allow", kind: "allowOnce" }],
  80. modeSwitch: params.get("current") === "guarded" ? "fullAccessOnly" : "choose",
  81. fullAccessOption: { optionId: "fullAccess", label: "Full access", kind: "custom" },
  82. },
  83. },
  84. ],
  85. } as ConversationSnapshot;
  86. const [sent, setSent] = useState<string[]>([]);
  87. const transport = {
  88. sendCommand: async (command) => {
  89. const id = (command.payload as { answer: { optionId: string } }).answer.optionId;
  90. setSent((previous) => [...previous, id]);
  91. if (params.get("mismatch") && !sent.length)
  92. return {
  93. commandId: command.commandId,
  94. revisionAtDecision: 1,
  95. status: "failed",
  96. reasonCode: "fault.permissionGrant.committed." + params.get("mismatch"),
  97. };
  98. setSettled(true);
  99. const ack: CommandAck = {
  100. commandId: command.commandId,
  101. revisionAtDecision: 1,
  102. status: "accepted",
  103. ...(params.get("grant") === "won"
  104. ? {
  105. result: {
  106. type: "resolveInteraction",
  107. resolvedBy: {
  108. clientId: command.clientId,
  109. optionId: (command.payload as { answer: { optionId: string } }).answer.optionId,
  110. },
  111. },
  112. }
  113. : {}),
  114. };
  115. if (params.has("queryOnly")) {
  116. pendingCommandRegistry.applyQuery({
  117. results: [
  118. { key: { sessionId: command.sessionId, commandId: command.commandId }, result: ack },
  119. ],
  120. });
  121. throw new Error("simulated lost ACK");
  122. }
  123. return ack;
  124. },
  125. } as V4ConversationContextValue;
  126. const open = (projectId: string) =>
  127. setMode(
  128. initializeNewTaskDraft(
  129. { text: "", updatedAt: 0 },
  130. "/example",
  131. undefined,
  132. { preferredSelection: null, providers: [] } as Parameters<typeof initializeNewTaskDraft>[3],
  133. { ...scope, projectId },
  134. ).draft.mode!,
  135. );
  136. return (
  137. <V4ConversationContext.Provider value={transport}>
  138. {!settled && (
  139. <V4InteractionDialogs
  140. sessionId="s"
  141. workspacePath="/example"
  142. isWebRemoteControl={innerWidth < 600}
  143. snapshot={snapshot}
  144. resolveRecentScope={async () => {
  145. if (params.has("holdScope")) await scopeGate.promise;
  146. if (params.has("scopeError")) throw new Error("project.service-unavailable");
  147. return scope;
  148. }}
  149. />
  150. )}
  151. {params.has("holdScope") && (
  152. <button onClick={() => scopeGate.resolve()}>Release scope</button>
  153. )}
  154. <output data-testid="sent-options">{sent.join(",")}</output>
  155. {settled && (
  156. <>
  157. <button onClick={() => open("project-a")}>New A</button>
  158. <button onClick={() => open("project-b")}>New B</button>
  159. <output data-testid="draft-mode">{mode}</output>
  160. </>
  161. )}
  162. <ConfirmDialogHost />
  163. </V4ConversationContext.Provider>
  164. );
  165. }
  166. function Fixture() {
  167. const [response, setResponse] = useState("");
  168. return (
  169. <main className="min-h-screen bg-background text-foreground p-3">
  170. <PermissionDialog
  171. workspacePath="/example"
  172. request={request}
  173. isWebRemoteControl={innerWidth < 600}
  174. onRespond={(_id, option) => setResponse(option.optionId)}
  175. />
  176. <ConfirmDialogHost />
  177. <output data-testid="response">{response}</output>
  178. </main>
  179. );
  180. }
  181. createRoot(document.getElementById("root")!).render(
  182. <ZCodeIntlProvider initialLocale={isLocale(requestedLocale) ? requestedLocale : "zh-CN"}>
  183. {params.has("grant") ? <MobileProjectApproval /> : <Fixture />}
  184. </ZCodeIntlProvider>,
  185. );