stop-tool-results-fixture.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import {
  5. resolveE2EHomeDir,
  6. resolveE2ERuntimePath,
  7. resolveE2EStorageRoot,
  8. } from "./e2e-runtime-paths.js";
  9. const CASE_NAME = "conversation-session-stop-tool-results";
  10. const runtimeRoot = resolveE2ERuntimePath(CASE_NAME);
  11. const configPath = join(resolveE2EStorageRoot(), "cli", "config.json");
  12. const tracePath = join(runtimeRoot, "hook-trace.jsonl");
  13. const hookPath = join(runtimeRoot, "block-read.mjs");
  14. const bashHookPath = join(runtimeRoot, "block-text-bash.mjs");
  15. const releasePath = join(runtimeRoot, "release-text-bash");
  16. const fileFixtureRoot = resolve("test/e2e/fixtures/fs/conversation-session", CASE_NAME);
  17. let originalConfig: string | null = null;
  18. export interface StopToolLogRecord {
  19. timestamp: string;
  20. event: string;
  21. module?: string;
  22. sessionId?: string;
  23. toolCallId?: string;
  24. status?: string;
  25. error?: unknown;
  26. context?: { sessionEventType?: string };
  27. }
  28. interface HookTrace {
  29. hook_event_name: string;
  30. session_id: string;
  31. tool_use_id: string;
  32. phase: string;
  33. }
  34. export async function installStopToolResultsFixture(): Promise<void> {
  35. await mkdir(runtimeRoot, { recursive: true });
  36. await mkdir(dirname(configPath), { recursive: true });
  37. originalConfig = await readOptionalFile(configPath);
  38. await rm(tracePath, { force: true });
  39. await rm(releasePath, { force: true });
  40. await Promise.all(
  41. [
  42. "first.txt",
  43. "first.png",
  44. "blocked-2.txt",
  45. "blocked-3.txt",
  46. "block-read.mjs",
  47. "block-text-bash.mjs",
  48. ].map((name) => copyFile(join(fileFixtureRoot, name), join(runtimeRoot, name))),
  49. );
  50. const config = originalConfig ? JSON.parse(originalConfig) : {};
  51. // 项目 Hook 不可信,会被正常安全策略忽略;只在隔离 HOME 写入用户 Hook,
  52. // 用真实 PreToolUse 固定两个 Read 的取消窗口,不改 executor 或历史。
  53. await writeFile(
  54. configPath,
  55. JSON.stringify(
  56. {
  57. ...config,
  58. hooks: {
  59. enabled: true,
  60. timeoutMs: 120000,
  61. events: {
  62. PreToolUse: [
  63. {
  64. matcher: "Read",
  65. hooks: [
  66. {
  67. type: "process",
  68. command: process.execPath,
  69. args: [hookPath, tracePath],
  70. timeoutMs: 120000,
  71. },
  72. ],
  73. },
  74. {
  75. matcher: "Bash",
  76. hooks: [
  77. {
  78. type: "process",
  79. command: process.execPath,
  80. args: [bashHookPath, tracePath, releasePath],
  81. timeoutMs: 120000,
  82. },
  83. ],
  84. },
  85. ],
  86. PostToolUse: [
  87. {
  88. matcher: "Bash",
  89. hooks: [
  90. {
  91. type: "process",
  92. command: process.execPath,
  93. args: [bashHookPath, tracePath, releasePath],
  94. timeoutMs: 120000,
  95. },
  96. ],
  97. },
  98. ],
  99. },
  100. },
  101. },
  102. null,
  103. 2,
  104. ),
  105. );
  106. }
  107. export async function waitForTextBashBarrier(sessionId: string, toolId: string): Promise<void> {
  108. await browser.waitUntil(
  109. async () => {
  110. const logs = await readStopToolLogs(sessionId);
  111. const trace = (await readOptionalFile(tracePath)) ?? "";
  112. return (
  113. logs.some(
  114. (record) =>
  115. record.event === "model.request.completed" && record.module === "core.runtime",
  116. ) &&
  117. trace
  118. .split("\n")
  119. .filter(Boolean)
  120. .some((line) => {
  121. const record = JSON.parse(line) as HookTrace;
  122. return (
  123. record.session_id === sessionId &&
  124. record.tool_use_id === toolId &&
  125. record.phase === "text_bash_completed"
  126. );
  127. })
  128. );
  129. },
  130. { timeout: 45000, timeoutMsg: "纯文本 Bash 未到达模型完成后的 PostToolUse barrier" },
  131. );
  132. }
  133. export function holdToolResultDatabaseWriteLock(): () => void {
  134. // Node 内置 SQLite 只提供同步连接;仅对本次隔离 E2E 数据库持锁,不写会话数据。
  135. const database = new DatabaseSync(join(resolveE2EStorageRoot(), "cli", "db", "db.sqlite"));
  136. try {
  137. database.exec("BEGIN IMMEDIATE");
  138. } catch (error) {
  139. database.close();
  140. throw error;
  141. }
  142. let released = false;
  143. return () => {
  144. if (released) return;
  145. released = true;
  146. try {
  147. database.exec("ROLLBACK");
  148. } finally {
  149. database.close();
  150. }
  151. };
  152. }
  153. export async function releaseTextBashHook(): Promise<void> {
  154. await writeFile(releasePath, "release");
  155. }
  156. export async function resetTextBashHook(): Promise<void> {
  157. await rm(releasePath, { force: true });
  158. }
  159. export async function restoreStopToolResultsFixture(): Promise<void> {
  160. if (originalConfig === null) await rm(configPath, { force: true });
  161. else await writeFile(configPath, originalConfig);
  162. await rm(runtimeRoot, { recursive: true, force: true });
  163. }
  164. export async function readStopToolLogs(sessionId: string): Promise<StopToolLogRecord[]> {
  165. const logDir =
  166. process.env.ZCODE_LOG_DIR?.trim() ||
  167. join(resolveE2EStorageRoot(resolveE2EHomeDir()), "cli", "log");
  168. const names = await readdir(logDir);
  169. const contents = await Promise.all(
  170. names
  171. .filter((name) => name.endsWith(".jsonl"))
  172. .map((name) => readFile(join(logDir, name), "utf8")),
  173. );
  174. return contents
  175. .flatMap((content) => content.split("\n").slice(0, -1))
  176. .filter((line) => line.includes(sessionId))
  177. .map((line) => JSON.parse(line) as StopToolLogRecord)
  178. .filter((record) => record.sessionId === sessionId)
  179. .sort((a, b) => a.timestamp.localeCompare(b.timestamp));
  180. }
  181. export async function waitForStopToolBarrier(
  182. sessionId: string,
  183. toolIds: readonly string[],
  184. ): Promise<void> {
  185. let logs: StopToolLogRecord[] = [];
  186. let hooks: HookTrace[] = [];
  187. await browser.waitUntil(
  188. async () => {
  189. logs = await readStopToolLogs(sessionId);
  190. hooks = ((await readOptionalFile(tracePath)) ?? "")
  191. .split("\n")
  192. .filter(Boolean)
  193. .map((line) => JSON.parse(line) as HookTrace);
  194. const firstCompleted = logs.some(
  195. (record) => record.event === "tool.call.completed" && record.toolCallId === toolIds[0],
  196. );
  197. const modelCompleted = logs.some(
  198. (record) => record.event === "model.request.completed" && record.module === "core.runtime",
  199. );
  200. const othersBlocked = toolIds
  201. .slice(1)
  202. .every((id) =>
  203. hooks.some(
  204. (record) =>
  205. record.session_id === sessionId &&
  206. record.tool_use_id === id &&
  207. record.phase === "blocked",
  208. ),
  209. );
  210. return firstCompleted && modelCompleted && othersBlocked;
  211. },
  212. { timeout: 45000, timeoutMsg: "未建立 Read 成功 + 模型完成 + 两个 Read Hook 挂起的 Stop 窗口" },
  213. );
  214. // 必须仍有未结算工具;否则 Stop 命中的是空闲态,无法证明取消收尾链路。
  215. expect(
  216. logs.filter(
  217. (record) =>
  218. toolIds.slice(1).includes(record.toolCallId ?? "") &&
  219. ["tool.call.completed", "tool.call.failed"].includes(record.event),
  220. ),
  221. ).toHaveLength(0);
  222. }
  223. export async function writeStopToolEvidence(
  224. variant: string,
  225. evidence: Record<string, unknown>,
  226. ): Promise<void> {
  227. const directory = join(
  228. process.env.ZCODE_E2E_ARTIFACT_DIR?.trim() || resolve(".e2e-artifacts"),
  229. CASE_NAME,
  230. );
  231. await mkdir(directory, { recursive: true });
  232. const sessionId = evidence.sessionId;
  233. const modelIo =
  234. typeof sessionId === "string"
  235. ? ((await readOptionalFile(
  236. join(resolveE2EStorageRoot(), "cli", "rollout", `model-io-${sessionId}.jsonl`),
  237. )) ??
  238. (await readOptionalFile(
  239. join(resolveE2EStorageRoot(), "cli", "debug", `model-io-${sessionId}.jsonl`),
  240. )))
  241. : null;
  242. if (modelIo) await writeFile(join(directory, `${variant}-model-io.jsonl`), modelIo);
  243. await writeFile(
  244. join(directory, `${variant}.json`),
  245. JSON.stringify(
  246. {
  247. ...evidence,
  248. hookTrace: await readOptionalFile(tracePath),
  249. },
  250. null,
  251. 2,
  252. ),
  253. );
  254. await browser.saveScreenshot(join(directory, `${variant}.png`));
  255. }
  256. async function readOptionalFile(path: string): Promise<string | null> {
  257. try {
  258. return await readFile(path, "utf8");
  259. } catch (error) {
  260. if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
  261. return null;
  262. throw error;
  263. }
  264. }