Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(devdock): memory readout popover with memory-infra breakdown (#19233)

Inneib6fc300c3309
diff --git a/apps/desktop/src/main/controllers/DevtoolsCtr.ts b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
index 1f9220b501c..df8db88f86f 100644
--- a/apps/desktop/src/main/controllers/DevtoolsCtr.ts
+++ b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
@@ -1,7 +1,8 @@
-import type { AppProcessMetrics, GpuStatus } from '@lobechat/electron-client-ipc';
+import type { AppProcessMetrics, GpuStatus, MemoryDump } from '@lobechat/electron-client-ipc';
import { app } from 'electron';
import { getIpcContext } from '@/utils/ipc';
+import { parseMemoryDump, type TraceEvent } from '@/utils/memoryDump';
import { ControllerModule, IpcMethod } from './index';
@@ -14,6 +15,8 @@ interface CompleteGpuInfo {
const readText = (value: unknown): string | null =>
typeof value === 'string' && value.length > 0 ? value : null;
+const MEMORY_DUMP_TIMEOUT = 15_000;
+
export default class DevtoolsCtr extends ControllerModule {
static override readonly groupName = 'devtools';
@@ -44,10 +47,61 @@ export default class DevtoolsCtr extends ControllerModule {
memoryMB:
gpuProcesses.reduce((sum, metric) => sum + metric.memory.workingSetSize, 0) / 1024,
},
+ processes: metrics.map((metric) => ({
+ cpuPercent: metric.cpu.percentCPUUsage,
+ name: readText(metric.name) ?? readText(metric.serviceName),
+ pid: metric.pid,
+ type: metric.type,
+ workingSetMB: metric.memory.workingSetSize / 1024,
+ })),
rendererResidentMB: renderer ? renderer.memory.workingSetSize / 1024 : null,
};
}
+ @IpcMethod()
+ async captureMemoryDump(): Promise<MemoryDump> {
+ const contents = getIpcContext()?.sender;
+ if (!contents) throw new Error('memory dump needs a renderer sender');
+
+ const dbg = contents.debugger;
+ const attachedHere = !dbg.isAttached();
+ if (attachedHere) dbg.attach('1.3');
+
+ const events: TraceEvent[] = [];
+ let finish!: () => void;
+ const complete = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const onMessage = (_event: unknown, method: string, params: { value?: TraceEvent[] }) => {
+ if (method === 'Tracing.dataCollected') events.push(...(params.value ?? []));
+ if (method === 'Tracing.tracingComplete') finish();
+ };
+ dbg.on('message', onMessage);
+
+ try {
+ await dbg.sendCommand('Tracing.start', {
+ traceConfig: {
+ includedCategories: ['disabled-by-default-memory-infra'],
+ memoryDumpConfig: { triggers: [] },
+ },
+ transferMode: 'ReportEvents',
+ });
+ await dbg.sendCommand('Tracing.requestMemoryDump', { levelOfDetail: 'detailed' });
+ await dbg.sendCommand('Tracing.end');
+ await Promise.race([
+ complete,
+ new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error('memory dump timed out')), MEMORY_DUMP_TIMEOUT);
+ }),
+ ]);
+ } finally {
+ dbg.off('message', onMessage);
+ if (attachedHere) dbg.detach();
+ }
+
+ return parseMemoryDump(events, contents.getOSProcessId());
+ }
+
@IpcMethod()
async getGpuStatus(): Promise<GpuStatus> {
const info = (await app.getGPUInfo('complete')) as CompleteGpuInfo;
diff --git a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
index 2235e5dea5c..6582ef806c7 100644
--- a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
@@ -72,19 +72,45 @@ describe('DevtoolsCtr', () => {
await expect(devtoolsCtr.getAppProcessMetrics()).resolves.toEqual({
cpuPercent: 3.75,
gpu: null,
+ processes: [
+ {
+ cpuPercent: 1.5,
+ name: null,
+ pid: undefined,
+ type: 'Browser',
+ workingSetMB: 100 / 1024,
+ },
+ { cpuPercent: 2.25, name: null, pid: undefined, type: 'Tab', workingSetMB: 200 / 1024 },
+ { cpuPercent: 0, name: null, pid: undefined, type: 'Utility', workingSetMB: 300 / 1024 },
+ ],
rendererResidentMB: null,
});
});
it('should report the gpu process usage separately in megabytes', async () => {
getAppMetricsMock.mockReturnValue([
- { cpu: { percentCPUUsage: 1.5 }, memory: { workingSetSize: 1024 }, type: 'Browser' },
- { cpu: { percentCPUUsage: 2.5 }, memory: { workingSetSize: 65_536 }, type: 'GPU' },
+ {
+ cpu: { percentCPUUsage: 1.5 },
+ memory: { workingSetSize: 1024 },
+ pid: 1,
+ type: 'Browser',
+ },
+ {
+ cpu: { percentCPUUsage: 2.5 },
+ memory: { workingSetSize: 65_536 },
+ name: 'GPU Process',
+ pid: 2,
+ type: 'GPU',
+ },
]);
await expect(devtoolsCtr.getAppProcessMetrics()).resolves.toEqual({
cpuPercent: 4,
gpu: { cpuPercent: 2.5, memoryMB: 64 },
+ processes: [
+ { cpuPercent: 1.5, name: null, pid: 1, type: 'Browser', workingSetMB: 1 },
+ { cpuPercent: 2.5, name: 'GPU Process', pid: 2, type: 'GPU', workingSetMB: 64 },
+ ],
rendererResidentMB: null,
});
});
@@ -95,7 +121,7 @@ describe('DevtoolsCtr', () => {
{ cpu: { percentCPUUsage: 3 }, memory: { workingSetSize: 3072 }, type: 'GPU' },
]);
- await expect(devtoolsCtr.getAppProcessMetrics()).resolves.toEqual({
+ await expect(devtoolsCtr.getAppProcessMetrics()).resolves.toMatchObject({
cpuPercent: 4,
gpu: { cpuPercent: 4, memoryMB: 4 },
rendererResidentMB: null,
@@ -108,6 +134,7 @@ describe('DevtoolsCtr', () => {
await expect(devtoolsCtr.getAppProcessMetrics()).resolves.toEqual({
cpuPercent: 0,
gpu: null,
+ processes: [],
rendererResidentMB: null,
});
});
@@ -123,7 +150,60 @@ describe('DevtoolsCtr', () => {
runWithIpcContext({ event: { sender } as any, sender }, () =>
devtoolsCtr.getAppProcessMetrics(),
),
- ).resolves.toEqual({ cpuPercent: 3, gpu: null, rendererResidentMB: 8 });
+ ).resolves.toMatchObject({ cpuPercent: 3, gpu: null, rendererResidentMB: 8 });
+ });
+ });
+
+ describe('captureMemoryDump', () => {
+ it('should drive the memory-infra tracing dance over the sender debugger', async () => {
+ const handlers = new Set<(event: unknown, method: string, params: unknown) => void>();
+ const emit = (method: string, params?: unknown) => {
+ for (const handler of handlers) handler({}, method, params);
+ };
+ const sendCommand = vi.fn(async (method: string) => {
+ if (method === 'Tracing.end') {
+ emit('Tracing.dataCollected', {
+ value: [
+ {
+ args: { dumps: { allocators: { v8: { attrs: { size: { value: '100000' } } } } } },
+ ph: 'v',
+ pid: 42,
+ },
+ ],
+ });
+ emit('Tracing.tracingComplete');
+ }
+ return {};
+ });
+ const dbg = {
+ attach: vi.fn(),
+ detach: vi.fn(),
+ isAttached: () => false,
+ off: vi.fn((_: string, handler: any) => handlers.delete(handler)),
+ on: vi.fn((_: string, handler: any) => handlers.add(handler)),
+ sendCommand,
+ };
+ const sender = { debugger: dbg, getOSProcessId: () => 42 } as any;
+
+ const dump = await runWithIpcContext({ event: { sender } as any, sender }, () =>
+ devtoolsCtr.captureMemoryDump(),
+ );
+
+ expect(sendCommand.mock.calls.map(([method]) => method)).toEqual([
+ 'Tracing.start',
+ 'Tracing.requestMemoryDump',
+ 'Tracing.end',
+ ]);
+ expect(dump.processes).toHaveLength(1);
+ expect(dump.processes[0]).toMatchObject({ isCaller: true, pid: 42 });
+ expect(dump.processes[0].allocators[0]).toEqual({
+ children: [],
+ name: 'v8',
+ sizeBytes: 0x10_00_00,
+ });
+ expect(dbg.attach).toHaveBeenCalledWith('1.3');
+ expect(dbg.detach).toHaveBeenCalledOnce();
+ expect(handlers.size).toBe(0);
});
});
diff --git a/apps/desktop/src/main/utils/__tests__/memoryDump.test.ts b/apps/desktop/src/main/utils/__tests__/memoryDump.test.ts
new file mode 100644
index 00000000000..f4cc4192075
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/memoryDump.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseMemoryDump, type TraceEvent } from '../memoryDump';
+
+const size = (bytes: number) => ({ effective_size: { value: bytes.toString(16) } });
+const MB = 1024 * 1024;
+
+const events: TraceEvent[] = [
+ { args: { name: 'Browser' }, name: 'process_name', ph: 'M', pid: 1 },
+ { args: { name: 'Renderer' }, name: 'process_name', ph: 'M', pid: 2 },
+ {
+ args: {
+ dumps: {
+ allocators: {
+ 'blink_objects/Node': { attrs: { object_count: { value: '9c9b' } } },
+ 'blink_objects/blink_gc': { attrs: size(10 * MB) },
+ 'global/abc': { attrs: size(50 * MB) },
+ 'shared_memory/abc': { attrs: size(50 * MB) },
+ 'v8': { attrs: size(300 * MB) },
+ 'v8/main': { attrs: size(298 * MB) },
+ 'v8/main/heap': { attrs: size(290 * MB) },
+ 'v8/main/heap/old_space': { attrs: size(200 * MB) },
+ 'v8/main/malloc': { attrs: size(8 * MB) },
+ 'v8/shared': { attrs: { size: { value: (2 * MB).toString(16) } } },
+ 'v8/tiny': { attrs: size(1024) },
+ },
+ process_totals: { private_footprint_bytes: (1000 * MB).toString(16) },
+ },
+ },
+ ph: 'v',
+ pid: 2,
+ },
+ { args: { dumps: { allocators: { malloc: { attrs: size(40 * MB) } } } }, ph: 'v', pid: 1 },
+];
+
+describe('parseMemoryDump', () => {
+ it('should put the calling renderer first with a size-sorted allocator tree', () => {
+ const dump = parseMemoryDump(events, 2);
+
+ expect(dump.processes.map((p) => [p.pid, p.name, p.isCaller])).toEqual([
+ [2, 'Renderer', true],
+ [1, 'Browser', false],
+ ]);
+
+ const renderer = dump.processes[0];
+ expect(renderer.privateFootprintBytes).toBe(1000 * MB);
+ expect(renderer.residentBytes).toBeNull();
+ expect(renderer.objectCounts).toEqual({ Node: 40_091 });
+ expect(renderer.allocators).toEqual([
+ {
+ children: [
+ {
+ children: [
+ { children: [], name: 'heap', sizeBytes: 290 * MB },
+ { children: [], name: 'malloc', sizeBytes: 8 * MB },
+ ],
+ name: 'main',
+ sizeBytes: 298 * MB,
+ },
+ { children: [], name: 'shared', sizeBytes: 2 * MB },
+ ],
+ name: 'v8',
+ sizeBytes: 300 * MB,
+ },
+ ]);
+ });
+
+ it('should fall back to a pid label when the process name is missing', () => {
+ const dump = parseMemoryDump([events[3]]);
+ expect(dump.processes[0].name).toBe('pid 1');
+ expect(dump.processes[0].isCaller).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/utils/memoryDump.ts b/apps/desktop/src/main/utils/memoryDump.ts
new file mode 100644
index 00000000000..bfefef98bdc
--- /dev/null
+++ b/apps/desktop/src/main/utils/memoryDump.ts
@@ -0,0 +1,99 @@
+import type { MemoryDump, MemoryDumpNode, MemoryDumpProcess } from '@lobechat/electron-client-ipc';
+
+interface TraceAttr {
+ value: string;
+}
+
+interface TraceAllocator {
+ attrs?: Record<string, TraceAttr>;
+}
+
+export interface TraceEvent {
+ args?: {
+ dumps?: {
+ allocators?: Record<string, TraceAllocator>;
+ process_totals?: Record<string, string>;
+ };
+ name?: string;
+ };
+ name?: string;
+ ph: string;
+ pid: number;
+}
+
+const MIN_NODE_BYTES = 64 * 1024;
+const MAX_DEPTH = 3;
+const SKIPPED_ROOTS = new Set(['global', 'shared_memory', 'blink_objects']);
+
+const hex = (value: string | undefined) => (value === undefined ? null : parseInt(value, 16));
+
+const insert = (roots: MemoryDumpNode[], path: string[], sizeBytes: number) => {
+ let siblings = roots;
+ for (const [index, segment] of path.entries()) {
+ let node = siblings.find((candidate) => candidate.name === segment);
+ if (!node) {
+ node = { children: [], name: segment, sizeBytes: 0 };
+ siblings.push(node);
+ }
+ if (index === path.length - 1) node.sizeBytes = sizeBytes;
+ siblings = node.children;
+ }
+};
+
+const sortTree = (nodes: MemoryDumpNode[]) => {
+ nodes.sort((a, b) => b.sizeBytes - a.sizeBytes);
+ for (const node of nodes) sortTree(node.children);
+};
+
+const buildProcess = (
+ event: TraceEvent,
+ name: string,
+ callerPid: number | undefined,
+): MemoryDumpProcess => {
+ const { allocators = {}, process_totals: totals = {} } = event.args!.dumps!;
+ const roots: MemoryDumpNode[] = [];
+ const objectCounts: Record<string, number> = {};
+
+ for (const [path, allocator] of Object.entries(allocators)) {
+ const segments = path.split('/');
+ if (segments[0] === 'blink_objects' && segments.length === 2) {
+ const count = hex(allocator.attrs?.object_count?.value);
+ if (count) objectCounts[segments[1]] = count;
+ continue;
+ }
+ if (SKIPPED_ROOTS.has(segments[0]) || segments.length > MAX_DEPTH) continue;
+ const size = hex((allocator.attrs?.effective_size ?? allocator.attrs?.size)?.value);
+ if (size === null || size < MIN_NODE_BYTES) continue;
+ insert(roots, segments, size);
+ }
+ sortTree(roots);
+
+ return {
+ allocators: roots,
+ isCaller: event.pid === callerPid,
+ name,
+ objectCounts,
+ pid: event.pid,
+ privateFootprintBytes: hex(totals.private_footprint_bytes),
+ residentBytes: hex(totals.resident_set_bytes),
+ };
+};
+
+export const parseMemoryDump = (events: TraceEvent[], callerPid?: number): MemoryDump => {
+ const names = new Map<number, string>();
+ for (const event of events) {
+ if (event.ph === 'M' && event.name === 'process_name' && event.args?.name)
+ names.set(event.pid, event.args.name);
+ }
+
+ const seen = new Set<number>();
+ const processes: MemoryDumpProcess[] = [];
+ for (const event of events) {
+ if (event.ph !== 'v' || !event.args?.dumps?.allocators || seen.has(event.pid)) continue;
+ seen.add(event.pid);
+ processes.push(buildProcess(event, names.get(event.pid) ?? `pid ${event.pid}`, callerPid));
+ }
+ processes.sort((a, b) => Number(b.isCaller) - Number(a.isCaller));
+
+ return { capturedAt: Date.now(), processes };
+};
diff --git a/apps/desktop/src/preload/electronApi.test.ts b/apps/desktop/src/preload/electronApi.test.ts
index 93cf51dd8a7..f51d6004012 100644
--- a/apps/desktop/src/preload/electronApi.test.ts
+++ b/apps/desktop/src/preload/electronApi.test.ts
@@ -8,8 +8,12 @@ const mockContextBridgeExposeInMainWorld = vi.fn();
const mockIpcRendererOn = vi.fn();
const mockIpcRendererSendSync = vi.fn();
const mockGetProcessMemoryInfo = vi.fn();
+const mockGetHeapStatistics = vi.fn();
+const mockGetBlinkMemoryInfo = vi.fn();
const originalGetProcessMemoryInfo = process.getProcessMemoryInfo;
+const originalGetHeapStatistics = process.getHeapStatistics;
+const originalGetBlinkMemoryInfo = process.getBlinkMemoryInfo;
vi.mock('electron', () => ({
contextBridge: {
@@ -45,7 +49,13 @@ describe('setupElectronApi', () => {
vi.clearAllMocks();
vi.resetModules();
mockGetProcessMemoryInfo.mockReset();
- Object.assign(process, { getProcessMemoryInfo: mockGetProcessMemoryInfo });
+ mockGetHeapStatistics.mockReset();
+ mockGetBlinkMemoryInfo.mockReset();
+ Object.assign(process, {
+ getBlinkMemoryInfo: mockGetBlinkMemoryInfo,
+ getHeapStatistics: mockGetHeapStatistics,
+ getProcessMemoryInfo: mockGetProcessMemoryInfo,
+ });
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
({ setupElectronApi } = await import('./electronApi'));
});
@@ -53,6 +63,10 @@ describe('setupElectronApi', () => {
afterAll(() => {
if (originalGetProcessMemoryInfo) process.getProcessMemoryInfo = originalGetProcessMemoryInfo;
else Reflect.deleteProperty(process, 'getProcessMemoryInfo');
+ if (originalGetHeapStatistics) process.getHeapStatistics = originalGetHeapStatistics;
+ else Reflect.deleteProperty(process, 'getHeapStatistics');
+ if (originalGetBlinkMemoryInfo) process.getBlinkMemoryInfo = originalGetBlinkMemoryInfo;
+ else Reflect.deleteProperty(process, 'getBlinkMemoryInfo');
});
it('should expose electron API to main world', () => {
@@ -88,11 +102,27 @@ describe('setupElectronApi', () => {
it('reads precise renderer process memory', async () => {
mockGetProcessMemoryInfo.mockResolvedValue({ private: 2_621_440, shared: 1024 });
+ mockGetHeapStatistics.mockReturnValue({
+ heapSizeLimit: 4_194_304,
+ mallocedMemory: 512,
+ totalHeapSize: 2048,
+ totalPhysicalSize: 1536,
+ usedHeapSize: 1024,
+ });
+ mockGetBlinkMemoryInfo.mockReturnValue({ allocated: 256, total: 320 });
setupElectronApi();
const exposedAPI = mockContextBridgeExposeInMainWorld.mock.calls[1][1];
await expect(exposedAPI.getRendererMemoryInfo()).resolves.toEqual({
+ blink: { allocatedBytes: 262_144, totalBytes: 327_680 },
+ heap: {
+ limitBytes: 4_294_967_296,
+ mallocedBytes: 524_288,
+ physicalBytes: 1_572_864,
+ totalBytes: 2_097_152,
+ usedBytes: 1_048_576,
+ },
privateBytes: 2_684_354_560,
sharedBytes: 1_048_576,
});
diff --git a/apps/desktop/src/preload/electronApi.ts b/apps/desktop/src/preload/electronApi.ts
index 737aedc7a83..ee4575361f3 100644
--- a/apps/desktop/src/preload/electronApi.ts
+++ b/apps/desktop/src/preload/electronApi.ts
@@ -34,8 +34,21 @@ export const setupElectronApi = () => {
getDesktopBootstrapIdentity: () => ipcRenderer.sendSync('desktop:get-bootstrap-identity'),
getRendererMemoryInfo: async (): Promise<RendererMemoryInfo> => {
const memory = await process.getProcessMemoryInfo();
+ const heap = process.getHeapStatistics();
+ const blink = process.getBlinkMemoryInfo();
- return { privateBytes: memory.private * 1024, sharedBytes: memory.shared * 1024 };
+ return {
+ blink: { allocatedBytes: blink.allocated * 1024, totalBytes: blink.total * 1024 },
+ heap: {
+ limitBytes: heap.heapSizeLimit * 1024,
+ mallocedBytes: heap.mallocedMemory * 1024,
+ physicalBytes: heap.totalPhysicalSize * 1024,
+ totalBytes: heap.totalHeapSize * 1024,
+ usedBytes: heap.usedHeapSize * 1024,
+ },
+ privateBytes: memory.private * 1024,
+ sharedBytes: memory.shared * 1024,
+ };
},
invoke,
onScreenCaptureSession: (listener: (session: ScreenCaptureSession) => void) => {
diff --git a/packages/electron-client-ipc/src/types/devtools.ts b/packages/electron-client-ipc/src/types/devtools.ts
index c02e0193209..4c85dc90aa8 100644
--- a/packages/electron-client-ipc/src/types/devtools.ts
+++ b/packages/electron-client-ipc/src/types/devtools.ts
@@ -3,18 +3,63 @@ export interface GpuProcessMetrics {
memoryMB: number;
}
+export interface AppProcessRow {
+ cpuPercent: number;
+ name: string | null;
+ pid: number;
+ type: string;
+ workingSetMB: number;
+}
+
export interface AppProcessMetrics {
cpuPercent: number;
gpu: GpuProcessMetrics | null;
+ processes: AppProcessRow[];
/** Resident set of the calling renderer, null when its pid is not in the metrics. */
rendererResidentMB: number | null;
}
+export interface RendererHeapInfo {
+ limitBytes: number;
+ mallocedBytes: number;
+ physicalBytes: number;
+ totalBytes: number;
+ usedBytes: number;
+}
+
+export interface RendererBlinkInfo {
+ allocatedBytes: number;
+ totalBytes: number;
+}
+
export interface RendererMemoryInfo {
+ blink: RendererBlinkInfo;
+ heap: RendererHeapInfo;
privateBytes: number;
sharedBytes: number;
}
+export interface MemoryDumpNode {
+ children: MemoryDumpNode[];
+ name: string;
+ sizeBytes: number;
+}
+
+export interface MemoryDumpProcess {
+ allocators: MemoryDumpNode[];
+ isCaller: boolean;
+ name: string;
+ objectCounts: Record<string, number>;
+ pid: number;
+ privateFootprintBytes: number | null;
+ residentBytes: number | null;
+}
+
+export interface MemoryDump {
+ capturedAt: number;
+ processes: MemoryDumpProcess[];
+}
+
export interface GpuStatus {
displayType: string | null;
featureStatus: Record<string, string>;
diff --git a/src/features/DevDock/widgets/MemoryPopover/DumpTree.tsx b/src/features/DevDock/widgets/MemoryPopover/DumpTree.tsx
new file mode 100644
index 00000000000..8339e260b84
--- /dev/null
+++ b/src/features/DevDock/widgets/MemoryPopover/DumpTree.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import type { MemoryDumpNode, MemoryDumpProcess } from '@lobechat/electron-client-ipc';
+import { cx } from 'antd-style';
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import { Fragment, memo, useState } from 'react';
+
+import { formatCompactSize } from '../memoryFormat';
+import { styles } from './styles';
+
+const OBJECT_COUNT_KEYS = [
+ 'Node',
+ 'LayoutObject',
+ 'JSEventListener',
+ 'ArrayBufferContents',
+ 'Document',
+ 'Frame',
+ 'Resource',
+];
+
+const NodeRow = memo<{
+ depth: number;
+ expanded: Set<string>;
+ node: MemoryDumpNode;
+ path: string;
+ toggle: (path: string) => void;
+ total: number;
+}>(({ depth, expanded, node, path, toggle, total }) => {
+ const open = expanded.has(path);
+ const hasChildren = node.children.length > 0;
+ const percent = total > 0 ? (node.sizeBytes / total) * 100 : 0;
+
+ return (
+ <Fragment>
+ <div
+ className={cx(styles.row, styles.mono, hasChildren && styles.rowClickable)}
+ onClick={hasChildren ? () => toggle(path) : undefined}
+ >
+ <span
+ style={{ alignItems: 'center', display: 'flex', gap: 4, paddingInlineStart: depth * 14 }}
+ >
+ {hasChildren ? (
+ open ? (
+ <ChevronDown size={11} />
+ ) : (
+ <ChevronRight size={11} />
+ )
+ ) : (
+ <span style={{ width: 11 }} />
+ )}
+ <span className={depth === 0 ? undefined : styles.muted}>{node.name}</span>
+ </span>
+ <span style={{ textAlign: 'end' }}>{formatCompactSize(node.sizeBytes)}</span>
+ <span className={styles.bar} title={`${percent.toFixed(1)}% of tracked`}>
+ <span className={styles.barFill} style={{ width: `${Math.min(100, percent)}%` }} />
+ </span>
+ </div>
+ {open &&
+ node.children.map((child) => (
+ <NodeRow
+ depth={depth + 1}
+ expanded={expanded}
+ key={child.name}
+ node={child}
+ path={`${path}/${child.name}`}
+ toggle={toggle}
+ total={total}
+ />
+ ))}
+ </Fragment>
+ );
+});
+
+NodeRow.displayName = 'DevMemoryDumpNodeRow';
+
+const DumpTree = memo<{ process: MemoryDumpProcess }>(({ process }) => {
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const toggle = (path: string) =>
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return next;
+ });
+
+ const total = process.allocators.reduce((sum, node) => sum + node.sizeBytes, 0);
+ const counts = OBJECT_COUNT_KEYS.filter((key) => process.objectCounts[key] !== undefined);
+
+ return (
+ <Fragment>
+ <div className={cx(styles.row, styles.mono)}>
+ <span>
+ {process.name} <span className={styles.muted}>pid {process.pid}</span>
+ </span>
+ <span style={{ textAlign: 'end' }}>{formatCompactSize(total)}</span>
+ <span className={styles.muted}>
+ {process.privateFootprintBytes === null
+ ? 'tracked'
+ : `footprint ${formatCompactSize(process.privateFootprintBytes)}`}
+ </span>
+ </div>
+ {process.allocators.map((node) => (
+ <NodeRow
+ depth={0}
+ expanded={expanded}
+ key={node.name}
+ node={node}
+ path={`${process.pid}/${node.name}`}
+ toggle={toggle}
+ total={total}
+ />
+ ))}
+ {counts.length > 0 && (
+ <div className={cx(styles.caption, styles.mono)}>
+ {counts.map((key) => `${key} ${process.objectCounts[key].toLocaleString()}`).join(' · ')}
+ </div>
+ )}
+ </Fragment>
+ );
+});
+
+DumpTree.displayName = 'DevMemoryDumpTree';
+
+export default DumpTree;
diff --git a/src/features/DevDock/widgets/MemoryPopover/HistoryChart.tsx b/src/features/DevDock/widgets/MemoryPopover/HistoryChart.tsx
new file mode 100644
index 00000000000..719988b4c97
--- /dev/null
+++ b/src/features/DevDock/widgets/MemoryPopover/HistoryChart.tsx
@@ -0,0 +1,79 @@
+'use client';
+
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import { formatCompactSize } from '../memoryFormat';
+import { MAX_HISTORY, type MemorySample } from '../memorySamples';
+import { styles } from './styles';
+
+const HEIGHT = 72;
+const WIDTH = 600;
+
+interface Series {
+ color: string;
+ label: string;
+ read: (sample: MemorySample) => number | null;
+}
+
+const SERIES: Series[] = [
+ { color: cssVar.colorInfo, label: 'private', read: (s) => s.renderer?.privateBytes ?? null },
+ { color: cssVar.colorSuccess, label: 'JS heap', read: (s) => s.jsHeapUsedBytes },
+];
+
+const pathFor = (values: (number | null)[], max: number) => {
+ const sx = (index: number) => (index / Math.max(1, values.length - 1)) * WIDTH;
+ const sy = (value: number) => HEIGHT - 1 - (value / max) * (HEIGHT - 2);
+ let d = '';
+ for (const [index, value] of values.entries()) {
+ if (value === null) continue;
+ d += `${d ? 'L' : 'M'}${sx(index).toFixed(1)} ${sy(value).toFixed(1)} `;
+ }
+ return d;
+};
+
+const HistoryChart = memo<{ history: MemorySample[] }>(({ history }) => {
+ const series = SERIES.map((item) => ({ ...item, values: history.map(item.read) })).filter(
+ (item) => item.values.some((value) => value !== null),
+ );
+ const max = Math.max(1, ...series.flatMap((item) => item.values.map((v) => v ?? 0)));
+ const spanSeconds = history.length > 1 ? (history.at(-1)!.at - history[0].at) / 1000 : 0;
+
+ return (
+ <div style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`, flexShrink: 0 }}>
+ <svg
+ aria-hidden
+ height={HEIGHT}
+ preserveAspectRatio={'none'}
+ style={{ display: 'block', paddingInline: 12, width: '100%' }}
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ >
+ {series.map((item) => (
+ <path
+ d={pathFor(item.values, max)}
+ fill={'none'}
+ key={item.label}
+ stroke={item.color}
+ strokeWidth={1.5}
+ vectorEffect={'non-scaling-stroke'}
+ />
+ ))}
+ </svg>
+ <div className={styles.caption} style={{ display: 'flex', gap: 12 }}>
+ {series.map((item) => (
+ <span key={item.label} style={{ color: item.color }}>
+ ● {item.label} {formatCompactSize(item.values.at(-1) ?? 0)}
+ </span>
+ ))}
+ <span style={{ flex: 1 }} />
+ <span>
+ top {formatCompactSize(max)} · last {Math.round(spanSeconds)}s of {MAX_HISTORY * 2}s
+ </span>
+ </div>
+ </div>
+ );
+});
+
+HistoryChart.displayName = 'DevMemoryHistoryChart';
+
+export default HistoryChart;
diff --git a/src/features/DevDock/widgets/MemoryPopover/index.tsx b/src/features/DevDock/widgets/MemoryPopover/index.tsx
new file mode 100644
index 00000000000..09263a8ebef
--- /dev/null
+++ b/src/features/DevDock/widgets/MemoryPopover/index.tsx
@@ -0,0 +1,194 @@
+'use client';
+
+import type { MemoryDump } from '@lobechat/electron-client-ipc';
+import { Flexbox } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { Fragment, memo, useState } from 'react';
+
+import { isDesktop } from '@/const/version';
+import { electronDevtoolsService } from '@/services/electron/devtools';
+
+import { devDockPanelStyles } from '../../panelStyles';
+import { useAppProcessMetrics } from '../appProcessMetrics';
+import { formatCompactSize } from '../memoryFormat';
+import { type MemorySample, useMemorySamples } from '../memorySamples';
+import DumpTree from './DumpTree';
+import HistoryChart from './HistoryChart';
+import { styles } from './styles';
+
+const MB = 1024 * 1024;
+
+const Stat = memo<{ hint?: string; label: string; value: string }>(({ hint, label, value }) => (
+ <div className={styles.cell} title={hint}>
+ <span className={styles.key}>{label}</span>
+ <span className={styles.value}>{value}</span>
+ </div>
+));
+
+Stat.displayName = 'DevMemoryStat';
+
+const Overview = memo<{ residentMB: number | null; sample: MemorySample }>(
+ ({ residentMB, sample }) => {
+ const { renderer } = sample;
+ const heapUsed = renderer?.heap.usedBytes ?? sample.jsHeapUsedBytes;
+ const heapLimit = renderer?.heap.limitBytes ?? sample.jsHeapLimitBytes;
+ const reclaimable =
+ residentMB !== null && renderer
+ ? Math.max(0, residentMB * MB - renderer.privateBytes - renderer.sharedBytes)
+ : null;
+
+ return (
+ <div className={styles.overview}>
+ {renderer && (
+ <Fragment>
+ <Stat
+ hint={'process.getProcessMemoryInfo().private — what the R readout shows'}
+ label={'private'}
+ value={formatCompactSize(renderer.privateBytes)}
+ />
+ <Stat label={'shared'} value={formatCompactSize(renderer.sharedBytes)} />
+ <Stat
+ hint={'app.getAppMetrics() workingSetSize'}
+ label={'resident'}
+ value={residentMB === null ? '—' : formatCompactSize(residentMB * MB)}
+ />
+ <Stat
+ hint={'resident − private − shared: freed pages macOS has not reclaimed yet'}
+ label={'reclaimable'}
+ value={reclaimable === null ? '—' : formatCompactSize(reclaimable)}
+ />
+ </Fragment>
+ )}
+ <Stat
+ hint={'V8 heap used / limit'}
+ label={'JS heap'}
+ value={`${formatCompactSize(heapUsed)} / ${formatCompactSize(heapLimit)} · ${((heapUsed / heapLimit) * 100).toFixed(1)}%`}
+ />
+ {renderer && (
+ <Fragment>
+ <Stat
+ hint={'V8 committed heap (totalHeapSize) and its physical pages'}
+ label={'heap committed'}
+ value={`${formatCompactSize(renderer.heap.totalBytes)} · phys ${formatCompactSize(renderer.heap.physicalBytes)}`}
+ />
+ <Stat
+ hint={'V8 malloc outside the managed heap'}
+ label={'v8 malloced'}
+ value={formatCompactSize(renderer.heap.mallocedBytes)}
+ />
+ <Stat
+ hint={'Blink (Oilpan) allocated / total'}
+ label={'blink'}
+ value={`${formatCompactSize(renderer.blink.allocatedBytes)} / ${formatCompactSize(renderer.blink.totalBytes)}`}
+ />
+ </Fragment>
+ )}
+ </div>
+ );
+ },
+);
+
+Overview.displayName = 'DevMemoryOverview';
+
+const Breakdown = memo(() => {
+ const [dump, setDump] = useState<MemoryDump | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const capture = async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ setDump(await electronDevtoolsService.captureMemoryDump());
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const [caller, ...others] = dump?.processes ?? [];
+
+ return (
+ <Fragment>
+ <div className={styles.sectionTitle}>
+ <span>Breakdown</span>
+ <span className={cx(styles.muted, styles.mono)}>
+ {dump
+ ? `captured ${new Date(dump.capturedAt).toLocaleTimeString()}`
+ : 'memory-infra dump'}
+ </span>
+ <span style={{ flex: 1 }} />
+ {error && <span className={cx(styles.error, styles.mono)}>{error}</span>}
+ <Button loading={loading} size={'small'} onClick={capture}>
+ {dump ? 'Re-capture' : 'Capture'}
+ </Button>
+ </div>
+ {caller && <DumpTree process={caller} />}
+ {others.map((process) => (
+ <DumpTree key={process.pid} process={process} />
+ ))}
+ </Fragment>
+ );
+});
+
+Breakdown.displayName = 'DevMemoryBreakdown';
+
+const ProcessTable = memo(() => {
+ const processes = useAppProcessMetrics()?.processes;
+ if (!processes) return null;
+
+ return (
+ <Fragment>
+ <div className={styles.sectionTitle}>Processes</div>
+ {[...processes]
+ .sort((a, b) => b.workingSetMB - a.workingSetMB)
+ .map((process) => (
+ <div className={cx(styles.row, styles.mono)} key={process.pid}>
+ <span>
+ {process.type}
+ {process.name && <span className={styles.muted}> · {process.name}</span>}
+ <span className={styles.muted}> pid {process.pid}</span>
+ </span>
+ <span style={{ textAlign: 'end' }}>{formatCompactSize(process.workingSetMB * MB)}</span>
+ <span className={styles.muted}>cpu {process.cpuPercent.toFixed(1)}%</span>
+ </div>
+ ))}
+ </Fragment>
+ );
+});
+
+ProcessTable.displayName = 'DevMemoryProcessTable';
+
+const MemoryPopover = memo(() => {
+ const samples = useMemorySamples();
+ const residentMB = useAppProcessMetrics()?.rendererResidentMB ?? null;
+
+ if (!samples) return null;
+
+ return (
+ <Flexbox className={cx(devDockPanelStyles.root, styles.popover)}>
+ <Overview residentMB={residentMB} sample={samples.latest} />
+ <HistoryChart history={samples.history} />
+ <div className={styles.scroll}>
+ {isDesktop && (
+ <Fragment>
+ <Breakdown />
+ <ProcessTable />
+ </Fragment>
+ )}
+ </div>
+ <div className={styles.legend}>
+ Overview samples every 2s. Breakdown attaches the CDP debugger to this renderer and requests
+ one detailed memory-infra dump (~1s): v8 is the JS heap, partition_alloc holds Blink strings
+ and buffers, web_cache keeps decoded script sources, blink_gc is the DOM and CSSOM, canvas
+ and cc/tile_memory are raster backing stores.
+ </div>
+ </Flexbox>
+ );
+});
+
+MemoryPopover.displayName = 'DevDockMemoryPopover';
+
+export default MemoryPopover;
diff --git a/src/features/DevDock/widgets/MemoryPopover/styles.ts b/src/features/DevDock/widgets/MemoryPopover/styles.ts
new file mode 100644
index 00000000000..21f393a932e
--- /dev/null
+++ b/src/features/DevDock/widgets/MemoryPopover/styles.ts
@@ -0,0 +1,109 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+export const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ height: 4px;
+ border-radius: 2px;
+ background: ${cssVar.colorFillSecondary};
+ `,
+ barFill: css`
+ height: 100%;
+ border-radius: 2px;
+ background: ${cssVar.colorInfo};
+ `,
+ caption: css`
+ padding-block: 6px;
+ padding-inline: 12px;
+ font-size: 10px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ cell: css`
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ `,
+ error: css`
+ color: ${cssVar.colorError};
+ `,
+ key: css`
+ font-size: 10px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ legend: css`
+ flex-shrink: 0;
+
+ padding-block: 8px 12px;
+ padding-inline: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 10px;
+ line-height: 1.6;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextSecondary};
+ `,
+ muted: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ popover: css`
+ width: min(640px, calc(100vw - 32px));
+ max-height: min(70vh, 720px);
+ `,
+ overview: css`
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ flex-shrink: 0;
+ gap: 8px 12px;
+
+ padding-block: 10px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ row: css`
+ display: grid;
+ grid-template-columns: 1fr 96px 120px;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 4px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ rowClickable: css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ scroll: css`
+ overflow: auto;
+ flex: 1;
+ min-height: 0;
+ max-height: 360px;
+ `,
+ sectionTitle: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11px;
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+ value: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorText};
+ white-space: nowrap;
+ `,
+}));
diff --git a/src/features/DevDock/widgets/MemoryWidget.tsx b/src/features/DevDock/widgets/MemoryWidget.tsx
index ec2dac47661..7cec5c5a201 100644
--- a/src/features/DevDock/widgets/MemoryWidget.tsx
+++ b/src/features/DevDock/widgets/MemoryWidget.tsx
@@ -1,16 +1,21 @@
'use client';
+import { Popover } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { memo, useEffect, useState } from 'react';
+import { memo, useState } from 'react';
-import { formatSize } from '@/utils/format';
-
-import { useAppProcessMetrics } from './appProcessMetrics';
+import { DOCK_Z_INDEX } from '../const';
+import { barButtonStyles } from './BarButton';
+import { formatCompactSize } from './memoryFormat';
+import MemoryPopover from './MemoryPopover';
+import { isMemorySamplingSupported, useMemorySamples } from './memorySamples';
import { isMemoryHigh } from './metricUtils';
-const formatCompactSize = (bytes: number) => formatSize(bytes).replace(' ', '').replace('B', '');
-
const styles = createStaticStyles(({ css }) => ({
+ active: css`
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ `,
high: css`
color: ${cssVar.colorError};
`,
@@ -25,83 +30,46 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface HeapSample {
- jsHeapLimitBytes: number;
- jsHeapUsedBytes: number;
- privateBytes?: number;
- sharedBytes?: number;
-}
-
-const readHeap = (): HeapSample | null => {
- const memory = (
- performance as Performance & {
- memory?: { jsHeapSizeLimit: number; usedJSHeapSize: number };
- }
- ).memory;
- if (!memory) return null;
- return {
- jsHeapLimitBytes: memory.jsHeapSizeLimit,
- jsHeapUsedBytes: memory.usedJSHeapSize,
- };
-};
-
const MemoryWidget = memo(() => {
- const [memory, setMemory] = useState<HeapSample | null>(null);
- const residentMB = useAppProcessMetrics()?.rendererResidentMB ?? null;
-
- useEffect(() => {
- if (!readHeap()) return;
- const getRendererMemoryInfo = window.electronAPI?.getRendererMemoryInfo;
-
- let disposed = false;
- const update = async () => {
- let privateBytes: number | undefined;
- let sharedBytes: number | undefined;
-
- try {
- const info = await getRendererMemoryInfo?.();
- privateBytes = info?.privateBytes;
- sharedBytes = info?.sharedBytes;
- } catch {
- /* native process metrics unavailable — JS heap remains useful */
- }
-
- const heap = readHeap();
- if (heap && !disposed) setMemory({ ...heap, privateBytes, sharedBytes });
- };
-
- void update();
- const timer = setInterval(update, 2000);
- return () => {
- disposed = true;
- clearInterval(timer);
- };
- }, []);
+ const samples = useMemorySamples();
+ const [open, setOpen] = useState(false);
- if (!memory) return null;
+ if (!isMemorySamplingSupported() || !samples) return null;
- const percent = (memory.jsHeapUsedBytes / memory.jsHeapLimitBytes) * 100;
- const high = isMemoryHigh(percent, memory.privateBytes);
- // macOS keeps madvise(MADV_FREE_REUSABLE) pages in the resident set until it needs
- // them, so resident minus private footprint is what the allocator already gave back.
- const reclaimableBytes =
- residentMB !== null && memory.privateBytes !== undefined
- ? Math.max(0, residentMB * 1024 * 1024 - memory.privateBytes - (memory.sharedBytes ?? 0))
- : undefined;
+ const { jsHeapUsedBytes, jsHeapLimitBytes, renderer } = samples.latest;
+ const percent = (jsHeapUsedBytes / jsHeapLimitBytes) * 100;
+ const high = isMemoryHigh(percent, renderer?.privateBytes);
return (
- <span
- className={cx(styles.text, high ? styles.high : percent >= 70 ? styles.mid : undefined)}
- title={
- memory.privateBytes === undefined
- ? 'JS heap used / limit'
- : 'R = Renderer private footprint (red at 1 GiB) · F = freed pages the OS has not reclaimed yet (plus some read-only library pages) · J = JS heap used / limit'
- }
+ <Popover
+ arrow={false}
+ content={<MemoryPopover />}
+ open={open}
+ placement={'topRight'}
+ positionerProps={{ sideOffset: 6 }}
+ styles={{ content: { padding: 0 } }}
+ trigger={'click'}
+ zIndex={DOCK_Z_INDEX + 1}
+ onOpenChange={setOpen}
>
- {memory.privateBytes !== undefined && `R${formatCompactSize(memory.privateBytes)} · `}
- {reclaimableBytes !== undefined && `F${formatCompactSize(reclaimableBytes)} · `}J
- {formatCompactSize(memory.jsHeapUsedBytes)} · {percent.toFixed(1)}%
- </span>
+ <button
+ type={'button'}
+ className={cx(
+ barButtonStyles.button,
+ styles.text,
+ high ? styles.high : percent >= 70 ? styles.mid : undefined,
+ open && styles.active,
+ )}
+ title={
+ renderer
+ ? 'R = Renderer private footprint (red at 1 GiB) · J = JS heap used — click for the full breakdown'
+ : 'J = JS heap used — click for the full breakdown'
+ }
+ >
+ {renderer && `R${formatCompactSize(renderer.privateBytes)} · `}J
+ {formatCompactSize(jsHeapUsedBytes)}
+ </button>
+ </Popover>
);
});
diff --git a/src/features/DevDock/widgets/memoryFormat.ts b/src/features/DevDock/widgets/memoryFormat.ts
new file mode 100644
index 00000000000..84bf39d43ec
--- /dev/null
+++ b/src/features/DevDock/widgets/memoryFormat.ts
@@ -0,0 +1,4 @@
+import { formatSize } from '@/utils/format';
+
+export const formatCompactSize = (bytes: number) =>
+ formatSize(bytes).replace(' ', '').replace('B', '');
diff --git a/src/features/DevDock/widgets/memorySamples.test.ts b/src/features/DevDock/widgets/memorySamples.test.ts
new file mode 100644
index 00000000000..199b76403e3
--- /dev/null
+++ b/src/features/DevDock/widgets/memorySamples.test.ts
@@ -0,0 +1,59 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MAX_HISTORY, useMemorySamples } from './memorySamples';
+
+const getRendererMemoryInfo = vi.fn();
+
+const advance = async (ms: number) => {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+};
+
+describe('useMemorySamples', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ getRendererMemoryInfo.mockReset();
+ getRendererMemoryInfo.mockResolvedValue({ privateBytes: 1024, sharedBytes: 0 });
+ Object.assign(performance, { memory: { jsHeapSizeLimit: 4096, usedJSHeapSize: 512 } });
+ Object.assign(window, { electronAPI: { getRendererMemoryInfo } });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('should keep a capped history across subscribers', async () => {
+ const { result, unmount } = renderHook(() => useMemorySamples());
+
+ await advance(0);
+ expect(result.current?.latest).toMatchObject({
+ jsHeapUsedBytes: 512,
+ renderer: { privateBytes: 1024 },
+ });
+
+ await advance(2000 * (MAX_HISTORY + 10));
+ expect(result.current?.history).toHaveLength(MAX_HISTORY);
+
+ const second = renderHook(() => useMemorySamples());
+ expect(second.result.current?.history).toHaveLength(MAX_HISTORY);
+
+ unmount();
+ second.unmount();
+ });
+
+ it('should fall back to the JS heap when the electron bridge is missing', async () => {
+ Object.assign(window, { electronAPI: undefined });
+ const { result, unmount } = renderHook(() => useMemorySamples());
+
+ await advance(0);
+ expect(result.current?.latest.renderer).toBeNull();
+ expect(result.current?.latest.jsHeapLimitBytes).toBe(4096);
+
+ unmount();
+ });
+});
diff --git a/src/features/DevDock/widgets/memorySamples.ts b/src/features/DevDock/widgets/memorySamples.ts
new file mode 100644
index 00000000000..b1b14d8ac58
--- /dev/null
+++ b/src/features/DevDock/widgets/memorySamples.ts
@@ -0,0 +1,70 @@
+import type { RendererMemoryInfo } from '@lobechat/electron-client-ipc';
+import { useSyncExternalStore } from 'react';
+
+export interface MemorySample {
+ at: number;
+ jsHeapLimitBytes: number;
+ jsHeapUsedBytes: number;
+ renderer: RendererMemoryInfo | null;
+}
+
+export interface MemorySamples {
+ history: MemorySample[];
+ latest: MemorySample;
+}
+
+const SAMPLE_INTERVAL = 2000;
+export const MAX_HISTORY = 150;
+
+const listeners = new Set<() => void>();
+let snapshot: MemorySamples | null = null;
+let timer: ReturnType<typeof setInterval> | null = null;
+
+const readHeap = () => {
+ const memory = (
+ performance as Performance & {
+ memory?: { jsHeapSizeLimit: number; usedJSHeapSize: number };
+ }
+ ).memory;
+ if (!memory) return null;
+ return { jsHeapLimitBytes: memory.jsHeapSizeLimit, jsHeapUsedBytes: memory.usedJSHeapSize };
+};
+
+export const isMemorySamplingSupported = () => readHeap() !== null;
+
+const sample = async () => {
+ let renderer: RendererMemoryInfo | null = null;
+ try {
+ renderer = (await window.electronAPI?.getRendererMemoryInfo?.()) ?? null;
+ } catch {
+ /* native process metrics unavailable — JS heap remains useful */
+ }
+ const heap = readHeap();
+ if (!heap || !timer) return;
+
+ const latest: MemorySample = { ...heap, at: Date.now(), renderer };
+ const history = [...(snapshot?.history ?? []), latest].slice(-MAX_HISTORY);
+ snapshot = { history, latest };
+ for (const listener of listeners) listener();
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ if (!timer) {
+ timer = setInterval(sample, SAMPLE_INTERVAL);
+ void sample();
+ }
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size > 0 || !timer) return;
+ clearInterval(timer);
+ timer = null;
+ };
+};
+
+const getSnapshot = () => snapshot;
+
+// History survives panel open/close on purpose: the widget keeps this sampler
+// subscribed, so the panel opens onto the trend instead of an empty chart.
+export const useMemorySamples = (): MemorySamples | null =>
+ useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
diff --git a/src/services/electron/devtools.ts b/src/services/electron/devtools.ts
index 4f43b014aef..c4aa6a32a97 100644
--- a/src/services/electron/devtools.ts
+++ b/src/services/electron/devtools.ts
@@ -1,4 +1,4 @@
-import type { AppProcessMetrics, GpuStatus } from '@lobechat/electron-client-ipc';
+import type { AppProcessMetrics, GpuStatus, MemoryDump } from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -11,6 +11,10 @@ class DevtoolsService {
return ensureElectronIpc().devtools.getAppProcessMetrics();
}
+ async captureMemoryDump(): Promise<MemoryDump> {
+ return ensureElectronIpc().devtools.captureMemoryDump();
+ }
+
async getGpuStatus(): Promise<GpuStatus> {
return ensureElectronIpc().devtools.getGpuStatus();
}