subagent-host-window.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import { readFile, readdir, writeFile, rename } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. export interface HostFaultControl {
  5. tracePaths?: string[];
  6. files?: Array<{
  7. id: string;
  8. path: string;
  9. operation: "readFile" | "readdir" | "writeFile";
  10. action: "hold" | "fail";
  11. once?: boolean;
  12. rejectAfterRelease?: boolean;
  13. }>;
  14. released?: string[];
  15. }
  16. export async function setHostFaults(control: HostFaultControl) {
  17. const path = join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "host-fault-control.json");
  18. await writeFile(path + ".tmp", JSON.stringify(control));
  19. await rename(path + ".tmp", path);
  20. }
  21. export async function readHostBoundary() {
  22. const root = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  23. return (
  24. await Promise.all(
  25. (
  26. await readdir(root)
  27. )
  28. .filter((p) => /^host-boundary-\d+\.jsonl$/u.test(p))
  29. .map(async (p) =>
  30. (await readFile(join(root, p), "utf8"))
  31. .trim()
  32. .split("\n")
  33. .filter(Boolean)
  34. .map(
  35. (line) =>
  36. JSON.parse(line) as {
  37. pid: number;
  38. kind: string;
  39. id?: string;
  40. paths?: string[];
  41. operation?: string;
  42. stack?: string;
  43. readCounts?: Record<string, number>;
  44. },
  45. ),
  46. ),
  47. )
  48. ).flat();
  49. }
  50. export async function waitForHostBoundary(kind: string, id?: string) {
  51. await browser.waitUntil(
  52. async () => (await readHostBoundary()).some((r) => r.kind === kind && (!id || r.id === id)),
  53. { timeout: 15000, timeoutMsg: `缺少 Host 边界事件 ${kind}/${id ?? ""}` },
  54. );
  55. }
  56. /** 测试侧控制 Electron 窗口发现并预加载文件/IPC 故障边界,调用产品已有 activate 路径。 */
  57. export async function openSubagentHostWindow() {
  58. return openFaultInjectedHostWindow(
  59. fileURLToPath(new URL("./subagent-host-faults.cjs", import.meta.url)),
  60. );
  61. }
  62. /** env 只注入新窗口的 Host,例如 ZCODE_E2E_FS_FAULTS,不影响已有窗口。 */
  63. export async function openFaultInjectedHostWindow(
  64. preloadPath: string,
  65. env: Record<string, string> = {},
  66. ) {
  67. await setHostFaults({});
  68. const handles = await browser.getWindowHandles();
  69. const windowId = await browser.electron.execute(
  70. async (electron, preload, root, extraEnv) => {
  71. const originalWindows = electron.BrowserWindow.getAllWindows;
  72. const originalFork = electron.utilityProcess.fork;
  73. let didFork!: () => void;
  74. const forked = new Promise<void>((resolve) => {
  75. didFork = resolve;
  76. });
  77. const created = new Promise<number>((resolve) =>
  78. electron.app.once("browser-window-created", (_event, window) => {
  79. electron.BrowserWindow.getAllWindows = originalWindows;
  80. resolve(window.id);
  81. }),
  82. );
  83. electron.utilityProcess.fork = (path, args, options) => {
  84. electron.utilityProcess.fork = originalFork;
  85. const child = originalFork(preload, [path, ...(args ?? [])], {
  86. ...options,
  87. env: { ...options?.env, ...extraEnv, ZCODE_E2E_HOST_FAULT_ROOT: root },
  88. });
  89. didFork();
  90. return child;
  91. };
  92. electron.BrowserWindow.getAllWindows = () => [];
  93. try {
  94. electron.app.emit("activate");
  95. const [id] = await Promise.all([created, forked]);
  96. return id;
  97. } finally {
  98. electron.BrowserWindow.getAllWindows = originalWindows;
  99. electron.utilityProcess.fork = originalFork;
  100. }
  101. },
  102. preloadPath,
  103. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  104. env,
  105. );
  106. let handle = "";
  107. await browser.waitUntil(
  108. async () => {
  109. handle = (await browser.getWindowHandles()).find((h) => !handles.includes(h)) ?? "";
  110. return Boolean(handle);
  111. },
  112. { timeout: 30000 },
  113. );
  114. await browser.switchToWindow(handle);
  115. await waitForHostBoundary("ready");
  116. return { windowId, handle };
  117. }