e2e-runtime-paths.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { join, posix, resolve } from "node:path";
  2. import { readdir, stat } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. export const E2E_RUNTIME_RELATIVE_ROOT = ".zcode-e2e";
  5. export const E2E_RUNTIME_ROOT_REPLAY_TOKEN = "{{e2eRuntimeRoot}}";
  6. const E2E_AGENT_WORKSPACE_NAME = "ZCodeProject";
  7. interface ResolveE2EHomeDirOptions {
  8. cwd?: string;
  9. env?: Record<string, string | undefined>;
  10. }
  11. export function resolveE2EHomeDir({
  12. cwd = process.cwd(),
  13. env = process.env,
  14. }: ResolveE2EHomeDirOptions = {}): string {
  15. const configuredHome =
  16. env.ZCODE_E2E_HOME_DIR?.trim() ||
  17. env.ZCODE_DATA_BASE_DIR?.trim() ||
  18. env.ZCODE_DESKTOP_HOME_DIR?.trim();
  19. return resolve(cwd, configuredHome || ".e2e-home");
  20. }
  21. /**
  22. * 判断 HOME 是否为 runner 分配的隔离 E2E HOME,供直接改写磁盘夹具的 case 做安全守卫。
  23. * Bug 根因:旧守卫只看 basename 是否以 `.e2e-home-` 开头;直接运行 wdio 的默认 `.e2e-home`
  24. * 被误拒。改为任一路径段满足 `isE2EHomeDirName` 即可:覆盖 `.e2e-home`、`.e2e-home-<runId>[-shard-N]`,
  25. * 以及根目录名带 `.e2e-home` 的显式 ZCODE_E2E_HOME_DIR 分片子目录。
  26. * 根目录名不带 `.e2e-home` 的显式 HOME 无法与真实目录区分,保守拒绝;需要改写夹具的 case 应使用带该前缀的根。
  27. */
  28. export function isIsolatedE2EHomeDir(home: string | undefined): home is string {
  29. if (!home?.trim()) return false;
  30. return resolve(home).split(/[\\/]/u).some(isE2EHomeDirName);
  31. }
  32. /**
  33. * runner 的隔离 HOME 目录名只有 `.e2e-home` 与 `.e2e-home-<runId>[-shard-N]` 两种布局。
  34. * 修复原因:裸前缀 `.e2e-home` 会放行 `.e2e-homebackup`、`.e2e-home2` 等误配目录,
  35. * 破坏性夹具步骤会继续执行而不是提前失败;因此只接受精确名或 `-` 分隔的后缀。
  36. */
  37. export function isE2EHomeDirName(name: string): boolean {
  38. return /^\.e2e-home(?:-|$)/u.test(name);
  39. }
  40. export function resolveE2EStorageRoot(e2eHomeDir = resolveE2EHomeDir()): string {
  41. // Bug 根因:回滚 storage profile 时删除了仍被 E2E 用例依赖的路径 helper。
  42. // E2E 继续隔离 HOME,但 CLI 根固定使用历史目录 .zcode,不再区分 dev/stable profile。
  43. return join(e2eHomeDir, ".zcode");
  44. }
  45. export function resolveE2ERuntimeRoot(e2eHomeDir = resolveE2EHomeDir()): string {
  46. // Bug 根因:conversation E2E 的 Agent 实际 cwd 是隔离 HOME 下的
  47. // ZCodeProject,而不是 conversation backing workspace。Node 若写到后者,
  48. // Bash 的相对路径就会永远等不到同一个文件,Windows 上还会叠加 shell 路径差异。
  49. return join(e2eHomeDir, E2E_AGENT_WORKSPACE_NAME, E2E_RUNTIME_RELATIVE_ROOT);
  50. }
  51. export function resolveE2ERuntimePath(...segments: string[]): string {
  52. return join(resolveE2ERuntimeRoot(), ...segments);
  53. }
  54. export function resolveE2EToolPath(...segments: string[]): string {
  55. // Bug 根因:Windows Node 与 Git Bash 会把裸 POSIX 临时根解析成不同目录。
  56. // 工具参数保留绝对路径,但统一成 Windows 文件 API 同样接受的正斜杠形式,
  57. // 让 JSON replay fixture 不需要猜测盘符转义或 Git Bash mount。
  58. return resolveE2ERuntimePath(...segments).replaceAll("\\", "/");
  59. }
  60. export function resolveE2EShellPath(...segments: string[]): string {
  61. return posix.join(E2E_RUNTIME_RELATIVE_ROOT, ...segments);
  62. }
  63. export function createE2EReplayFixtureVariables(
  64. e2eHomeDir = resolveE2EHomeDir(),
  65. ): Readonly<Record<string, string>> {
  66. return {
  67. e2eRuntimeRoot: resolveE2ERuntimeRoot(e2eHomeDir).replaceAll("\\", "/"),
  68. };
  69. }
  70. /** 前台 Bash 仍在运行时尚无 tool_result;按真实 session/tool 查找唯一输出,不能固定旧 HOME 根。 */
  71. export async function findE2EBashOutputPath(
  72. sessionId: string,
  73. toolCallId: string,
  74. {
  75. tempRoot = tmpdir(),
  76. storageRoot = resolveE2EStorageRoot(),
  77. }: { tempRoot?: string; storageRoot?: string } = {},
  78. ): Promise<string | null> {
  79. const directories = (await readdir(tempRoot, { withFileTypes: true }))
  80. .filter((entry) => entry.isDirectory() && entry.name.startsWith("zcode-bash-"))
  81. .map((entry) => join(tempRoot, entry.name));
  82. const candidates = [...directories, join(storageRoot, "cli", "exec")].map((root) =>
  83. join(root, sessionId, `${toolCallId}-stdout.log`),
  84. );
  85. const existing = (
  86. await Promise.all(
  87. candidates.map(async (path) => {
  88. try {
  89. return (await stat(path)).isFile() ? path : null;
  90. } catch (error) {
  91. if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
  92. throw error;
  93. }
  94. }),
  95. )
  96. ).filter((path): path is string => path !== null);
  97. if (existing.length > 1)
  98. throw new Error(
  99. `Bash 没有唯一实际输出文件: ${sessionId}/${toolCallId}; ${JSON.stringify(existing)}`,
  100. );
  101. return existing[0] ?? null;
  102. }