subagent-snapshot-wait.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. async function runtimeLogReader() {
  4. const root = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR!);
  5. const read = async () =>
  6. (
  7. await Promise.all(
  8. (
  9. await readdir(root)
  10. )
  11. .filter((p) => p.endsWith(".log"))
  12. .sort()
  13. .map((p) => readFile(join(root, p), "utf8")),
  14. )
  15. ).join("\n");
  16. return read;
  17. }
  18. /** 观察现有 Host 日志,不查询/改写生产缓存,也不为模型额外制造父 turn。 */
  19. export async function subagentUpdateCursor() {
  20. const read = await runtimeLogReader();
  21. const before = await read();
  22. return async (hostPids?: number[], changedPaths: string[] = []) => {
  23. await browser.waitUntil(
  24. async () => {
  25. const after = await read();
  26. const lines = after
  27. .split("\n")
  28. .filter((line) => line.includes("Subagent 配置文件更新完成") && !before.includes(line));
  29. const matches = (pid?: number) =>
  30. changedPaths.length
  31. ? changedPaths.every((path) =>
  32. lines.some(
  33. // Host 的路径元数据经过 JSON 序列化;原始 Windows 反斜杠无法直接匹配日志。
  34. (line) =>
  35. (!pid || line.includes(`[pid:${pid}]`)) &&
  36. line.includes(JSON.stringify(path).slice(1, -1)),
  37. ),
  38. )
  39. : lines.some((line) => !pid || line.includes(`[pid:${pid}]`));
  40. return hostPids?.length ? hostPids.every(matches) : matches();
  41. },
  42. { timeout: 20000, timeoutMsg: "Host 未完成配置文件更新" },
  43. );
  44. };
  45. }
  46. export function hasCompletedSubagentSettingsLoad(lines: readonly string[]): boolean {
  47. const initializedHosts = new Set<string>();
  48. for (const line of lines) {
  49. const match = line.match(
  50. /\[pid:(\d+)\] \[zcode-host\] \[rpc:call\] (plugin-management\.getPluginsOverview|subagents\.list) OK/u,
  51. );
  52. if (!match) continue;
  53. if (match[2] === "plugin-management.getPluginsOverview") initializedHosts.add(match[1]!);
  54. else if (initializedHosts.has(match[1]!)) return true;
  55. }
  56. return false;
  57. }
  58. export async function subagentSettingsReadyCursor() {
  59. const read = await runtimeLogReader();
  60. const previousLines = new Set((await read()).split("\n"));
  61. return async () => {
  62. await browser.waitUntil(
  63. async () =>
  64. hasCompletedSubagentSettingsLoad(
  65. (await read()).split("\n").filter((line) => !previousLines.has(line)),
  66. ),
  67. { timeout: 20000, timeoutMsg: "Subagent 设置初始插件投影未完成" },
  68. );
  69. };
  70. }