conversation-session-permission-hook-rewrite.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // DCA-V1-06:共享审批在旧 build 模式下的 Hook 改写交互,不修改 Guarded 产品合同。
  2. import { access, copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { fileURLToPath } from "node:url";
  6. import {
  7. clearAppData,
  8. getE2EAppDataPaths,
  9. restoreCliConfig,
  10. seedCliConfig,
  11. snapshotCliConfig,
  12. type CliConfigSnapshot,
  13. } from "../helpers/desktop-app.js";
  14. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  15. import { skipOccupationOnboardingIfPresent } from "../helpers/occupation-onboarding.js";
  16. import {
  17. ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  18. startElectronWindowRecording,
  19. } from "../helpers/electron-window-recorder.js";
  20. import { getLatestUpstreamToolResultByToolCallId } from "../helpers/conversation-session-network.js";
  21. import {
  22. getV4PaneSnapshot,
  23. prepareV4ConversationE2E,
  24. sendV4Prompt,
  25. switchV4Mode,
  26. waitForV4PermissionDialogInComposerDock,
  27. waitForV4TimelineContaining,
  28. } from "../helpers/v4-conversation.js";
  29. const CASE = "conversation-session-permission-hook-rewrite";
  30. const MARKER = "E2E_PERMISSION_HOOK_REWRITE";
  31. const TOOL_ID = "toolu_e2e_permission_hook_rewrite";
  32. const ROOT = resolveE2ERuntimePath(CASE);
  33. const ARTIFACT = join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), CASE);
  34. const DIALOG =
  35. '[role="listbox"][aria-label="Permission required"], [role="listbox"][aria-label="需要权限"]';
  36. const ALLOW = '[role="listbox"] [data-permission-option-kind="allowOnce"]';
  37. const DOCK = '[data-v4-composer-dock="true"]';
  38. const RULES = JSON.stringify({ version: 1, ask: [{ toolName: "Write" }] });
  39. const exists = (path: string) =>
  40. access(path).then(
  41. () => true,
  42. () => false,
  43. );
  44. interface BrowserObservation {
  45. commands: Array<{ id: string; at: number; held: boolean }>;
  46. frames: Array<{ at: number; count: number; text: string }>;
  47. release: () => void;
  48. restore: () => void;
  49. }
  50. declare global {
  51. interface Window {
  52. __permissionRewriteReview?: BrowserObservation;
  53. }
  54. }
  55. describe("PermissionRequest Hook 改写后的确认替换", () => {
  56. let config: CliConfigSnapshot;
  57. before(async function () {
  58. this.timeout(120000);
  59. await mkdir(ROOT, { recursive: true });
  60. await mkdir(ARTIFACT, { recursive: true });
  61. const source = fileURLToPath(
  62. new URL(
  63. "../fixtures/fs/conversation-session/conversation-session-permission-hook-rewrite/hook.mjs",
  64. import.meta.url,
  65. ),
  66. );
  67. const script = join(ROOT, "hook.mjs");
  68. await copyFile(source, script);
  69. config = await snapshotCliConfig();
  70. const commandHook = {
  71. type: "process",
  72. command: process.execPath,
  73. args: [script, ROOT],
  74. timeoutMs: 90000,
  75. };
  76. await seedCliConfig({
  77. hooks: {
  78. enabled: true,
  79. timeoutMs: 90000,
  80. events: {
  81. PermissionRequest: [{ matcher: "Write", hooks: [commandHook] }],
  82. PostToolUse: [{ matcher: "Write", hooks: [commandHook] }],
  83. },
  84. },
  85. });
  86. // 新隔离 profile 先完成 staging 的职业引导,再进入原审批测试。
  87. await skipOccupationOnboardingIfPresent();
  88. await prepareV4ConversationE2E();
  89. await switchV4Mode("build");
  90. // 先通过真实提交建立 session/project;只在隔离 E2E 数据库布置项目 ask 前置条件。
  91. await sendV4Prompt(`${MARKER}_SETUP Prepare the approval interaction demonstration.`);
  92. await waitForV4TimelineContaining(`${MARKER}_READY`, 60000);
  93. const sessionId = (await getV4PaneSnapshot()).sessionId;
  94. withDatabase((db) => {
  95. const session = db.prepare("select project_id from session where id = ?").get(sessionId!) as {
  96. project_id: string;
  97. };
  98. expect(session.project_id).toBeTruthy();
  99. db.prepare(
  100. "insert into local_setting (scope, scope_id, namespace, key, value, schema_version, time_created, time_updated) values ('project', ?, 'permission', 'ruleset', ?, 1, ?, ?)",
  101. ).run(session.project_id, RULES, Date.now(), Date.now());
  102. });
  103. });
  104. after(async () => {
  105. await browser.execute(() => window.__permissionRewriteReview?.restore());
  106. if (config) await restoreCliConfig(config);
  107. await browser.electron.restoreAllMocks();
  108. await clearAppData();
  109. await rm(ROOT, { recursive: true, force: true });
  110. });
  111. it("DCA-V1-06: 旧确认被 B 替换,迟到 A 批准无效,B 仅执行一次", async function () {
  112. this.timeout(180000);
  113. await observeAndDelayFirstApproval();
  114. // 转正后强制录屏会让无 ffmpeg 的默认回放在业务通过后失败;仅人工审核需要视频。
  115. const recording = process.env.ZCODE_E2E_MANUAL_REVIEW === "1"
  116. ? await startElectronWindowRecording({
  117. outputPath: join(ARTIFACT, "approval-replacement.webm"),
  118. frameIntervalMs: 100,
  119. })
  120. : null;
  121. let staleResponse: Record<string, unknown> | undefined;
  122. try {
  123. await sendV4Prompt(
  124. `${MARKER}_RUN Write A-after-model.txt with the original content exactly once.`,
  125. );
  126. await waitForV4PermissionDialogInComposerDock();
  127. await browser.waitUntil(async () =>
  128. (await readTrace()).some((item) => item.phase === "started"),
  129. );
  130. expect(await $(DOCK).getText()).toContain("A-after-model.txt");
  131. await browser.saveScreenshot(join(ARTIFACT, "01-original-A.png"));
  132. expect(await exists(join(ROOT, "A-after-model.txt"))).toBe(false);
  133. // 人工审核需要读清 A;仅延长录屏展示,不代替上面的条件等待和断言。
  134. if (recording) await browser.pause(3000);
  135. // 真实 WebDriver 点击;只延迟它生成的原始 RPC 包,不伪造批准或权限事件。
  136. await $(ALLOW).click();
  137. await browser.waitUntil(async () => (await observation()).commands.length === 1, {
  138. timeout: 10000,
  139. timeoutMsg: "没有捕获到真实 UI 生成的旧批准命令",
  140. });
  141. await writeFile(join(ROOT, "release"), "release Hook rewrite");
  142. await browser.waitUntil(async () => (await $(DOCK).getText()).includes("B-after-hook.txt"), {
  143. timeout: 30000,
  144. timeoutMsg: "Hook 返回后未显示修改后的 B 确认",
  145. });
  146. await waitForV4PermissionDialogInComposerDock();
  147. await browser.saveScreenshot(join(ARTIFACT, "02-rewritten-B.png"));
  148. await browser.execute(() => window.__permissionRewriteReview!.release());
  149. // interaction 命令不进入通用 UI ACK buffer;用 CLI 的精确 ID 终态证明服务端已处理旧包。
  150. const oldId = (await observation()).commands[0]!.id;
  151. await browser.waitUntil(
  152. async () => {
  153. staleResponse = await readStaleResponse(oldId);
  154. return Boolean(staleResponse);
  155. },
  156. { timeout: 15000, timeoutMsg: "CLI 未确认旧 interactionId 已失效" },
  157. );
  158. expect(await $(DOCK).getText()).toContain("B-after-hook.txt");
  159. expect(await exists(join(ROOT, "B-after-hook.txt"))).toBe(false);
  160. expect((await readTrace()).filter((item) => item.phase === "executed")).toHaveLength(0);
  161. await browser.saveScreenshot(join(ARTIFACT, "03-stale-A-still-pending-B.png"));
  162. // 原版 B 只展示约半秒;保留阅读时间,旧响应失效和未执行已在上面验证。
  163. if (recording) await browser.pause(3000);
  164. await $(ALLOW).click();
  165. await waitForV4TimelineContaining(`${MARKER}_DONE`, 60000);
  166. await browser.waitUntil(async () =>
  167. (await readTrace()).some((item) => item.phase === "executed"),
  168. );
  169. expect(await exists(join(ROOT, "A-after-model.txt"))).toBe(false);
  170. expect(await readFile(join(ROOT, "B-after-hook.txt"), "utf8")).toBe(
  171. "Approved rewritten input B\n",
  172. );
  173. const trace = await readTrace();
  174. expect(trace.filter((item) => item.phase === "started")).toHaveLength(1);
  175. expect(trace.filter((item) => item.phase === "executed")).toHaveLength(1);
  176. const result = await getLatestUpstreamToolResultByToolCallId(TOOL_ID);
  177. expect(result?.isError).toBe(false);
  178. expect(result?.content).toContain("B-after-hook.txt");
  179. const captured = await observation();
  180. expect(captured.commands).toHaveLength(2);
  181. expect(captured.commands[0]!.id).not.toBe(captured.commands[1]!.id);
  182. expect(Math.max(...captured.frames.map((frame) => frame.count))).toBe(1);
  183. expect(await $$(DIALOG).length).toBe(0);
  184. expect(
  185. withDatabase((db) =>
  186. db
  187. .prepare(
  188. "select value from local_setting where namespace = 'permission' and key = 'ruleset'",
  189. )
  190. .all(),
  191. ),
  192. ).toEqual([{ value: RULES }]);
  193. await browser.saveScreenshot(join(ARTIFACT, "04-completed-B.png"));
  194. } finally {
  195. await writeFile(
  196. join(ARTIFACT, "interaction-evidence.json"),
  197. JSON.stringify(
  198. {
  199. clientMode: "desktop-continuous",
  200. video_capture_mode: recording ? ELECTRON_WINDOW_RECORDING_CAPTURE_MODE : null,
  201. ...(await observation()),
  202. staleResponse,
  203. trace: await readTrace(),
  204. },
  205. null,
  206. 2,
  207. ),
  208. );
  209. await recording?.stop({ tailDurationMs: 500 });
  210. }
  211. });
  212. });
  213. function withDatabase<T>(action: (db: DatabaseSync) => T): T {
  214. const db = new DatabaseSync(join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"));
  215. try {
  216. return action(db);
  217. } finally {
  218. db.close();
  219. }
  220. }
  221. async function readTrace(): Promise<Array<{ phase: string }>> {
  222. if (!(await exists(join(ROOT, "trace.jsonl")))) return [];
  223. return (await readFile(join(ROOT, "trace.jsonl"), "utf8"))
  224. .trim()
  225. .split("\n")
  226. .filter(Boolean)
  227. .map((line) => JSON.parse(line));
  228. }
  229. async function readStaleResponse(id: string): Promise<Record<string, unknown> | undefined> {
  230. const logDir =
  231. process.env.ZCODE_LOG_DIR?.trim() || join(getE2EAppDataPaths().storageRoot, "cli", "log");
  232. for (const name of await readdir(logDir)) {
  233. if (!name.endsWith(".jsonl")) continue;
  234. const lines = (await readFile(join(logDir, name), "utf8")).split("\n");
  235. for (const line of lines.slice(0, -1)) {
  236. if (
  237. line.includes('"event":"zcode_protocol.v4.interaction_already_resolved"') &&
  238. line.includes(id)
  239. )
  240. return JSON.parse(line) as Record<string, unknown>;
  241. }
  242. }
  243. return undefined;
  244. }
  245. function observation() {
  246. return browser.execute(() => ({
  247. commands: window.__permissionRewriteReview?.commands ?? [],
  248. frames: window.__permissionRewriteReview?.frames ?? [],
  249. }));
  250. }
  251. async function observeAndDelayFirstApproval() {
  252. await browser.execute((selector) => {
  253. const original = MessagePort.prototype.postMessage;
  254. const commands: BrowserObservation["commands"] = [];
  255. const frames: BrowserObservation["frames"] = [];
  256. let held: { port: MessagePort; data: Uint8Array } | undefined;
  257. const capture = () => {
  258. const dialogs = Array.from(document.querySelectorAll<HTMLElement>(selector));
  259. const frame = {
  260. at: performance.now(),
  261. count: dialogs.length,
  262. text: dialogs
  263. .map(
  264. (item) =>
  265. item.closest<HTMLElement>('[data-v4-composer-dock="true"]')?.innerText ??
  266. item.innerText,
  267. )
  268. .join("\n"),
  269. };
  270. const previous = frames.at(-1);
  271. if (!previous || previous.count !== frame.count || previous.text !== frame.text)
  272. frames.push(frame);
  273. };
  274. const observer = new MutationObserver(capture);
  275. observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  276. capture();
  277. // MessagePortProtocol 发送 Uint8Array;JSON 载荷嵌在 RPC binary 中。
  278. // 仅识别并暂存第一条真实 resolveInteraction allowOnce 包,其余消息原样转发。
  279. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  280. if (message instanceof Uint8Array) {
  281. const text = new TextDecoder().decode(message);
  282. if (
  283. text.includes('"type":"resolveInteraction"') &&
  284. text.includes('"optionId":"allowOnce"')
  285. ) {
  286. const id = /"interactionId":"([^"]+)"/.exec(text)?.[1];
  287. if (!id) throw new Error("批准命令缺失 interactionId");
  288. commands.push({ id, at: performance.now(), held: commands.length === 0 });
  289. if (commands.length === 1) {
  290. held = { port: this, data: message.slice() };
  291. return;
  292. }
  293. }
  294. }
  295. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  296. };
  297. window.__permissionRewriteReview = {
  298. commands,
  299. frames,
  300. release() {
  301. if (!held) throw new Error("没有待投递的旧批准");
  302. original.call(held.port, held.data);
  303. held = undefined;
  304. },
  305. restore() {
  306. MessagePort.prototype.postMessage = original;
  307. observer.disconnect();
  308. if (held) original.call(held.port, held.data);
  309. delete window.__permissionRewriteReview;
  310. },
  311. };
  312. }, DIALOG);
  313. }