resource-manager.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import type { MenuItem } from "electron";
  2. import { type ResourceUsageSnapshot } from "@zcode/shared";
  3. import {
  4. TID_RESOURCE_MANAGER_TAB,
  5. TID_WORKSPACE_HELP_MENU_RESOURCE_MANAGER,
  6. TID_WORKSPACE_HELP_MENU_TRIGGER,
  7. testId,
  8. } from "@zcode/shared/test-ids";
  9. import { clickTestIdByWebDriver, dispatchMouseDownByExactTestId } from "./desktop-app.js";
  10. import { sel } from "./selectors.js";
  11. const RESOURCE_MANAGER_URL_MARKER = "resource-manager.html";
  12. const MAIN_RENDERER_URL_MARKER = "/renderer/index.html";
  13. type ResourceManagerWindow = Window & {
  14. resourceManager?: { getSnapshot: () => Promise<ResourceUsageSnapshot> };
  15. };
  16. export async function openResourceManager(): Promise<void> {
  17. await browser.electron.execute((electron) => {
  18. const findResourceManagerItem = (items: MenuItem[]): MenuItem | undefined => {
  19. for (const item of items) {
  20. if (item.label === "资源管理器" || item.label.toLowerCase() === "resource manager") {
  21. return item;
  22. }
  23. const nested = item.submenu ? findResourceManagerItem(item.submenu.items) : undefined;
  24. if (nested) return nested;
  25. }
  26. return undefined;
  27. };
  28. const item = findResourceManagerItem(electron.Menu.getApplicationMenu()?.items ?? []);
  29. if (!item) throw new Error("应用菜单中没有找到资源管理器");
  30. item.click(undefined as never, undefined, undefined as never);
  31. });
  32. }
  33. /**
  34. * 从主窗口右上角问号帮助菜单打开资源管理器。
  35. * Windows/Linux 没有原生菜单栏,这是这两个平台唯一的入口;调用前需处于主 renderer target。
  36. */
  37. export async function openResourceManagerFromHelpMenu(): Promise<void> {
  38. // Radix DropdownMenu trigger 依赖 pointerdown,必须走真实 WebDriver 指针链。
  39. await clickTestIdByWebDriver(TID_WORKSPACE_HELP_MENU_TRIGGER);
  40. const item = $(sel(TID_WORKSPACE_HELP_MENU_RESOURCE_MANAGER));
  41. await item.waitForClickable({ timeout: 10_000, timeoutMsg: "问号菜单里没有资源管理器项" });
  42. await item.click();
  43. }
  44. /** 关闭资源管理器窗口(若存在),供同一 spec 内多个 case 各自验证打开路径。 */
  45. export async function closeResourceManagerWindow(): Promise<void> {
  46. await browser.electron.execute((electron, marker) => {
  47. for (const window of electron.BrowserWindow.getAllWindows()) {
  48. if (window.webContents.getURL().includes(marker)) {
  49. window.close();
  50. }
  51. }
  52. }, RESOURCE_MANAGER_URL_MARKER);
  53. await browser.waitUntil(
  54. async () =>
  55. browser.electron.execute(
  56. (electron, marker) =>
  57. !electron.BrowserWindow.getAllWindows().some((window) =>
  58. window.webContents.getURL().includes(marker),
  59. ),
  60. RESOURCE_MANAGER_URL_MARKER,
  61. ),
  62. { timeout: 10_000, interval: 250, timeoutMsg: "资源管理器窗口没有关闭" },
  63. );
  64. }
  65. export async function switchToElectronRendererTarget(
  66. predicate: (url: string) => boolean,
  67. ): Promise<void> {
  68. await browser.waitUntil(
  69. async () => {
  70. const puppeteer = await browser.getPuppeteer();
  71. const target = puppeteer.targets().find((candidate) => predicate(candidate.url()));
  72. const targetId = target
  73. ? ((target as unknown as { _targetId?: string })._targetId ?? null)
  74. : null;
  75. if (!targetId) return false;
  76. await browser.switchToWindow(targetId);
  77. (browser.electron as typeof browser.electron & { windowHandle?: string }).windowHandle =
  78. targetId;
  79. return predicate(await browser.execute(() => window.location.href));
  80. },
  81. {
  82. timeout: 15_000,
  83. interval: 250,
  84. timeoutMsg: "没有找到目标 Electron renderer",
  85. },
  86. );
  87. }
  88. export function isMainRendererUrl(url: string): boolean {
  89. try {
  90. const parsed = new URL(url);
  91. return (
  92. parsed.pathname.endsWith(MAIN_RENDERER_URL_MARKER) ||
  93. (parsed.hostname === "localhost" && !parsed.pathname.endsWith(RESOURCE_MANAGER_URL_MARKER))
  94. );
  95. } catch {
  96. return false;
  97. }
  98. }
  99. export function isResourceManagerUrl(url: string): boolean {
  100. return url.includes(RESOURCE_MANAGER_URL_MARKER);
  101. }
  102. /** 读取 preload 指标源的一次完整快照(与 UI 同源,避免读瞬时 DOM 撞上 React commit 边界) */
  103. export async function readResourceUsageSnapshot(): Promise<ResourceUsageSnapshot | null> {
  104. return browser.execute(async () => {
  105. const snapshot = await (window as ResourceManagerWindow).resourceManager?.getSnapshot();
  106. return snapshot ?? null;
  107. });
  108. }
  109. export async function waitForResourceManagerReady(): Promise<void> {
  110. await browser.waitUntil(
  111. async () => {
  112. const snapshot = await readResourceUsageSnapshot();
  113. return Boolean(snapshot?.processes.some((process) => process.name === "zcode-main"));
  114. },
  115. {
  116. timeout: 15_000,
  117. interval: 250,
  118. timeoutMsg: "资源管理器没有加载进程快照",
  119. },
  120. );
  121. }
  122. export async function waitForAgentProcessCount(
  123. expected: number,
  124. options: { workspaceNameSuffix?: string } = {},
  125. ): Promise<void> {
  126. await browser.waitUntil(async () => (await countAgentProcessRows(options)) === expected, {
  127. timeout: 30_000,
  128. interval: 250,
  129. timeoutMsg: `资源管理器中 Agent 数量没有收敛为 ${expected}`,
  130. });
  131. }
  132. export async function countAgentProcessRows(
  133. options: { workspaceNameSuffix?: string } = {},
  134. ): Promise<number> {
  135. return (await listAgentProcessIdentities(options)).length;
  136. }
  137. export interface AgentProcessIdentity {
  138. pid: number;
  139. name: string;
  140. }
  141. export async function listAgentProcessIdentities(
  142. options: { workspaceNameSuffix?: string } = {},
  143. ): Promise<AgentProcessIdentity[]> {
  144. const snapshot = await readResourceUsageSnapshot();
  145. if (!snapshot) return [];
  146. const suffix = options.workspaceNameSuffix ?? "";
  147. return snapshot.processes
  148. .filter(
  149. (process) =>
  150. process.name.startsWith("zcode-agent-") && (!suffix || process.name.endsWith(suffix)),
  151. )
  152. .map((process) => ({ pid: process.pid, name: process.name }))
  153. .sort((left, right) =>
  154. left.name === right.name ? left.pid - right.pid : left.name.localeCompare(right.name),
  155. );
  156. }
  157. /** Host 进程行(`zcode-host-*`),按 pid 升序 */
  158. export async function listHostProcessIdentities(): Promise<AgentProcessIdentity[]> {
  159. const snapshot = await readResourceUsageSnapshot();
  160. if (!snapshot) return [];
  161. return snapshot.processes
  162. .filter((process) => process.name.startsWith("zcode-host-"))
  163. .map((process) => ({ pid: process.pid, name: process.name }))
  164. .sort((left, right) => left.pid - right.pid);
  165. }
  166. /**
  167. * 切换资源管理器顶部 tab。Radix TabsTrigger 在 mousedown 时激活,DOM click() 不会切换,
  168. * 所以这里派发 mousedown 并等待 data-state=active。
  169. */
  170. export async function activateResourceManagerTab(
  171. tab: "cpu" | "memory" | "storage" | "network",
  172. ): Promise<void> {
  173. const tabTestId = testId(TID_RESOURCE_MANAGER_TAB, tab);
  174. await browser.waitUntil(
  175. async () => {
  176. await browser.execute(dispatchMouseDownByExactTestId, tabTestId);
  177. return browser.execute((currentTestId: string) => {
  178. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  179. (item) => item.dataset.testid === currentTestId,
  180. );
  181. return element?.getAttribute("data-state") === "active";
  182. }, tabTestId);
  183. },
  184. { timeout: 10_000, interval: 200, timeoutMsg: `资源管理器 tab ${tab} 没有激活` },
  185. );
  186. }