ResourceManagerApp.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import { useCallback, useEffect, useMemo, useState } from "react";
  2. import type { ResourceManagerAppProps, ResourceManagerTab } from "@/resource-manager/contract.js";
  3. import { type ResourceUsageCategory, type ResourceUsageSnapshot } from "@zcode/shared";
  4. import { TID_RESOURCE_MANAGER_TAB, testId } from "@zcode/shared/test-ids";
  5. import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs.js";
  6. import { useZCodeIntl } from "@/i18n/index.js";
  7. import { StorageSection } from "./storage/StorageSection.js";
  8. import { NetworkSection } from "./NetworkSection.js";
  9. import { UNSAMPLED_PLACEHOLDER, UsageGroup, UsageMeter } from "./resourceUsageParts.js";
  10. import {
  11. clampPercent,
  12. formatBytes,
  13. formatPercent,
  14. groupResourceUsage,
  15. type ResourceUsageGroupView,
  16. } from "./resourceUsageView.js";
  17. export type { ResourceManagerAppProps, ResourceManagerTab } from "@/resource-manager/contract.js";
  18. const RESOURCE_MANAGER_TABS: ResourceManagerTab[] = ["cpu", "memory", "storage", "network"];
  19. const TAB_LABEL_IDS: Record<ResourceManagerTab, string> = {
  20. cpu: "resourceManager.cpu",
  21. memory: "resourceManager.memory",
  22. storage: "resourceManager.storage",
  23. network: "resourceManager.network",
  24. };
  25. const DEFAULT_REFRESH_INTERVAL_MS = 1_000;
  26. const CATEGORY_LABEL_IDS: Record<ResourceUsageCategory, string> = {
  27. base: "resourceManager.category.base",
  28. task: "resourceManager.category.task",
  29. "builtin-plugin": "resourceManager.category.builtinPlugin",
  30. "community-plugin": "resourceManager.category.communityPlugin",
  31. };
  32. /**
  33. * 资源管理器窗口 UI。
  34. * 组件放在 packages/ui 内是为了纳入 Tailwind 扫描;desktop 的独立 renderer 入口只负责挂载。
  35. */
  36. export function ResourceManagerApp({
  37. getSnapshot,
  38. setSamplingActive,
  39. storage,
  40. network,
  41. refreshIntervalMs = DEFAULT_REFRESH_INTERVAL_MS,
  42. initialTab = "cpu",
  43. }: ResourceManagerAppProps) {
  44. const { intl } = useZCodeIntl();
  45. const [tab, setTab] = useState<ResourceManagerTab>(initialTab);
  46. // CPU / 内存共用一份进程快照;存储 tab 激活时停止轮询,避免和扫盘争抢 IO。
  47. const pollingActive = tab === "cpu" || tab === "memory";
  48. const [snapshot, setSnapshot] = useState<ResourceUsageSnapshot | null>(null);
  49. const [error, setError] = useState<string | null>(null);
  50. const [expanded, setExpanded] = useState<Record<ResourceUsageCategory, boolean>>({
  51. base: true,
  52. task: true,
  53. "builtin-plugin": true,
  54. "community-plugin": true,
  55. });
  56. useEffect(() => {
  57. if (!getSnapshot) {
  58. setError(intl.formatMessage({ id: "resourceManager.unavailable" }));
  59. return;
  60. }
  61. if (!pollingActive) return;
  62. setSamplingActive?.(true);
  63. let disposed = false;
  64. let inFlight = false;
  65. async function refresh() {
  66. // 请求串行:上一轮未返回(Host 采样慢)时不叠加新请求。
  67. if (inFlight) return;
  68. inFlight = true;
  69. try {
  70. const next = await getSnapshot!();
  71. if (disposed) return;
  72. setSnapshot(next);
  73. setError(null);
  74. } catch (err) {
  75. if (disposed) return;
  76. setError(err instanceof Error ? err.message : String(err));
  77. } finally {
  78. inFlight = false;
  79. }
  80. }
  81. void refresh();
  82. const interval = window.setInterval(() => void refresh(), refreshIntervalMs);
  83. return () => {
  84. disposed = true;
  85. window.clearInterval(interval);
  86. // 停止 renderer 定时器还不够,Host 在途采样也必须随页面生命周期取消。
  87. setSamplingActive?.(false);
  88. };
  89. }, [getSnapshot, intl, pollingActive, refreshIntervalMs, setSamplingActive]);
  90. const groups = useMemo(() => groupResourceUsage(snapshot?.processes ?? []), [snapshot]);
  91. const toggleGroup = useCallback((category: ResourceUsageCategory) => {
  92. setExpanded((current) => ({ ...current, [category]: !current[category] }));
  93. }, []);
  94. return (
  95. <main
  96. className="flex h-dvh min-h-0 flex-col bg-background text-foreground"
  97. data-testid="resource-manager"
  98. >
  99. <header className="flex h-12 shrink-0 items-center justify-between gap-4 border-b border-border bg-header px-4">
  100. <div className="min-w-0">
  101. <h1 className="truncate text-ui-base font-medium">
  102. {intl.formatMessage({ id: "resourceManager.title" })}
  103. </h1>
  104. {pollingActive ? (
  105. <div className="text-ui-xs text-foreground-subtle">
  106. {snapshot
  107. ? intl.formatMessage(
  108. { id: "resourceManager.processCount" },
  109. { count: snapshot.processes.length },
  110. )
  111. : intl.formatMessage({ id: "resourceManager.loading" })}
  112. </div>
  113. ) : null}
  114. </div>
  115. <Tabs value={tab} onValueChange={(value) => setTab(value as ResourceManagerTab)}>
  116. <TabsList variant="line" className="h-8 gap-1 p-0">
  117. {RESOURCE_MANAGER_TABS.map((item) => (
  118. <TabsTrigger
  119. key={item}
  120. value={item}
  121. data-testid={testId(TID_RESOURCE_MANAGER_TAB, item)}
  122. className="h-8 flex-none rounded-full px-3 hover:bg-hover data-active:!bg-selected data-active:hover:!bg-hover after:hidden"
  123. >
  124. {intl.formatMessage({ id: TAB_LABEL_IDS[item] })}
  125. </TabsTrigger>
  126. ))}
  127. </TabsList>
  128. </Tabs>
  129. </header>
  130. <div className="min-h-0 flex-1 overflow-auto bg-background-alt p-4">
  131. {tab === "storage" ? (
  132. <StorageSection bridge={storage} active={tab === "storage"} />
  133. ) : tab === "network" ? (
  134. <NetworkSection bridge={network} />
  135. ) : (
  136. <UsageTabContent
  137. metric={tab}
  138. snapshot={snapshot}
  139. error={error}
  140. groups={groups}
  141. expanded={expanded}
  142. onToggleGroup={toggleGroup}
  143. />
  144. )}
  145. </div>
  146. </main>
  147. );
  148. }
  149. /** CPU / 内存 tab 的正文:左侧对应指标卡,右侧分组列表只显示当前指标列。 */
  150. function UsageTabContent({
  151. metric,
  152. snapshot,
  153. error,
  154. groups,
  155. expanded,
  156. onToggleGroup,
  157. }: {
  158. metric: "cpu" | "memory";
  159. snapshot: ResourceUsageSnapshot | null;
  160. error: string | null;
  161. groups: ResourceUsageGroupView[];
  162. expanded: Record<ResourceUsageCategory, boolean>;
  163. onToggleGroup: (category: ResourceUsageCategory) => void;
  164. }) {
  165. const { intl } = useZCodeIntl();
  166. return (
  167. <>
  168. {error ? (
  169. <div
  170. className="rounded-xl border border-destructive/30 bg-card px-4 py-3 text-ui-sm text-destructive"
  171. data-testid="resource-manager-error"
  172. >
  173. {error}
  174. </div>
  175. ) : null}
  176. <div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]">
  177. <aside className="flex min-w-0 flex-col gap-4">
  178. {metric === "cpu" ? (
  179. <UsageMeter
  180. testId="resource-manager-cpu"
  181. label={intl.formatMessage({ id: "resourceManager.cpu" })}
  182. appValue={snapshot ? formatPercent(snapshot.app.cpuPercent) : UNSAMPLED_PLACEHOLDER}
  183. systemValue={
  184. snapshot ? formatPercent(snapshot.system.cpuPercent) : UNSAMPLED_PLACEHOLDER
  185. }
  186. appPercent={snapshot ? clampPercent(snapshot.app.cpuPercent) : 0}
  187. systemPercent={snapshot ? clampPercent(snapshot.system.cpuPercent) : 0}
  188. appLabel={intl.formatMessage({ id: "resourceManager.appUsage" })}
  189. systemLabel={intl.formatMessage({ id: "resourceManager.systemUsage" })}
  190. />
  191. ) : (
  192. <UsageMeter
  193. testId="resource-manager-memory"
  194. label={intl.formatMessage({ id: "resourceManager.memory" })}
  195. appValue={snapshot ? formatBytes(snapshot.app.memoryBytes) : UNSAMPLED_PLACEHOLDER}
  196. systemValue={
  197. snapshot
  198. ? `${formatBytes(snapshot.system.memoryUsedBytes)} / ${formatBytes(snapshot.system.memoryTotalBytes)}`
  199. : UNSAMPLED_PLACEHOLDER
  200. }
  201. appPercent={
  202. snapshot && snapshot.system.memoryTotalBytes > 0
  203. ? clampPercent(
  204. (snapshot.app.memoryBytes / snapshot.system.memoryTotalBytes) * 100,
  205. )
  206. : 0
  207. }
  208. systemPercent={
  209. snapshot && snapshot.system.memoryTotalBytes > 0
  210. ? clampPercent(
  211. (snapshot.system.memoryUsedBytes / snapshot.system.memoryTotalBytes) * 100,
  212. )
  213. : 0
  214. }
  215. appLabel={intl.formatMessage({ id: "resourceManager.appUsage" })}
  216. systemLabel={intl.formatMessage({ id: "resourceManager.systemUsage" })}
  217. />
  218. )}
  219. </aside>
  220. <section className="flex min-w-0 flex-col gap-3">
  221. {groups.map((group) => (
  222. <UsageGroup
  223. key={group.category}
  224. group={group}
  225. metric={metric}
  226. title={intl.formatMessage({ id: CATEGORY_LABEL_IDS[group.category] })}
  227. expanded={expanded[group.category]}
  228. onToggle={() => onToggleGroup(group.category)}
  229. emptyText={intl.formatMessage({ id: "resourceManager.empty" })}
  230. samplingText={intl.formatMessage({ id: "resourceManager.sampling" })}
  231. columns={{
  232. process: intl.formatMessage({ id: "resourceManager.column.process" }),
  233. pid: intl.formatMessage({ id: "resourceManager.column.pid" }),
  234. cpu: intl.formatMessage({ id: "resourceManager.cpu" }),
  235. memory: intl.formatMessage({ id: "resourceManager.memory" }),
  236. }}
  237. />
  238. ))}
  239. </section>
  240. </div>
  241. </>
  242. );
  243. }