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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 "#e2e/helpers/desktop-app";
  14. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  15. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  16. import {
  17. ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  18. startElectronWindowRecording,
  19. } from "#e2e/helpers/electron-window-recorder";
  20. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  21. import {
  22. getV4PaneSnapshot,
  23. prepareV4ConversationE2E,
  24. sendV4Prompt,
  25. switchV4Mode,
  26. waitForV4PermissionDialogInComposerDock,
  27. waitForV4TimelineContaining,
  28. } from "#e2e/helpers/v4-conversation";
  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 =
  116. process.env.ZCODE_E2E_MANUAL_REVIEW === "1"
  117. ? await startElectronWindowRecording({
  118. outputPath: join(ARTIFACT, "approval-replacement.webm"),
  119. frameIntervalMs: 100,
  120. })
  121. : null;
  122. let staleResponse: Record<string, unknown> | undefined;
  123. try {
  124. await sendV4Prompt(
  125. `${MARKER}_RUN Write A-after-model.txt with the original content exactly once.`,
  126. );
  127. await waitForV4PermissionDialogInComposerDock();
  128. await browser.waitUntil(async () =>
  129. (await readTrace()).some((item) => item.phase === "started"),
  130. );
  131. expect(await $(DOCK).getText()).toContain("A-after-model.txt");
  132. await browser.saveScreenshot(join(ARTIFACT, "01-original-A.png"));
  133. expect(await exists(join(ROOT, "A-after-model.txt"))).toBe(false);
  134. // 人工审核需要读清 A;仅延长录屏展示,不代替上面的条件等待和断言。
  135. if (recording) await browser.pause(3000);
  136. // 真实 WebDriver 点击;只延迟它生成的原始 RPC 包,不伪造批准或权限事件。
  137. await $(ALLOW).click();
  138. await browser.waitUntil(async () => (await observation()).commands.length === 1, {
  139. timeout: 10000,
  140. timeoutMsg: "没有捕获到真实 UI 生成的旧批准命令",
  141. });
  142. await writeFile(join(ROOT, "release"), "release Hook rewrite");
  143. await browser.waitUntil(async () => (await $(DOCK).getText()).includes("B-after-hook.txt"), {
  144. timeout: 30000,
  145. timeoutMsg: "Hook 返回后未显示修改后的 B 确认",
  146. });
  147. await waitForV4PermissionDialogInComposerDock();
  148. await browser.saveScreenshot(join(ARTIFACT, "02-rewritten-B.png"));
  149. await browser.execute(() => window.__permissionRewriteReview!.release());
  150. // interaction 命令不进入通用 UI ACK buffer;用 CLI 的精确 ID 终态证明服务端已处理旧包。
  151. const oldId = (await observation()).commands[0]!.id;
  152. await browser.waitUntil(
  153. async () => {
  154. staleResponse = await readStaleResponse(oldId);
  155. return Boolean(staleResponse);
  156. },
  157. { timeout: 15000, timeoutMsg: "CLI 未确认旧 interactionId 已失效" },
  158. );
  159. expect(await $(DOCK).getText()).toContain("B-after-hook.txt");
  160. expect(await exists(join(ROOT, "B-after-hook.txt"))).toBe(false);
  161. expect((await readTrace()).filter((item) => item.phase === "executed")).toHaveLength(0);
  162. await browser.saveScreenshot(join(ARTIFACT, "03-stale-A-still-pending-B.png"));
  163. // 原版 B 只展示约半秒;保留阅读时间,旧响应失效和未执行已在上面验证。
  164. if (recording) await browser.pause(3000);
  165. await $(ALLOW).click();
  166. await waitForV4TimelineContaining(`${MARKER}_DONE`, 60000);
  167. await browser.waitUntil(async () =>
  168. (await readTrace()).some((item) => item.phase === "executed"),
  169. );
  170. expect(await exists(join(ROOT, "A-after-model.txt"))).toBe(false);
  171. expect(await readFile(join(ROOT, "B-after-hook.txt"), "utf8")).toBe(
  172. "Approved rewritten input B\n",
  173. );
  174. const trace = await readTrace();
  175. expect(trace.filter((item) => item.phase === "started")).toHaveLength(1);
  176. expect(trace.filter((item) => item.phase === "executed")).toHaveLength(1);
  177. const result = await getLatestUpstreamToolResultByToolCallId(TOOL_ID);
  178. expect(result?.isError).toBe(false);
  179. expect(result?.content).toContain("B-after-hook.txt");
  180. const captured = await observation();
  181. expect(captured.commands).toHaveLength(2);
  182. expect(captured.commands[0]!.id).not.toBe(captured.commands[1]!.id);
  183. expect(Math.max(...captured.frames.map((frame) => frame.count))).toBe(1);
  184. expect(await $$(DIALOG).length).toBe(0);
  185. expect(
  186. withDatabase((db) =>
  187. db
  188. .prepare(
  189. "select value from local_setting where namespace = 'permission' and key = 'ruleset'",
  190. )
  191. .all(),
  192. ),
  193. ).toEqual([{ value: RULES }]);
  194. await browser.saveScreenshot(join(ARTIFACT, "04-completed-B.png"));
  195. } finally {
  196. await writeFile(
  197. join(ARTIFACT, "interaction-evidence.json"),
  198. JSON.stringify(
  199. {
  200. clientMode: "desktop-continuous",
  201. video_capture_mode: recording ? ELECTRON_WINDOW_RECORDING_CAPTURE_MODE : null,
  202. ...(await observation()),
  203. staleResponse,
  204. trace: await readTrace(),
  205. },
  206. null,
  207. 2,
  208. ),
  209. );
  210. await recording?.stop({ tailDurationMs: 500 });
  211. }
  212. });
  213. });
  214. function withDatabase<T>(action: (db: DatabaseSync) => T): T {
  215. const db = new DatabaseSync(join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"));
  216. try {
  217. return action(db);
  218. } finally {
  219. db.close();
  220. }
  221. }
  222. async function readTrace(): Promise<Array<{ phase: string }>> {
  223. if (!(await exists(join(ROOT, "trace.jsonl")))) return [];
  224. return (await readFile(join(ROOT, "trace.jsonl"), "utf8"))
  225. .trim()
  226. .split("\n")
  227. .filter(Boolean)
  228. .map((line) => JSON.parse(line));
  229. }
  230. async function readStaleResponse(id: string): Promise<Record<string, unknown> | undefined> {
  231. const logDir =
  232. process.env.ZCODE_LOG_DIR?.trim() || join(getE2EAppDataPaths().storageRoot, "cli", "log");
  233. for (const name of await readdir(logDir)) {
  234. if (!name.endsWith(".jsonl")) continue;
  235. const lines = (await readFile(join(logDir, name), "utf8")).split("\n");
  236. for (const line of lines.slice(0, -1)) {
  237. if (
  238. line.includes('"event":"zcode_protocol.v4.interaction_already_resolved"') &&
  239. line.includes(id)
  240. )
  241. return JSON.parse(line) as Record<string, unknown>;
  242. }
  243. }
  244. return undefined;
  245. }
  246. function observation() {
  247. return browser.execute(() => ({
  248. commands: window.__permissionRewriteReview?.commands ?? [],
  249. frames: window.__permissionRewriteReview?.frames ?? [],
  250. }));
  251. }
  252. async function observeAndDelayFirstApproval() {
  253. await browser.execute((selector) => {
  254. const original = MessagePort.prototype.postMessage;
  255. const commands: BrowserObservation["commands"] = [];
  256. const frames: BrowserObservation["frames"] = [];
  257. let held: { port: MessagePort; data: Uint8Array } | undefined;
  258. const capture = () => {
  259. const dialogs = Array.from(document.querySelectorAll<HTMLElement>(selector));
  260. const frame = {
  261. at: performance.now(),
  262. count: dialogs.length,
  263. text: dialogs
  264. .map(
  265. (item) =>
  266. item.closest<HTMLElement>('[data-v4-composer-dock="true"]')?.innerText ??
  267. item.innerText,
  268. )
  269. .join("\n"),
  270. };
  271. const previous = frames.at(-1);
  272. if (!previous || previous.count !== frame.count || previous.text !== frame.text)
  273. frames.push(frame);
  274. };
  275. const observer = new MutationObserver(capture);
  276. observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  277. capture();
  278. // MessagePortProtocol 发送 Uint8Array;JSON 载荷嵌在 RPC binary 中。
  279. // 仅识别并暂存第一条真实 resolveInteraction allowOnce 包,其余消息原样转发。
  280. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  281. if (message instanceof Uint8Array) {
  282. const text = new TextDecoder().decode(message);
  283. if (
  284. text.includes('"type":"resolveInteraction"') &&
  285. text.includes('"optionId":"allowOnce"')
  286. ) {
  287. const id = /"interactionId":"([^"]+)"/.exec(text)?.[1];
  288. if (!id) throw new Error("批准命令缺失 interactionId");
  289. commands.push({ id, at: performance.now(), held: commands.length === 0 });
  290. if (commands.length === 1) {
  291. held = { port: this, data: message.slice() };
  292. return;
  293. }
  294. }
  295. }
  296. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  297. };
  298. window.__permissionRewriteReview = {
  299. commands,
  300. frames,
  301. release() {
  302. if (!held) throw new Error("没有待投递的旧批准");
  303. original.call(held.port, held.data);
  304. held = undefined;
  305. },
  306. restore() {
  307. MessagePort.prototype.postMessage = original;
  308. observer.disconnect();
  309. if (held) original.call(held.port, held.data);
  310. delete window.__permissionRewriteReview;
  311. },
  312. };
  313. }, DIALOG);
  314. }