official-plugin-cache-prewarm.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { execFile } from "node:child_process";
  2. import { existsSync } from "node:fs";
  3. import { cp, mkdir, rm } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { promisify } from "node:util";
  6. /*
  7. * 官方插件缓存预热(docs/testing/conversation-session-automatic-e2e-ci.md「官方插件缓存预热」)。
  8. *
  9. * 修复原因:每个 spec 的 beforeSession 都会重置 HOME。CLI 首次处理请求时在事件循环上同步
  10. * seed 约 1100 个官方插件文件,Windows 上阻塞 8–15s,session/create 排在其后,首发用例的
  11. * “输入框清空”等待因此超时。这里在 launcher 用同一份 CLI 只 seed 一次模板,再在每个 HOME
  12. * 启动 Electron 前拷入;CLI 的 seed marker 校验命中后不再重写,业务用例不再承担冷启动开销。
  13. */
  14. const execFileAsync = promisify(execFile);
  15. const OFFICIAL_PLUGIN_CACHE_SEGMENTS = [
  16. ".zcode",
  17. "cli",
  18. "plugins",
  19. "cache",
  20. "zcode-plugins-official",
  21. ] as const;
  22. const SEED_TIMEOUT_MS = 180_000;
  23. function officialPluginCacheDir(homeDir: string): string {
  24. return join(homeDir, ...OFFICIAL_PLUGIN_CACHE_SEGMENTS);
  25. }
  26. /** 用 E2E 实际启动的 CLI 在模板 HOME 中 seed 官方插件缓存;`plugin list` 会完成 seed 后退出。 */
  27. export async function prepareOfficialPluginCacheTemplate(input: {
  28. cliEntryPoint: string;
  29. templateHome: string;
  30. }): Promise<void> {
  31. await rm(input.templateHome, { force: true, recursive: true });
  32. await mkdir(input.templateHome, { recursive: true });
  33. await execFileAsync(process.execPath, [input.cliEntryPoint, "plugin", "list"], {
  34. env: {
  35. ...process.env,
  36. HOME: input.templateHome,
  37. USERPROFILE: input.templateHome,
  38. ZCODE_DATA_BASE_DIR: input.templateHome,
  39. ZCODE_DESKTOP_HOME_DIR: input.templateHome,
  40. },
  41. timeout: SEED_TIMEOUT_MS,
  42. windowsHide: true,
  43. });
  44. if (!existsSync(officialPluginCacheDir(input.templateHome))) {
  45. throw new Error(`官方插件缓存预热没有生成 cache 目录: ${input.templateHome}`);
  46. }
  47. }
  48. /** 把模板缓存拷入新 HOME;模板不存在时返回 false,由 CLI 照常冷 seed。 */
  49. export async function installOfficialPluginCacheTemplate(input: {
  50. homeDir: string;
  51. templateHome: string;
  52. }): Promise<boolean> {
  53. const source = officialPluginCacheDir(input.templateHome);
  54. if (!existsSync(source)) return false;
  55. await cp(source, officialPluginCacheDir(input.homeDir), { recursive: true });
  56. return true;
  57. }