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(desktop): monitor and clean up agent background processes (#20096)

Inneib03afd8370df
diff --git a/apps/desktop/resources/locales/zh-CN/menu.json b/apps/desktop/resources/locales/zh-CN/menu.json
index 95a9accb95a..304118e6397 100644
--- a/apps/desktop/resources/locales/zh-CN/menu.json
+++ b/apps/desktop/resources/locales/zh-CN/menu.json
@@ -58,6 +58,7 @@
"help.openConfigDir": "配置目录",
"help.openHeteroAgentDir": "打开 HeteroAgent 目录",
"help.openLogsDir": "打开日志目录",
+ "help.processExplorer": "打开进程管理器",
"help.reportIssue": "反馈问题",
"help.title": "帮助",
"help.toggleHeteroTracing": "记录 Agent CLI 调试日志",
diff --git a/apps/desktop/src/main/appBrowsers.ts b/apps/desktop/src/main/appBrowsers.ts
index 126a30b91d5..f5aac57665c 100644
--- a/apps/desktop/src/main/appBrowsers.ts
+++ b/apps/desktop/src/main/appBrowsers.ts
@@ -5,6 +5,7 @@ import type { BrowserWindowOpts } from './core/browser/Browser';
export const BrowsersIdentifiers = {
app: 'app',
devtools: 'devtools',
+ processExplorer: 'processExplorer',
};
export const appBrowsers = {
@@ -32,6 +33,16 @@ export const appBrowsers = {
titleBarStyle: 'hiddenInset',
width: 1000,
},
+ processExplorer: {
+ autoHideMenuBar: true,
+ height: 560,
+ identifier: 'processExplorer',
+ minHeight: 320,
+ minWidth: 560,
+ path: '/popup/processes',
+ titleBarStyle: 'hidden',
+ width: 840,
+ },
} satisfies Record<string, BrowserWindowOpts>;
// Window templates for multi-instance windows
diff --git a/apps/desktop/src/main/controllers/DevtoolsCtr.ts b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
index b3f8a624734..2d7b233269e 100644
--- a/apps/desktop/src/main/controllers/DevtoolsCtr.ts
+++ b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
@@ -1,6 +1,8 @@
import type { AppProcessMetrics, GpuStatus, MemoryDump } from '@lobechat/electron-client-ipc';
-import { app } from 'electron';
+import { getManagedProcesses, stopManagedProcess } from '@lobechat/utils/managedProcess';
+import { app, BrowserWindow, webContents } from 'electron';
+import { getSharedAppMetrics } from '@/utils/appMetrics';
import { collectRendererGarbage, startIdleRendererGc } from '@/utils/idleRendererGc';
import { getIpcContext } from '@/utils/ipc';
import { parseMemoryDump, type TraceEvent } from '@/utils/memoryDump';
@@ -21,6 +23,22 @@ const MEMORY_DUMP_TIMEOUT = 15_000;
export default class DevtoolsCtr extends ControllerModule {
static override readonly groupName = 'devtools';
+ @IpcMethod()
+ async getManagedProcesses() {
+ return getManagedProcesses();
+ }
+
+ @IpcMethod()
+ async stopManagedProcess({ id }: { id: string }) {
+ if (typeof id !== 'string' || !id) throw new Error('Invalid process identity');
+ await stopManagedProcess(id);
+ }
+
+ @IpcMethod()
+ async openProcessExplorer() {
+ this.app.browserManager.retrieveByIdentifier('processExplorer').show();
+ }
+
@IpcMethod()
async openDevtools() {
const devtoolsBrowser = this.app.browserManager.retrieveByIdentifier('devtools');
@@ -32,7 +50,13 @@ export default class DevtoolsCtr extends ControllerModule {
// sees the sliver since the other one sampled.
@IpcMethod()
async getAppProcessMetrics(): Promise<AppProcessMetrics> {
- const metrics = app.getAppMetrics();
+ const metrics = getSharedAppMetrics();
+ const windowTitles = new Map<number, string>();
+ for (const contents of webContents.getAllWebContents()) {
+ const title = BrowserWindow.fromWebContents(contents)?.getTitle();
+ const pid = contents.getOSProcessId();
+ if (title && !windowTitles.has(pid)) windowTitles.set(pid, title);
+ }
const gpuProcesses = metrics.filter((metric) => metric.type === 'GPU');
const rendererPid = getIpcContext()?.sender.getOSProcessId();
const renderer =
@@ -53,6 +77,7 @@ export default class DevtoolsCtr extends ControllerModule {
name: readText(metric.name) ?? readText(metric.serviceName),
pid: metric.pid,
type: metric.type,
+ windowTitle: windowTitles.get(metric.pid) ?? null,
workingSetMB: metric.memory.workingSetSize / 1024,
})),
rendererResidentMB: renderer ? renderer.memory.workingSetSize / 1024 : null,
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 5637587d1aa..382dbe7efa8 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -13,6 +13,7 @@ import {
resolveRemotePlatformRuntime,
} from '@lobechat/heterogeneous-agents/scanHost';
import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
+import { managedProcessEnvironment, spawnManaged } from '@lobechat/utils/managedProcess';
import { app as electronApp } from 'electron';
import { updaterConfig } from '@/modules/updater/configs';
@@ -356,6 +357,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
// the process has actually spawned (or emitted an early error) before
// acknowledging the server request.
return await this.heterogeneousAgentCtr.spawnLhHeteroExec({
+ agentId: request.agentId,
agentType: request.agentType,
assistantMessageId: request.assistantMessageId,
args: request.args,
@@ -916,10 +918,10 @@ export default class GatewayConnectionCtr extends ControllerModule {
'--local',
];
const spawnPlan = await runtime.prepareSpawn(openclawArgs);
- const child = spawn(spawnPlan.command, spawnPlan.args, {
+ const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: workDir,
detached: true,
- env: spawnPlan.env,
+ env: { ...spawnPlan.env, ...managedProcessEnvironment({ topicId, agentId }) },
stdio: 'ignore',
});
@@ -1012,10 +1014,10 @@ export default class GatewayConnectionCtr extends ControllerModule {
// Hermes keeps stdout response-only in --quiet mode and prints the final
// session_id to stderr so callers can resume the session on the next turn.
const spawnPlan = await runtime.prepareSpawn(hermesArgs);
- const child = spawn(spawnPlan.command, spawnPlan.args, {
+ const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: workDir,
detached: true,
- env: spawnPlan.env,
+ env: { ...spawnPlan.env, ...managedProcessEnvironment({ topicId, agentId }) },
stdio: ['ignore', 'pipe', 'pipe'],
});
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 36ab364881a..bc708bdf225 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -114,6 +114,11 @@ import type {
HeteroSessionImportMessage,
ListHeterogeneousAgentModelsParams,
} from '@lobechat/types';
+import {
+ managedProcessEnvironment,
+ shutdownManagedProcesses,
+ spawnManaged,
+} from '@lobechat/utils/managedProcess';
import { sleep } from '@lobechat/utils/sleep';
import { app as electronApp, BrowserWindow } from 'electron';
import { isPlainObject } from 'es-toolkit';
@@ -487,6 +492,7 @@ interface AgentSession {
/** Active pi RPC run (per-run process; cleared when the run settles). */
piRpcSession?: PiRpcSession;
process?: ChildProcess;
+ processOwner?: { topicId?: string; agentId?: string };
/**
* Absolute CLI path resolved by spawn preflight detection. Used for spawn()
* when the configured command is bare: detection can find the CLI through
@@ -1181,7 +1187,10 @@ export default class HeterogeneousAgentCtr {
);
}
- private buildSessionSpawnEnv(session: AgentSession): NodeJS.ProcessEnv {
+ private buildSessionSpawnEnv(
+ session: AgentSession,
+ includeProcessOwnership = true,
+ ): NodeJS.ProcessEnv {
// Forward the user's proxy settings to the CLI/SDK subprocess. The
// main-process undici dispatcher doesn't reach child processes — they need
// env vars.
@@ -1198,6 +1207,12 @@ export default class HeterogeneousAgentCtr {
? { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' }
: {}),
...session.env,
+ ...(includeProcessOwnership
+ ? managedProcessEnvironment(
+ { ...session.processOwner, label: session.agentType },
+ session.env?.AGENT_BROWSER_SESSION,
+ )
+ : {}),
};
const operationTokenEnvKey = session.hostedProviderBinding?.operationTokenEnvKey;
if (session.serverOperationToken && operationTokenEnvKey) {
@@ -1749,7 +1764,10 @@ export default class HeterogeneousAgentCtr {
params: SendPromptParams,
): Promise<ServerDefaultOperationSettlement | HeteroTranscriptReplayOutcome | void> {
const session = this.sessions.get(params.sessionId);
- if (session) session.cancelledByUs = false;
+ if (session) {
+ session.cancelledByUs = false;
+ session.processOwner = { topicId: params.topicId, agentId: params.agentId };
+ }
// A replay reads a file and calls no model, so it bypasses server-default
// operation accounting entirely.
if (params.replayTranscript) return this.replayTranscript(params);
@@ -1998,7 +2016,11 @@ export default class HeterogeneousAgentCtr {
// is matched against, and the CLI may append this turn's prompt record
// the moment it starts.
const startedAt = new Date().toISOString();
- const proc = spawn(resolvedCliSpawnPlan.command, resolvedCliSpawnPlan.args, spawnOptions);
+ const proc = spawnManaged(
+ resolvedCliSpawnPlan.command,
+ resolvedCliSpawnPlan.args,
+ spawnOptions,
+ );
this.handleSpawnedAgentProcess({
cwd,
intervention,
@@ -2164,7 +2186,8 @@ export default class HeterogeneousAgentCtr {
session: AgentSession,
): Promise<boolean> {
const cwd = session.cwd || electronApp.getPath('desktop');
- const spawnEnv = this.buildSessionSpawnEnv(session);
+ // One app-server serves multiple topics; ownership belongs to each thread, not its process.
+ const spawnEnv = this.buildSessionSpawnEnv(session, false);
const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
const promptInput = buildHeterogeneousPrompt({
imageList: params.imageList,
@@ -4110,7 +4133,7 @@ export default class HeterogeneousAgentCtr {
event.preventDefault();
if (this.shuttingDown) return;
this.shuttingDown = true;
- const piClosing: Promise<void>[] = [];
+ const piClosing: Promise<void>[] = [shutdownManagedProcesses()];
this.unlinkPendingInterventionConfigsSync();
for (const [, session] of this.sessions) {
session.hostedProviderBinding?.cleanupSync();
@@ -4201,6 +4224,7 @@ export default class HeterogeneousAgentCtr {
* eager accepted ack would strand the server operation without a producer.
*/
spawnLhHeteroExec(params: {
+ agentId?: string;
agentType: string;
assistantMessageId?: string;
/** Resolved `lh hetero exec` wrapper args. */
@@ -4318,10 +4342,13 @@ export default class HeterogeneousAgentCtr {
// `killPlatformProcessTree(-pid, signal)` reaches the CLI and its children;
// the inherited-group env contract prevents the inner agent from detaching
// into a second, unreachable group.
- const child = spawn(process.execPath, [cliScript, ...args], {
+ const child = spawnManaged(process.execPath, [cliScript, ...args], {
cwd: spawnCwd,
detached: true,
- env,
+ env: {
+ ...env,
+ ...managedProcessEnvironment({ topicId, agentId: params.agentId, label: agentType }),
+ },
stdio: ['pipe', 'inherit', 'inherit'],
windowsHide: true,
});
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index bfad7d2f7c4..57df4ba338a 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -24,6 +24,7 @@ import {
setWindowsShellPreference,
ShellProcessManager,
} from '@lobechat/local-file-shell/shell';
+import { managedProcessEnvironment, spawnManagedFor } from '@lobechat/utils/managedProcess';
import { createLogger } from '@/utils/logger';
@@ -241,6 +242,25 @@ export default class ShellCommandCtr extends ControllerModule {
@IpcMethod()
async handleRunCommand(params: RunCommandParams): Promise<RunCommandResult> {
+ const spawnProcess = spawnManagedFor({
+ topicId: params.topicId,
+ agentId: params.agentId,
+ label: params.description || 'Shell',
+ });
+ params = {
+ ...params,
+ env: {
+ ...params.env,
+ ...managedProcessEnvironment(
+ {
+ topicId: params.topicId,
+ agentId: params.agentId,
+ label: params.description || 'Shell',
+ },
+ params.env?.AGENT_BROWSER_SESSION,
+ ),
+ },
+ };
if (SIMPLE_LH_PREFIX.test(params.command)) {
const cliCtr = this.app.getController(CliCtr);
if (cliCtr) {
@@ -260,11 +280,11 @@ export default class ShellCommandCtr extends ControllerModule {
// credentials it authenticates with.
logger.debug('Running lh command with the embedded CLI environment');
const env = await cliCtr.buildCliEnv(params.env);
- return runCommand({ ...params, env }, { logger, processManager });
+ return runCommand({ ...params, env }, { logger, processManager, spawnProcess });
}
}
- if (!params.sandbox) return runCommand(params, { logger, processManager });
+ if (!params.sandbox) return runCommand(params, { logger, processManager, spawnProcess });
// Sandboxed run. The policy is scoped to the run's working directory, so
// without one there is nothing to scope to — refuse rather than fall back
@@ -310,6 +330,7 @@ export default class ShellCommandCtr extends ControllerModule {
logger,
onSandboxUnavailable: (error) => this.downgradeSandboxCapability(error),
processManager,
+ spawnProcess,
sandboxPolicy: createLocalSandboxPolicy(params.cwd, {
allowNetwork: params.sandboxNetwork === true,
}),
diff --git a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
index 03fc3efdbeb..b2ea43735db 100644
--- a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
@@ -5,16 +5,27 @@ import { runWithIpcContext } from '@/utils/ipc';
import DevtoolsCtr from '../DevtoolsCtr';
-const { getAppMetricsMock, getGPUFeatureStatusMock, getGPUInfoMock, ipcMainHandleMock } =
- vi.hoisted(() => ({
- getAppMetricsMock: vi.fn(),
- getGPUFeatureStatusMock: vi.fn(),
- getGPUInfoMock: vi.fn(),
- ipcMainHandleMock: vi.fn(),
- }));
+const {
+ fromWebContentsMock,
+ getAllWebContentsMock,
+ getAppMetricsMock,
+ getGPUFeatureStatusMock,
+ getGPUInfoMock,
+ ipcMainHandleMock,
+} = vi.hoisted(() => ({
+ fromWebContentsMock: vi.fn(),
+ getAllWebContentsMock: vi.fn((): unknown[] => []),
+ getAppMetricsMock: vi.fn(),
+ getGPUFeatureStatusMock: vi.fn(),
+ getGPUInfoMock: vi.fn(),
+ ipcMainHandleMock: vi.fn(),
+}));
+
+vi.mock('@/utils/appMetrics', () => ({ getSharedAppMetrics: () => getAppMetricsMock() }));
vi.mock('electron', () => ({
- BrowserWindow: {},
+ BrowserWindow: { fromWebContents: fromWebContentsMock },
+ webContents: { getAllWebContents: getAllWebContentsMock },
app: {
getAppMetrics: getAppMetricsMock,
getGPUFeatureStatus: getGPUFeatureStatusMock,
@@ -79,10 +90,25 @@ describe('DevtoolsCtr', () => {
name: null,
pid: undefined,
type: 'Browser',
+ windowTitle: null,
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 },
+ {
+ cpuPercent: 2.25,
+ name: null,
+ pid: undefined,
+ type: 'Tab',
+ windowTitle: null,
+ workingSetMB: 200 / 1024,
+ },
+ {
+ cpuPercent: 0,
+ name: null,
+ pid: undefined,
+ type: 'Utility',
+ windowTitle: null,
+ workingSetMB: 300 / 1024,
+ },
],
rendererResidentMB: null,
});
@@ -109,8 +135,22 @@ describe('DevtoolsCtr', () => {
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 },
+ {
+ cpuPercent: 1.5,
+ name: null,
+ pid: 1,
+ type: 'Browser',
+ windowTitle: null,
+ workingSetMB: 1,
+ },
+ {
+ cpuPercent: 2.5,
+ name: 'GPU Process',
+ pid: 2,
+ type: 'GPU',
+ windowTitle: null,
+ workingSetMB: 64,
+ },
],
rendererResidentMB: null,
});
@@ -155,6 +195,35 @@ describe('DevtoolsCtr', () => {
});
});
+ describe('getAppProcessMetrics window titles', () => {
+ it('labels each renderer with the title of the window it hosts', async () => {
+ getAppMetricsMock.mockReturnValue([
+ { cpu: { percentCPUUsage: 0 }, memory: { workingSetSize: 1024 }, pid: 42, type: 'Tab' },
+ { cpu: { percentCPUUsage: 0 }, memory: { workingSetSize: 1024 }, pid: 43, type: 'Tab' },
+ ]);
+ getAllWebContentsMock.mockReturnValue([
+ { getOSProcessId: () => 42, title: 'LobeHub' },
+ { getOSProcessId: () => 43, title: undefined },
+ ]);
+ fromWebContentsMock.mockImplementation((contents: { title?: string }) =>
+ contents.title ? { getTitle: () => contents.title } : null,
+ );
+
+ const { processes } = await devtoolsCtr.getAppProcessMetrics();
+
+ expect(processes.map((row) => row.windowTitle)).toEqual(['LobeHub', null]);
+ });
+ });
+
+ describe('openProcessExplorer', () => {
+ it('shows the process explorer window', async () => {
+ await devtoolsCtr.openProcessExplorer();
+
+ expect(mockRetrieveByIdentifier).toHaveBeenCalledWith('processExplorer');
+ expect(mockShow).toHaveBeenCalled();
+ });
+ });
+
describe('collectRendererGarbage', () => {
it('should run HeapProfiler.collectGarbage over a debugger it attaches and detaches', async () => {
const dbg = {
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index b249e427d10..0b2e8707da1 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -11,7 +11,9 @@ import {
HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,
lobeHubCliGuide,
} from '@lobechat/heterogeneous-agents/protocol';
+import type { CodexAppServerClient as NativeCodexAppServerClient } from '@lobechat/heterogeneous-agents/spawn';
import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';
+import * as managedProcess from '@lobechat/utils/managedProcess';
// `electron` is mocked below; this binding is the mock object so tests can
// flip `isPackaged` to exercise the packaged-build tracing gate.
import { app as electronAppMock } from 'electron';
@@ -305,13 +307,14 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
}
}
- class MockCodexAppServerClient {
+ class MockCodexAppServerClient extends (actual.CodexAppServerClient as typeof NativeCodexAppServerClient) {
constructor(options: any) {
+ super(options);
codexAppServerClientConstructMock(options);
}
- canReuseFor() {
- return codexAppServerCanReuse.value;
+ canReuseFor(options: Parameters<NativeCodexAppServerClient['canReuseFor']>[0]) {
+ return codexAppServerCanReuse.value && super.canReuseFor(options);
}
get hasConsumers() {
@@ -3389,27 +3392,50 @@ describe('HeterogeneousAgentCtr', () => {
expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
});
- it('reuses one native app-server client for multiple new Codex sessions', async () => {
- const ctr = new HeterogeneousAgentCtr({
- appStoragePath,
- storeManager: { get: vi.fn() },
- } as any);
- const first = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
- const second = await ctr.startSession({
- agentType: 'codex',
- command: 'codex',
- useCodexAppServer: true,
- });
+ it('reuses one native app-server client for sessions owned by different topics and agents', async () => {
+ const registry = new managedProcess.ManagedProcessRegistry();
+ const environment = vi
+ .spyOn(managedProcess, 'managedProcessEnvironment')
+ .mockImplementation(registry.environment.bind(registry));
+ try {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const first = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ const second = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
- await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
- await ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId: second.sessionId });
+ await ctr.sendPrompt({
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ operationId: 'op-1',
+ prompt: 'first',
+ sessionId: first.sessionId,
+ });
+ await ctr.sendPrompt({
+ agentId: 'agent-2',
+ topicId: 'topic-2',
+ operationId: 'op-2',
+ prompt: 'second',
+ sessionId: second.sessionId,
+ });
- expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
- expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ const { env } = codexAppServerClientConstructMock.mock.calls[0][0];
+ expect(env.LOBEHUB_PROCESS_TOPIC).toBeUndefined();
+ expect(env.AGENT_BROWSER_NAMESPACE).toBeUndefined();
+ } finally {
+ environment.mockRestore();
+ }
});
it('reuses one native thread session across multiple turns', async () => {
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 0d1cf4d6e22..3bfacc6d3fb 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import type { DesktopBootProfilePayload } from '@lobechat/electron-client-ipc';
import type { ElectronIPCEventHandler } from '@lobechat/electron-server-ipc';
import { ElectronIPCServer } from '@lobechat/electron-server-ipc';
+import { enableManagedProcesses, shutdownManagedProcesses } from '@lobechat/utils/managedProcess';
import { app, ipcMain, nativeTheme, protocol } from 'electron';
import { name } from '@/../../package.json';
@@ -90,6 +91,7 @@ export class App {
}
constructor() {
+ enableManagedProcesses();
logger.info('----------------------------------------------');
// Log system information
logger.info(` OS: ${os.platform()} (${os.arch()})`);
@@ -183,6 +185,8 @@ export class App {
// Unified handling of before-quit event
app.on('before-quit', this.handleBeforeQuit);
+ process.on('SIGTERM', () => app.quit());
+ process.on('SIGINT', () => app.quit());
// Initialize theme mode from store
this.initializeThemeMode();
@@ -595,8 +599,23 @@ export class App {
});
}
- // Add before-quit handler function
- private handleBeforeQuit = () => {
+ private quitReady = false;
+ private quitCleanup?: Promise<void>;
+
+ private handleBeforeQuit = (event: Electron.Event) => {
+ if (this.quitReady) return;
+ event.preventDefault();
+ this.isQuiting = true;
+ this.quitCleanup ??= shutdownManagedProcesses()
+ .catch((error) => logger.error('Process shutdown failed:', error))
+ .then(() => {
+ this.destroyOnQuit();
+ this.quitReady = true;
+ app.quit();
+ });
+ };
+
+ private destroyOnQuit = () => {
logger.info('Application is preparing to quit');
this.isQuiting = true;
diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.ts
index 108668d3559..6968533c6db 100644
--- a/apps/desktop/src/main/core/__tests__/App.test.ts
+++ b/apps/desktop/src/main/core/__tests__/App.test.ts
@@ -1,3 +1,4 @@
+import * as managedProcess from '@lobechat/utils/managedProcess';
import { app as electronApp, ipcMain } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -25,6 +26,7 @@ vi.mock('electron', () => ({
setIcon: vi.fn(),
},
exit: vi.fn(),
+ quit: vi.fn(),
},
ipcMain: {
handle: vi.fn(),
@@ -223,17 +225,34 @@ describe('App', () => {
);
});
- it('destroys registered services before quitting', () => {
+ it('waits for managed processes before destroying services and completing quit', async () => {
+ let finish!: () => void;
+ vi.spyOn(managedProcess, 'shutdownManagedProcesses').mockReturnValue(
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
appInstance = new App();
const databaseService = appInstance.getService(LocalDatabaseService);
const destroy = vi.spyOn(databaseService, 'destroy');
const beforeQuitHandler = vi
.mocked(electronApp.on)
- .mock.calls.findLast(([event]) => (event as string) === 'before-quit')?.[1] as () => void;
-
- beforeQuitHandler();
-
- expect(destroy).toHaveBeenCalledOnce();
+ .mock.calls.findLast(([event]) => (event as string) === 'before-quit')?.[1] as (event: {
+ preventDefault: () => void;
+ }) => void;
+
+ const event = { preventDefault: vi.fn() };
+ beforeQuitHandler(event);
+ beforeQuitHandler(event);
+ expect(event.preventDefault).toHaveBeenCalledTimes(2);
+ expect(destroy).not.toHaveBeenCalled();
+ expect(managedProcess.shutdownManagedProcesses).toHaveBeenCalledOnce();
+ finish();
+ await vi.waitFor(() => expect(destroy).toHaveBeenCalledOnce());
+ expect(electronApp.quit).toHaveBeenCalledOnce();
+ event.preventDefault.mockClear();
+ beforeQuitHandler(event);
+ expect(event.preventDefault).not.toHaveBeenCalled();
});
it('prewarms the local database after browser initialization yields to the event loop', async () => {
diff --git a/apps/desktop/src/main/locales/default/menu.ts b/apps/desktop/src/main/locales/default/menu.ts
index 7f6001dcebf..f0d90bf240b 100644
--- a/apps/desktop/src/main/locales/default/menu.ts
+++ b/apps/desktop/src/main/locales/default/menu.ts
@@ -58,6 +58,7 @@ const menu = {
'help.openConfigDir': 'Open Config Directory',
'help.openHeteroAgentDir': 'Open HeteroAgent Directory',
'help.openLogsDir': 'Open Logs Directory',
+ 'help.processExplorer': 'Open Process Explorer',
'help.reportIssue': 'Send Feedback',
'help.title': 'Help',
'help.toggleHeteroTracing': 'Record Agent CLI Trace Logs',
diff --git a/apps/desktop/src/main/menus/impls/linux.ts b/apps/desktop/src/main/menus/impls/linux.ts
index c905a2849f4..9edba6a7fc0 100644
--- a/apps/desktop/src/main/menus/impls/linux.ts
+++ b/apps/desktop/src/main/menus/impls/linux.ts
@@ -211,6 +211,12 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
label: t('help.githubRepo'),
},
{ type: 'separator' },
+ {
+ click: () => {
+ this.app.browserManager.retrieveByIdentifier('processExplorer').show();
+ },
+ label: t('help.processExplorer'),
+ },
{
click: () => {
const heteroAgentPath = path.join(this.app.appStoragePath, HETERO_AGENT_DIR);
diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.ts
index 6a5b1c75092..a392c4b3164 100644
--- a/apps/desktop/src/main/menus/impls/macOS.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.ts
@@ -275,6 +275,12 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
label: t('help.reportIssue'),
},
{ type: 'separator' },
+ {
+ click: () => {
+ this.app.browserManager.retrieveByIdentifier('processExplorer').show();
+ },
+ label: t('help.processExplorer'),
+ },
{
click: () => {
const logsPath = app.getPath('logs');
diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.ts
index acbeccf6a79..bf3898dedd9 100644
--- a/apps/desktop/src/main/menus/impls/windows.ts
+++ b/apps/desktop/src/main/menus/impls/windows.ts
@@ -209,6 +209,12 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
label: t('help.githubRepo'),
},
{ type: 'separator' },
+ {
+ click: () => {
+ this.app.browserManager.retrieveByIdentifier('processExplorer').show();
+ },
+ label: t('help.processExplorer'),
+ },
{
click: () => {
const heteroAgentPath = path.join(this.app.appStoragePath, HETERO_AGENT_DIR);
diff --git a/apps/desktop/src/main/utils/__tests__/appMetrics.test.ts b/apps/desktop/src/main/utils/__tests__/appMetrics.test.ts
new file mode 100644
index 00000000000..03882bd437d
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/appMetrics.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const getAppMetrics = vi.fn(() => []);
+vi.mock('electron', () => ({ app: { getAppMetrics } }));
+
+const { getSharedAppMetrics } = await import('../appMetrics');
+
+describe('getSharedAppMetrics', () => {
+ it('reuses one sample for 1.5 s so cpu windows are not cut short', () => {
+ getSharedAppMetrics(10_000);
+ getSharedAppMetrics(11_499);
+ expect(getAppMetrics).toHaveBeenCalledTimes(1);
+ getSharedAppMetrics(11_500);
+ expect(getAppMetrics).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/utils/appMetrics.ts b/apps/desktop/src/main/utils/appMetrics.ts
new file mode 100644
index 00000000000..d119d8a0a98
--- /dev/null
+++ b/apps/desktop/src/main/utils/appMetrics.ts
@@ -0,0 +1,12 @@
+import { app, type ProcessMetric } from 'electron';
+
+const MAX_AGE = 1500;
+
+let cached: { at: number; metrics: ProcessMetric[] } | undefined;
+
+// percentCPUUsage is measured since the previous getAppMetrics call anywhere in the
+// process, so every reader must share one sample or each shortens the others' window.
+export const getSharedAppMetrics = (now = Date.now()) => {
+ if (!cached || now - cached.at >= MAX_AGE) cached = { at: now, metrics: app.getAppMetrics() };
+ return cached.metrics;
+};
diff --git a/apps/desktop/src/main/utils/idleRendererGc.ts b/apps/desktop/src/main/utils/idleRendererGc.ts
index 8d89f5a6ee1..02fc8c42a54 100644
--- a/apps/desktop/src/main/utils/idleRendererGc.ts
+++ b/apps/desktop/src/main/utils/idleRendererGc.ts
@@ -1,6 +1,7 @@
import type { WebContents } from 'electron';
-import { app, BrowserWindow } from 'electron';
+import { BrowserWindow } from 'electron';
+import { getSharedAppMetrics } from '@/utils/appMetrics';
import { createLogger } from '@/utils/logger';
const logger = createLogger('utils:idleRendererGc');
@@ -34,7 +35,7 @@ const defaultDeps: IdleRendererGcDeps = {
collect: collectRendererGarbage,
getFocusedWindow: () => BrowserWindow.getFocusedWindow(),
getResidentBytes: () =>
- new Map(app.getAppMetrics().map((m) => [m.pid, m.memory.workingSetSize * 1024])),
+ new Map(getSharedAppMetrics().map((m) => [m.pid, m.memory.workingSetSize * 1024])),
getWindows: () => BrowserWindow.getAllWindows(),
now: Date.now,
};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index 401fb7a7916..d40a0401dfa 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -1033,6 +1033,7 @@ export const dispatchHeteroAgent = async (
? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }
: await deviceGateway.dispatchAgentRun({
...heteroParams,
+ agentId: resolvedAgentId,
args: heteroExecArgs,
cwd: deviceCwd,
deviceId: dispatchDeviceId,
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index bd288188b40..603b8d61295 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -1826,6 +1826,7 @@ export class DeviceGateway {
}
async dispatchAgentRun(params: {
+ agentId?: string;
agentType: HeterogeneousAgentType;
assistantMessageId: string;
/** Resolved `lh hetero exec` wrapper args. */
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 1db39a4d037..6e29b97ba0c 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -130,6 +130,7 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
// script, a Makefile) inherits the scope too. The model's own `env`
// wins: it may be deliberately overriding the scope.
if (api.name === LocalSystemApiName.runCommand && typeof finalArgs?.command === 'string') {
+ finalArgs = { ...finalArgs, topicId: context.topicId, agentId: context.agentId };
const lhEnv = buildDeviceLhEnv(await getContentWorkspaceId());
if (lhEnv) finalArgs = { ...finalArgs, env: { ...lhEnv, ...finalArgs.env } };
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 11f6a042398..984613ef041 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -79,6 +79,22 @@
"audioPlayer.seek": "Seek audio",
"availableAgents": "Available Agents",
"backToBottom": "Jump to latest",
+ "backgroundActivity.alertDesc": "{{name}} is using {{memory}} of memory and {{cpu}} CPU.",
+ "backgroundActivity.cpu": "CPU",
+ "backgroundActivity.details": "View details",
+ "backgroundActivity.empty": "No background activity",
+ "backgroundActivity.emptyDesc": "Dev servers, shells, and agents started from conversations appear here while they run.",
+ "backgroundActivity.highUsage": "High resource usage",
+ "backgroundActivity.memory": "Memory",
+ "backgroundActivity.processCount_one": "{{count}} process",
+ "backgroundActivity.processCount_other": "{{count}} processes",
+ "backgroundActivity.retry": "Retry",
+ "backgroundActivity.shared": "Shared / unassigned",
+ "backgroundActivity.stop": "Stop",
+ "backgroundActivity.stopFailed": "Could not stop this activity. Try again.",
+ "backgroundActivity.title": "Background activity",
+ "backgroundActivity.topic": "Conversation",
+ "backgroundActivity.unavailable": "Resource data is unavailable. Displayed values may be out of date.",
"beforeUnload.confirmLeave": "A request is still running. Leave anyway?",
"builtinCopilot": "Built-in Copilot",
"chatList.expandMessage": "Expand Message",
@@ -1397,6 +1413,18 @@
"plus.search.offDesc": "",
"plus.title": "Add",
"plus.tooltip": "Add files, skills, and more context...",
+ "processExplorer.copyPid": "Copy PID",
+ "processExplorer.filter": "Filter",
+ "processExplorer.gpu": "GPU",
+ "processExplorer.live": "Live · updates every 2 s",
+ "processExplorer.main": "Main process",
+ "processExplorer.name": "Name",
+ "processExplorer.pid": "PID",
+ "processExplorer.processes": "Processes",
+ "processExplorer.title": "Process Explorer",
+ "processExplorer.updated": "Updated {{time}}",
+ "processExplorer.utility": "Utility",
+ "processExplorer.window": "Window",
"qoderInstallGuide.actions.openDocs": "Open Install Guide",
"qoderInstallGuide.actions.openSystemTools": "Open System Tools",
"qoderInstallGuide.afterInstall": "After installing, run `qodercli login`, then retry your message or click Re-detect in System Tools.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 24f301ab95c..9b9361efd42 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -79,6 +79,22 @@
"audioPlayer.seek": "跳转音频播放位置",
"availableAgents": "可用助理",
"backToBottom": "跳转到最新",
+ "backgroundActivity.alertDesc": "{{name}} 正在占用 {{memory}} 内存和 {{cpu}} CPU。",
+ "backgroundActivity.cpu": "CPU",
+ "backgroundActivity.details": "查看详情",
+ "backgroundActivity.empty": "暂无后台活动",
+ "backgroundActivity.emptyDesc": "会话中启动的开发服务器、终端命令和智能体运行时会显示在这里。",
+ "backgroundActivity.highUsage": "后台活动资源占用过高",
+ "backgroundActivity.memory": "内存",
+ "backgroundActivity.processCount_one": "{{count}} 个进程",
+ "backgroundActivity.processCount_other": "{{count}} 个进程",
+ "backgroundActivity.retry": "重试",
+ "backgroundActivity.shared": "共享 / 未归属",
+ "backgroundActivity.stop": "停止",
+ "backgroundActivity.stopFailed": "停止活动失败,请重试。",
+ "backgroundActivity.title": "后台活动",
+ "backgroundActivity.topic": "会话",
+ "backgroundActivity.unavailable": "暂时无法获取资源数据,已显示的数据可能已过期。",
"beforeUnload.confirmLeave": "你有正在生成中的请求,确定要离开吗?",
"builtinCopilot": "内置 Copilot",
"chatList.expandMessage": "展开消息",
@@ -1397,6 +1413,18 @@
"plus.search.offDesc": "",
"plus.title": "添加",
"plus.tooltip": "添加文件、技能和更多上下文...",
+ "processExplorer.copyPid": "复制 PID",
+ "processExplorer.filter": "筛选",
+ "processExplorer.gpu": "GPU",
+ "processExplorer.live": "实时 · 每 2 秒更新",
+ "processExplorer.main": "主进程",
+ "processExplorer.name": "名称",
+ "processExplorer.pid": "PID",
+ "processExplorer.processes": "进程数",
+ "processExplorer.title": "进程管理器",
+ "processExplorer.updated": "更新于 {{time}}",
+ "processExplorer.utility": "辅助进程",
+ "processExplorer.window": "窗口",
"qoderInstallGuide.actions.openDocs": "打开安装指南",
"qoderInstallGuide.actions.openSystemTools": "打开系统工具",
"qoderInstallGuide.afterInstall": "安装后,请运行 `qodercli login` 登录,然后重试消息或在系统工具中点击「重新检测」。",
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.ts
index 2b4526c8a85..554656c8310 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -63,9 +63,15 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
// `ctx.workingDirectory` is undefined whenever the agent has none
// configured — so an off-contract `cwd` must be dropped here rather than
// mistaken for a server-injected one.
- const output = await this.runtime.executeToolCall(apiName, params, {
- workingDirectory: ctx?.workingDirectory,
- });
+ const output = await this.runtime.executeToolCall(
+ apiName,
+ apiName === 'runCommand'
+ ? { ...params, topicId: ctx?.topicId ?? undefined, agentId: ctx?.agentId }
+ : params,
+ {
+ workingDirectory: ctx?.workingDirectory,
+ },
+ );
// apiEnum and the runtime dispatch cover the same tool set, so a null
// (unknown tool) here is a programming error, not a user-facing state.
if (!output) return this.errorResult(new Error(`Unknown local-system API: ${apiName}`));
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index f60f0ce8acb..c91e7ccb2c5 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -264,6 +264,7 @@ export class GatewayHttpClient {
}
async dispatchAgentRun(params: {
+ agentId?: string;
agentType: string;
assistantMessageId: string;
/** Resolved `lh hetero exec` wrapper args. */
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 2d168301035..bedd4979095 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -245,6 +245,7 @@ export interface RpcResponseMessage {
/** Server → Client: request the desktop to spawn `lh hetero exec`. */
export interface AgentRunRequestMessage {
+ agentId?: string;
agentType: string;
/**
* Resolved `lh hetero exec` wrapper args, e.g. `--model` / `--effort`.
diff --git a/packages/electron-client-ipc/src/types/devtools.ts b/packages/electron-client-ipc/src/types/devtools.ts
index 4c85dc90aa8..6c2e29e2597 100644
--- a/packages/electron-client-ipc/src/types/devtools.ts
+++ b/packages/electron-client-ipc/src/types/devtools.ts
@@ -8,6 +8,7 @@ export interface AppProcessRow {
name: string | null;
pid: number;
type: string;
+ windowTitle: string | null;
workingSetMB: number;
}
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index f4d26ca4006..193f6afce75 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -424,6 +424,7 @@ export interface OpenLocalFolderParams {
// Shell command types
export interface RunCommandParams {
+ agentId?: string;
command: string;
cwd?: string;
description?: string;
@@ -451,6 +452,7 @@ export interface RunCommandParams {
*/
sandboxNetwork?: boolean;
timeout?: number;
+ topicId?: string;
}
/**
diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts
index c815ed77f07..3e6255c9f6c 100644
--- a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts
+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts
@@ -1,7 +1,7 @@
import type { ChildProcess } from 'node:child_process';
-import { spawn } from 'node:child_process';
import path from 'node:path';
+import { spawnManaged } from '@lobechat/utils/managedProcess';
import { isRecord, pickString } from '@lobechat/utils/object';
import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
@@ -358,7 +358,7 @@ export class CodexAppServerClient {
);
}
- const child = spawn(spawnPlan.command, spawnPlan.args, {
+ const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: this.options.cwd,
detached: process.platform !== 'win32',
env: this.options.env,
diff --git a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
index 4f5156976a6..6cb48ebdb5e 100644
--- a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
+++ b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
@@ -2,6 +2,8 @@ import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
import { StringDecoder } from 'node:string_decoder';
+import { spawnManaged } from '@lobechat/utils/managedProcess';
+
import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
/**
@@ -117,7 +119,7 @@ export class RpcStdioClient {
const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);
if (this.closed) return;
- const child = spawn(spawnPlan.command, spawnPlan.args, {
+ const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: this.options.cwd,
detached: process.platform !== 'win32' && (this.options.detached ?? true),
env: this.options.env,
diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
index 164d7f5405e..80d8f07688d 100644
--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
@@ -1,6 +1,8 @@
import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
+import { spawnManaged } from '@lobechat/utils/managedProcess';
+
import { resolveCliSpawnPlan } from './cliSpawn';
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
@@ -103,7 +105,7 @@ export class AcpStdioClient {
const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);
if (this.closed) throw new Error('ACP stdio client is closed');
const detached = process.platform !== 'win32' && (this.options.detached ?? true);
- const child = spawn(spawnPlan.command, spawnPlan.args, {
+ const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: this.options.cwd,
detached,
env: this.options.env,
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
index 0496aa4d434..0f68a136249 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
@@ -8,7 +8,10 @@ const resolveCliSpawnPlanMock = vi.hoisted(() => vi.fn());
const spawnMock = vi.hoisted(() => vi.fn());
vi.mock('./cliSpawn', () => ({ resolveCliSpawnPlan: resolveCliSpawnPlanMock }));
-vi.mock('node:child_process', () => ({ spawn: spawnMock }));
+vi.mock('node:child_process', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ spawn: spawnMock,
+}));
describe('resolveClaudeSdkExecutablePath', () => {
beforeEach(() => {
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
index 166c4a4b281..fc24c64348a 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
@@ -1,4 +1,4 @@
-import { type ChildProcess, spawn } from 'node:child_process';
+import { type ChildProcess } from 'node:child_process';
import type {
Options as ClaudeAgentSdkOptions,
@@ -9,6 +9,7 @@ import type {
SpawnOptions as SdkSpawnOptions,
} from '@anthropic-ai/claude-agent-sdk';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { spawnManaged } from '@lobechat/utils/managedProcess';
import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';
import { resolveCliSpawnPlan } from './cliSpawn';
@@ -194,7 +195,7 @@ export const spawnClaudeCodeCliProcess = (
},
platform: NodeJS.Platform = process.platform,
): SdkSpawnedProcess => {
- const child: ChildProcess = spawn(options.command, options.args, {
+ const child: ChildProcess = spawnManaged(options.command, options.args, {
cwd: options.cwd,
detached: platform !== 'win32',
// The SDK types env as a plain string map; this repo augments ProcessEnv
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index 4e92a38dd8e..d6b8c073ac4 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -1,10 +1,10 @@
import type { ChildProcess } from 'node:child_process';
-import { spawn } from 'node:child_process';
import { platform } from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { spawnManaged } from '@lobechat/utils/managedProcess';
import type { AskUserBridge } from '../askUser/AskUserBridge';
import { resolveHeterogeneousAgentCommand } from '../config';
@@ -708,7 +708,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const cliSpawnPlan = await resolveCliSpawnPlan(command, args);
const detached = platform() !== 'win32' && (options.detached ?? true);
- const proc = spawn(cliSpawnPlan.command, cliSpawnPlan.args, {
+ const proc = spawnManaged(cliSpawnPlan.command, cliSpawnPlan.args, {
cwd,
detached,
env: childEnv,
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index 45bb47b1ccb..e5de5690c8b 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -30,6 +30,7 @@ export interface RunCommandOptions {
onSandboxUnavailable?: (error: Error) => void;
processManager: ShellProcessManager;
sandboxPolicy?: SandboxPolicy;
+ spawnProcess?: typeof spawn;
}
/**
@@ -57,7 +58,13 @@ export async function runCommand(
run_in_background,
timeout = DEFAULT_OBSERVATION_TIMEOUT_MS,
}: RunCommandParams,
- { processManager, logger, onSandboxUnavailable, sandboxPolicy }: RunCommandOptions,
+ {
+ processManager,
+ logger,
+ onSandboxUnavailable,
+ sandboxPolicy,
+ spawnProcess = spawn,
+ }: RunCommandOptions,
): Promise<RunCommandResult> {
if (!command) {
return { error: 'command is required', success: false };
@@ -121,7 +128,7 @@ export async function runCommand(
const shellId = processManager.createShellId();
const shellOutputFiles = processManager.createOutputFiles(shellId);
outputFiles = shellOutputFiles;
- const childProcess = spawn(launchCommand.cmd, launchCommand.args, {
+ const childProcess = spawnProcess(launchCommand.cmd, launchCommand.args, {
cwd,
detached: process.platform !== 'win32',
env: launchEnv,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 8497add9a43..d508d2b7bf1 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1,4 +1,35 @@
export default {
+ 'backgroundActivity.alertDesc': '{{name}} is using {{memory}} of memory and {{cpu}} CPU.',
+ 'backgroundActivity.cpu': 'CPU',
+ 'backgroundActivity.details': 'View details',
+ 'backgroundActivity.empty': 'No background activity',
+ 'backgroundActivity.emptyDesc':
+ 'Dev servers, shells, and agents started from conversations appear here while they run.',
+ 'backgroundActivity.highUsage': 'High resource usage',
+ 'backgroundActivity.memory': 'Memory',
+ 'backgroundActivity.processCount_one': '{{count}} process',
+ 'backgroundActivity.processCount_other': '{{count}} processes',
+ 'backgroundActivity.retry': 'Retry',
+ 'backgroundActivity.shared': 'Shared / unassigned',
+ 'backgroundActivity.stop': 'Stop',
+ 'backgroundActivity.stopFailed': 'Could not stop this activity. Try again.',
+ 'backgroundActivity.title': 'Background activity',
+ 'backgroundActivity.topic': 'Conversation',
+ 'backgroundActivity.unavailable':
+ 'Resource data is unavailable. Displayed values may be out of date.',
+ 'processExplorer.copyPid': 'Copy PID',
+ 'processExplorer.filter': 'Filter',
+ 'processExplorer.live': 'Live · updates every 2 s',
+ 'processExplorer.name': 'Name',
+ 'processExplorer.processes': 'Processes',
+ 'processExplorer.gpu': 'GPU',
+ 'processExplorer.main': 'Main process',
+ 'processExplorer.pid': 'PID',
+ 'processExplorer.title': 'Process Explorer',
+ 'processExplorer.updated': 'Updated {{time}}',
+ 'processExplorer.utility': 'Utility',
+ 'processExplorer.window': 'Window',
+
'response.contentSafetyNotice':
'This reply was limited for content safety reasons. If this happens often, you may temporarily lose access to this model.',
'goalExperiment.continuedFrom': 'Continued exploration',
diff --git a/packages/utils/src/managedProcess.polling.test.ts b/packages/utils/src/managedProcess.polling.test.ts
new file mode 100644
index 00000000000..c31b3fff961
--- /dev/null
+++ b/packages/utils/src/managedProcess.polling.test.ts
@@ -0,0 +1,91 @@
+// @vitest-environment node
+import type * as ChildProcessModule from 'node:child_process';
+import type { ChildProcess } from 'node:child_process';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ManagedProcessRegistry } from './managedProcess';
+
+const { enumerate } = vi.hoisted(() => ({ enumerate: vi.fn() }));
+vi.mock('node:child_process', async (importOriginal) => {
+ const { promisify } = await import('node:util');
+ return {
+ ...(await importOriginal<typeof ChildProcessModule>()),
+ execFile: Object.assign(vi.fn(), { [promisify.custom]: enumerate }),
+ };
+});
+vi.mock('node:fs/promises', () => ({ readdir: async () => [] }));
+
+const platform = process.platform;
+beforeEach(() => {
+ vi.useFakeTimers();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ enumerate.mockReset().mockResolvedValue({ stdout: '[]' });
+});
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ Object.defineProperty(process, 'platform', { value: platform });
+});
+
+const start = () => {
+ const registry = new ManagedProcessRegistry();
+ registry.environment({ topicId: 'topic' });
+ const child = { pid: 123, exitCode: 0 as number | null, signalCode: null };
+ registry.register(child as ChildProcess, false, { topicId: 'topic' });
+ return { registry, child };
+};
+
+describe('Windows process polling', () => {
+ it('bounds idle discovery scans and stops when the reuse window expires', async () => {
+ start();
+ await vi.advanceTimersByTimeAsync(900000);
+ expect(enumerate.mock.calls.length).toBeLessThanOrEqual(31);
+ expect(enumerate).toHaveBeenCalledWith('powershell.exe', expect.any(Array), expect.any(Object));
+ await vi.advanceTimersByTimeAsync(30000);
+ const scans = enumerate.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(120000);
+ expect(enumerate).toHaveBeenCalledTimes(scans);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('backs off failures and expires unused scopes without successful enumeration', async () => {
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ enumerate.mockRejectedValue(new Error('CIM unavailable'));
+ start();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(enumerate).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(enumerate).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(enumerate).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1800000);
+ expect(enumerate.mock.calls.length).toBeLessThan(22);
+ expect(errors).toHaveBeenCalledTimes(enumerate.mock.calls.length);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('resumes fast tracking for new work and allows immediate explicit snapshots', async () => {
+ const { registry, child } = start();
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+ await registry.snapshot();
+ expect(enumerate).toHaveBeenCalledTimes(2);
+ child.exitCode = null;
+ registry.register(child as ChildProcess, false, { topicId: 'topic' });
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(enumerate).toHaveBeenCalledTimes(5);
+ });
+
+ it('resets failure backoff after recovery', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { child } = start();
+ child.exitCode = null;
+ enumerate.mockRejectedValueOnce(new Error('CIM unavailable'));
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(enumerate).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(enumerate).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/packages/utils/src/managedProcess.test.ts b/packages/utils/src/managedProcess.test.ts
new file mode 100644
index 00000000000..58768afb18a
--- /dev/null
+++ b/packages/utils/src/managedProcess.test.ts
@@ -0,0 +1,176 @@
+// @vitest-environment node
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ManagedProcessRegistry } from './managedProcess';
+
+const alive = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+const cleanup: Array<() => Promise<unknown>> = [];
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((fn) => fn()));
+});
+
+describe.skipIf(process.platform === 'win32')('managed process shutdown', () => {
+ const start = async (code: string) => {
+ const registry = new ManagedProcessRegistry();
+ const child = spawn(process.execPath, ['-e', code], { detached: true, stdio: 'pipe' });
+ registry.register(child, true);
+ cleanup.push(async () => {
+ try {
+ process.kill(-child.pid!, 'SIGKILL');
+ } catch {
+ /* already gone */
+ }
+ await registry.shutdown(0);
+ });
+ await once(child.stdout!, 'data');
+ return { child, registry };
+ };
+
+ it('waits for a real process ignoring TERM, escalates, and refuses late launches', async () => {
+ const { child, registry } = await start(
+ `process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000);`,
+ );
+ const closing = registry.shutdown(80);
+ expect(registry.shutdown()).toBe(closing);
+ expect(() => registry.assertCanSpawn()).toThrow('shutting down');
+ await closing;
+ expect(alive(child.pid!)).toBe(false);
+ expect(child.signalCode).toBe('SIGKILL');
+ });
+
+ it('reaps a background child even after the shell leader has exited', async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'managed-process-'));
+ cleanup.push(() => rm(directory, { recursive: true, force: true }));
+ const pidFile = path.join(directory, 'pid');
+ const code = `const {spawn} = require('child_process'); const c = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {stdio: 'ignore'}); require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); c.unref(); console.log('ready');`;
+ const { child, registry } = await start(code);
+ if (child.exitCode === null) await once(child, 'exit');
+ const pid = Number(await readFile(pidFile, 'utf8'));
+ expect(alive(pid)).toBe(true);
+ await registry.shutdown(80);
+ expect(alive(pid)).toBe(false);
+ });
+
+ it('discovers a child in a different process group without killing an unrelated process', async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'managed-process-'));
+ cleanup.push(() => rm(directory, { recursive: true, force: true }));
+ const pidFile = path.join(directory, 'pid');
+ const unrelated = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
+ cleanup.push(async () => {
+ unrelated.kill('SIGKILL');
+ });
+ const code = `const {spawn} = require('child_process'); const c = spawn(process.execPath, ['-e', "process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000)"], {detached: true, stdio: ['ignore', 'pipe', 'ignore']}); c.stdout.once('data', () => { require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); console.log('ready'); }); setInterval(() => {}, 1000);`;
+ const { registry } = await start(code);
+ const pid = Number(await readFile(pidFile, 'utf8'));
+ cleanup.push(async () => {
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch {
+ /* gone */
+ }
+ });
+ await registry.shutdown(80);
+ expect(alive(pid)).toBe(false);
+ expect(alive(unrelated.pid!)).toBe(true);
+ });
+ it('reports owned memory and stops only the selected tree', async () => {
+ const { child, registry } = await start("console.log('ready'); setInterval(() => {}, 1000)");
+ const unrelated = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
+ cleanup.push(async () => {
+ unrelated.kill('SIGKILL');
+ });
+ registry.register(child, true, { topicId: 'topic-one', label: 'Dev server' });
+ const snapshot = await registry.snapshot();
+ const row = snapshot.processes.find((item) => item.pid === child.pid)!;
+ expect(row.topicId).toBe('topic-one');
+ expect(row.memoryMB).toBeGreaterThan(0);
+ const rolledBack = Date.now() - 1000;
+ vi.spyOn(Date, 'now').mockReturnValue(rolledBack);
+ expect((await registry.snapshot()).sampledAt).toBe(rolledBack);
+ vi.restoreAllMocks();
+ expect(snapshot.processes.some((item) => item.pid === unrelated.pid)).toBe(false);
+ await expect(registry.stop('stale-identity')).rejects.toThrow('already exited');
+ expect(alive(child.pid!)).toBe(true);
+ await registry.stop(row.rootId);
+ expect(alive(child.pid!)).toBe(false);
+ expect(alive(unrelated.pid!)).toBe(true);
+ });
+ it('adopts a detached browser daemon from its own namespace and reaps it after idle', async () => {
+ const registry = new ManagedProcessRegistry();
+ const env = registry.environment({ topicId: 'browser-topic' });
+ expect(registry.environment({ topicId: 'browser-topic' }).AGENT_BROWSER_NAMESPACE).toBe(
+ env.AGENT_BROWSER_NAMESPACE,
+ );
+ expect(registry.environment({ topicId: 'other-topic' }).AGENT_BROWSER_NAMESPACE).not.toBe(
+ env.AGENT_BROWSER_NAMESPACE,
+ );
+ const daemon = spawn(
+ process.execPath,
+ [
+ '-e',
+ "process.title='agent-browser-regression'; console.log('ready'); setInterval(()=>{},1000)",
+ ],
+ { detached: true, stdio: 'pipe' },
+ );
+ cleanup.push(async () => {
+ vi.restoreAllMocks();
+ daemon.kill('SIGKILL');
+ await registry.shutdown(0);
+ await rm(env.AGENT_BROWSER_SOCKET_DIR, { recursive: true, force: true });
+ });
+ await once(daemon.stdout!, 'data');
+ const directory = path.join(
+ env.AGENT_BROWSER_SOCKET_DIR,
+ 'namespaces',
+ env.AGENT_BROWSER_NAMESPACE,
+ 'run',
+ );
+ await mkdir(directory, { recursive: true });
+ await writeFile(path.join(directory, 'default.pid'), String(daemon.pid));
+ const snapshot = await registry.snapshot();
+ expect(snapshot.processes.find((row) => row.pid === daemon.pid)).toMatchObject({
+ topicId: 'browser-topic',
+ label: 'Agent Browser · default',
+ });
+ const now = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(now + 901000);
+ await registry.snapshot();
+ await vi.waitFor(() => expect(alive(daemon.pid!)).toBe(false), { timeout: 3000 });
+ vi.restoreAllMocks();
+ });
+ it('owns processes launched from a separately evaluated lazy module', async () => {
+ const eager = await import('./managedProcess');
+ eager.enableManagedProcesses();
+ vi.resetModules();
+ const lazy = await import('./managedProcess');
+ const child = lazy.spawnManaged(
+ process.execPath,
+ ['-e', "console.log('ready'); setInterval(() => {}, 1000)"],
+ { detached: true, stdio: 'pipe' },
+ );
+ cleanup.push(async () => {
+ try {
+ process.kill(-child.pid!, 'SIGKILL');
+ } catch {
+ /* gone */
+ }
+ });
+ await once(child.stdout!, 'data');
+ await eager.shutdownManagedProcesses();
+ expect(alive(child.pid!)).toBe(false);
+ expect(() => lazy.spawnManaged(process.execPath, ['-e', ''])).toThrow('shutting down');
+ });
+});
diff --git a/packages/utils/src/managedProcess.ts b/packages/utils/src/managedProcess.ts
new file mode 100644
index 00000000000..6e153bb44f7
--- /dev/null
+++ b/packages/utils/src/managedProcess.ts
@@ -0,0 +1,516 @@
+import type { ChildProcess, SpawnOptions } from 'node:child_process';
+import { execFile, spawn } from 'node:child_process';
+import { createHash, randomUUID } from 'node:crypto';
+import { readdir, readFile, stat } from 'node:fs/promises';
+import { tmpdir, totalmem } from 'node:os';
+import path from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { promisify } from 'node:util';
+
+import debug from 'debug';
+
+const log = debug('lobe-desktop:processes');
+const exec = promisify(execFile);
+
+export interface ProcessOwner {
+ agentId?: string;
+ label?: string;
+ topicId?: string;
+}
+
+export interface ManagedProcessInfo extends ProcessOwner {
+ cpuPercent: number | null;
+ id: string;
+ memoryMB: number;
+ name: string;
+ pid: number;
+ ppid: number;
+ rootId: string;
+}
+
+export interface ManagedProcessSnapshot {
+ processes: ManagedProcessInfo[];
+ sampledAt: number;
+ totalMemoryMB: number;
+}
+
+interface ProcessIdentity {
+ cpuTime: number;
+ group: number;
+ memoryMB: number;
+ name: string;
+ pid: number;
+ ppid: number;
+ started: string;
+}
+
+interface RootProcess {
+ child: Pick<ChildProcess, 'exitCode' | 'signalCode'>;
+ group: boolean;
+ owner: ProcessOwner;
+}
+
+const exists = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false;
+ throw error;
+ }
+};
+
+const signal = (pid: number, value: NodeJS.Signals) => {
+ try {
+ process.kill(pid, value);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
+ }
+};
+
+const parseCpuTime = (value: string) => {
+ const [days, clock] = value.includes('-') ? value.split('-') : ['0', value];
+ return Number(days) * 86400 + clock.split(':').reduce((sum, part) => sum * 60 + Number(part), 0);
+};
+
+const readProcesses = async (): Promise<ProcessIdentity[]> => {
+ if (process.platform === 'win32') {
+ const { stdout } = await exec(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CreationDate,WorkingSetSize,KernelModeTime,UserModeTime,Name | ConvertTo-Json -Compress',
+ ],
+ { timeout: 2000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
+ );
+ const rows = JSON.parse(stdout) as Array<{
+ ProcessId: number;
+ ParentProcessId: number;
+ CreationDate: string;
+ WorkingSetSize: number;
+ KernelModeTime: number;
+ UserModeTime: number;
+ Name: string;
+ }>;
+ return (Array.isArray(rows) ? rows : [rows]).map((row) => ({
+ name: row.Name,
+ memoryMB: Number(row.WorkingSetSize) / 1024 / 1024,
+ cpuTime: (Number(row.KernelModeTime) + Number(row.UserModeTime)) / 10000000,
+ pid: row.ProcessId,
+ ppid: row.ParentProcessId,
+ group: 0,
+ started: row.CreationDate,
+ }));
+ }
+ const { stdout } = await exec('ps', ['-axo', 'pid=,ppid=,pgid=,stat=,rss=,time=,lstart=,comm='], {
+ timeout: 2000,
+ maxBuffer: 8 * 1024 * 1024,
+ env: { ...process.env, LC_ALL: 'C' },
+ });
+ return stdout
+ .trim()
+ .split('\n')
+ .flatMap((line) => {
+ const columns = line.trim().split(/\s+/);
+ if (columns.length < 12 || columns[3].startsWith('Z')) return [];
+ return [
+ {
+ pid: Number(columns[0]),
+ ppid: Number(columns[1]),
+ group: Number(columns[2]),
+ memoryMB: Number(columns[4]) / 1024,
+ cpuTime: parseCpuTime(columns[5]),
+ started: columns.slice(6, 11).join(' '),
+ name: path.basename(columns.slice(11).join(' ')),
+ },
+ ];
+ });
+};
+
+/** Host-owned process lifetime. No Electron dependency; CLI/server hosts opt in separately. */
+export class ManagedProcessRegistry {
+ private roots = new Map<number, RootProcess>();
+ private descendants = new Map<number, ProcessIdentity>();
+ private timer?: ReturnType<typeof setInterval>;
+ private nextPollAt = 0;
+ private retryDelay = 0;
+ private sampling?: Promise<void>;
+ private closing?: Promise<void>;
+ private stopping = false;
+ private owners = new Map<number, { rootId: string; owner: ProcessOwner }>();
+ private rows: ManagedProcessInfo[] = [];
+ private sampledAt = 0;
+ private browserScopes = new Map<string, ProcessOwner>();
+ private browserActivity = new Map<string, number>();
+ private idleStopping = new Set<string>();
+ private browserBase = path.join(
+ process.platform === 'darwin' ? '/tmp' : tmpdir(),
+ `lb-${randomUUID().slice(0, 12)}`,
+ );
+
+ environment(owner: ProcessOwner, browserSession = 'default'): Record<string, string> {
+ this.assertCanSpawn();
+ const namespace = createHash('sha256')
+ .update(owner.topicId ?? owner.agentId ?? 'shared')
+ .digest('hex')
+ .slice(0, 12);
+ this.browserScopes.set(namespace, owner);
+ this.browserActivity.set(namespace, Date.now());
+ return {
+ LOBEHUB_PROCESS_TOPIC: owner.topicId ?? '',
+ LOBEHUB_PROCESS_AGENT: owner.agentId ?? '',
+ LOBEHUB_PROCESS_LABEL: owner.label ?? '',
+ AGENT_BROWSER_SOCKET_DIR: this.browserBase,
+ AGENT_BROWSER_NAMESPACE: namespace,
+ AGENT_BROWSER_SESSION: browserSession,
+ AGENT_BROWSER_IDLE_TIMEOUT_MS: '900000',
+ };
+ }
+
+ async snapshot(): Promise<ManagedProcessSnapshot> {
+ // Share a recent sample across windows instead of measuring tiny CPU intervals.
+ const age = Date.now() - this.sampledAt;
+ if (!this.sampledAt || age < 0 || age >= 500) await this.sample();
+ return {
+ processes: this.rows,
+ sampledAt: this.sampledAt,
+ totalMemoryMB: totalmem() / 1024 / 1024,
+ };
+ }
+
+ async stop(id: string) {
+ await this.sample();
+ const selected = this.rows.find((row) => row.id === id || row.rootId === id);
+ if (!selected) throw new Error('Process has already exited');
+ const rootId = selected.rootId;
+ // Keep start identities: a recycled PID must never become a stop target.
+ const targets = new Map(
+ this.rows.filter((row) => row.rootId === rootId).map((row) => [row.pid, row.id]),
+ );
+ const terminate = async (value: NodeJS.Signals) => {
+ await this.sample();
+ for (const row of this.rows) {
+ if (row.rootId !== rootId || (targets.has(row.pid) && targets.get(row.pid) !== row.id))
+ continue;
+ targets.set(row.pid, row.id);
+ if (process.platform === 'win32') {
+ try {
+ await exec('taskkill', ['/pid', String(row.pid), '/T', '/F'], {
+ timeout: 2000,
+ windowsHide: true,
+ });
+ } catch (error) {
+ if (exists(row.pid)) throw error;
+ }
+ } else signal(row.pid, value);
+ }
+ };
+ await terminate('SIGTERM');
+ await delay(1000);
+ await terminate('SIGKILL');
+ const deadline = Date.now() + 2000;
+ do {
+ await this.sample();
+ if (!this.rows.some((row) => row.rootId === rootId)) return;
+ await delay(50);
+ } while (Date.now() < deadline);
+ throw new Error('Activity remains after SIGKILL');
+ }
+
+ private async discoverBrowsers(processes: ProcessIdentity[]) {
+ for (const [namespace, owner] of this.browserScopes) {
+ const directory = path.join(this.browserBase, 'namespaces', namespace, 'run');
+ let files: string[];
+ try {
+ files = await readdir(directory);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ for (const file of files.filter((name) => name.endsWith('.pid'))) {
+ let pid: number;
+ let modified: number;
+ try {
+ pid = Number((await readFile(path.join(directory, file), 'utf8')).trim());
+ modified = (await stat(path.join(directory, file))).mtimeMs;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ const row = processes.find(
+ (item) => item.pid === pid && item.name.includes('agent-browser'),
+ );
+ if (!row || this.descendants.has(pid)) continue;
+ // Reject a stale PID file pointing at a later, unrelated browser daemon.
+ if (Date.parse(row.started) > modified + 1000) continue;
+ this.descendants.set(pid, row);
+ this.owners.set(pid, {
+ rootId: `${pid}:${row.started}`,
+ owner: { ...owner, label: `Agent Browser · ${file.slice(0, -4)}` },
+ });
+ }
+ }
+ }
+
+ assertCanSpawn() {
+ if (this.stopping) throw new Error('Application is shutting down; cannot start a process');
+ }
+
+ register(child: ChildProcess, detached: boolean, owner: ProcessOwner = {}) {
+ if (!child.pid) return;
+ log('register pid=%d detached=%s', child.pid, detached);
+ if (this.roots.get(child.pid)?.child !== child) this.owners.delete(child.pid);
+ this.roots.set(child.pid, { child, group: process.platform !== 'win32' && detached, owner });
+ this.nextPollAt = 0;
+ if (!this.timer) {
+ // ponytail: polling can miss a daemon that detaches between samples; strict
+ // containment needs a platform supervisor/job, not a faster polling loop.
+ this.timer = setInterval(() => {
+ if (this.sampling || Date.now() < this.nextPollAt) return;
+ void this.sample()
+ .then(() => {
+ this.retryDelay = 0;
+ this.nextPollAt =
+ Date.now() + (this.roots.size || this.descendants.size ? 1000 : 30000);
+ })
+ .catch((error) => {
+ this.retryDelay = Math.min(this.retryDelay ? this.retryDelay * 2 : 2000, 60000);
+ this.nextPollAt = Date.now() + this.retryDelay;
+ console.error('Process tracking failed:', error);
+ });
+ }, 1000);
+ this.timer.unref();
+ }
+ }
+
+ private sample(): Promise<void> {
+ this.sampling ??= this.collect().finally(() => {
+ this.sampling = undefined;
+ });
+ return this.sampling;
+ }
+
+ private async collect() {
+ const now = Date.now();
+ // Exited non-group roots and unused scopes can expire even if enumeration fails.
+ for (const [pid, root] of this.roots)
+ if (!root.group && (root.child.exitCode !== null || root.child.signalCode !== null))
+ this.roots.delete(pid);
+ // Old system agent-browser versions do not implement idle-timeout. Reap only
+ // once all commands for this topic have ended and the reuse window expires.
+ if (!this.stopping)
+ for (const [namespace, owner] of this.browserScopes) {
+ const active = [...this.roots.values()].some(
+ (root) =>
+ root.owner.topicId === owner.topicId &&
+ root.owner.agentId === owner.agentId &&
+ root.child.exitCode === null &&
+ root.child.signalCode === null,
+ );
+ if (active) this.browserActivity.set(namespace, now);
+ if (now - (this.browserActivity.get(namespace) ?? now) < 900000) continue;
+ const browsers = this.rows.filter(
+ (item) =>
+ item.label?.startsWith('Agent Browser ·') &&
+ item.topicId === owner.topicId &&
+ item.agentId === owner.agentId,
+ );
+ if (!browsers.length) {
+ this.browserScopes.delete(namespace);
+ this.browserActivity.delete(namespace);
+ }
+ for (const row of browsers) {
+ if (this.idleStopping.has(row.rootId)) continue;
+ this.idleStopping.add(row.rootId);
+ setTimeout(() => {
+ void this.stop(row.rootId)
+ .catch((error) => console.error('Browser idle cleanup failed:', error))
+ .finally(() => this.idleStopping.delete(row.rootId));
+ }, 0).unref();
+ }
+ }
+ if (!this.roots.size && !this.descendants.size && !this.browserScopes.size) {
+ clearInterval(this.timer);
+ this.timer = undefined;
+ return;
+ }
+ const roots = [...this.roots];
+ const processes = await readProcesses();
+ await this.discoverBrowsers(processes);
+ const owned = new Set<number>();
+ const prior = this.descendants;
+ const assign = (row: ProcessIdentity, pid: number, owner: ProcessOwner) => {
+ const root = processes.find((item) => item.pid === pid);
+ const rootId = this.owners.get(pid)?.rootId ?? `${pid}:${root?.started ?? row.started}`;
+ this.owners.set(row.pid, { rootId, owner });
+ owned.add(row.pid);
+ };
+ for (const [pid, root] of roots) {
+ if (root.group) {
+ if (
+ !exists(-pid) ||
+ ((root.child.exitCode !== null || root.child.signalCode !== null) &&
+ (!processes.some((row) => row.group === pid) ||
+ processes.some((row) => row.pid === pid)))
+ ) {
+ this.roots.delete(pid);
+ continue;
+ }
+ for (const row of processes) if (row.group === pid) assign(row, pid, root.owner);
+ } else if (root.child.exitCode === null && root.child.signalCode === null) {
+ const row = processes.find((item) => item.pid === pid);
+ if (row) assign(row, pid, root.owner);
+ } else {
+ this.roots.delete(pid);
+ }
+ }
+ for (const row of processes) {
+ if (this.descendants.get(row.pid)?.started === row.started) owned.add(row.pid);
+ }
+ // A single process-table snapshot, expanded to a fixed point for arbitrary depth.
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const row of processes) {
+ if (!owned.has(row.pid) && owned.has(row.ppid)) {
+ owned.add(row.pid);
+ const parent = this.owners.get(row.ppid);
+ if (parent) this.owners.set(row.pid, parent);
+ changed = true;
+ }
+ }
+ }
+ this.descendants = new Map(
+ processes.filter((row) => owned.has(row.pid)).map((row) => [row.pid, row]),
+ );
+ this.rows = [...this.descendants.values()].map((row) => {
+ const previous = prior.get(row.pid);
+ const attribution = this.owners.get(row.pid);
+ return {
+ ...attribution?.owner,
+ id: `${row.pid}:${row.started}`,
+ rootId: attribution?.rootId ?? `${row.pid}:${row.started}`,
+ pid: row.pid,
+ ppid: row.ppid,
+ name: row.name,
+ memoryMB: row.memoryMB,
+ cpuPercent:
+ previous?.started === row.started && this.sampledAt && now > this.sampledAt
+ ? Math.max(0, ((row.cpuTime - previous.cpuTime) * 100000) / (now - this.sampledAt))
+ : null,
+ };
+ });
+ this.sampledAt = now;
+ for (const pid of this.owners.keys()) if (!this.descendants.has(pid)) this.owners.delete(pid);
+ if (!this.roots.size && !this.descendants.size && !this.browserScopes.size) {
+ clearInterval(this.timer);
+ this.timer = undefined;
+ }
+ }
+
+ private async terminate(value: NodeJS.Signals) {
+ let sampled = true;
+ try {
+ await this.sample();
+ } catch (error) {
+ sampled = false;
+ console.error('Cannot enumerate descendants; terminating registered roots:', error);
+ }
+ if (process.platform === 'win32') {
+ const targets = sampled
+ ? [...this.descendants.keys()]
+ : [...this.roots]
+ .filter(([, root]) => root.child.exitCode === null && root.child.signalCode === null)
+ .map(([pid]) => pid);
+ await Promise.all(
+ targets.map(async (pid) => {
+ try {
+ await exec('taskkill', ['/pid', String(pid), '/T', '/F'], {
+ timeout: 2000,
+ windowsHide: true,
+ });
+ } catch (error) {
+ if (exists(pid)) throw error;
+ }
+ }),
+ );
+ return;
+ }
+ for (const [pid, root] of this.roots) if (root.group) signal(-pid, value);
+ if (sampled) for (const pid of this.descendants.keys()) signal(pid, value);
+ }
+
+ shutdown(graceMs = 2000): Promise<void> {
+ log('shutdown roots=%o descendants=%o', [...this.roots.keys()], [...this.descendants.keys()]);
+ this.stopping = true;
+ this.closing ??= this.close(graceMs);
+ return this.closing;
+ }
+
+ private async close(graceMs: number) {
+ clearInterval(this.timer);
+ this.timer = undefined;
+ try {
+ try {
+ await this.terminate('SIGTERM');
+ const deadline = Date.now() + graceMs;
+ while ((this.roots.size || this.descendants.size) && Date.now() < deadline) {
+ await delay(50);
+ await this.sample();
+ }
+ } catch (error) {
+ console.error('Graceful process shutdown failed:', error);
+ }
+ await this.terminate('SIGKILL');
+ const killDeadline = Date.now() + 2000;
+ while ((this.roots.size || this.descendants.size) && Date.now() < killDeadline) {
+ await delay(50);
+ await this.sample();
+ }
+ if (this.roots.size || this.descendants.size)
+ throw new Error('Managed processes remain after SIGKILL');
+ } finally {
+ clearInterval(this.timer);
+ }
+ }
+}
+
+// Electron's eager and deferred CJS graphs can evaluate this module separately.
+// The owner must belong to the host process, not to a particular module instance.
+const registryKey = Symbol.for('lobehub.managedProcesses');
+const host = globalThis as typeof globalThis & { [registryKey]?: ManagedProcessRegistry };
+
+export const enableManagedProcesses = () => (host[registryKey] ??= new ManagedProcessRegistry());
+export const managedProcessEnvironment = (owner: ProcessOwner, browserSession?: string) =>
+ host[registryKey]?.environment(owner, browserSession) ?? {};
+export const getManagedProcesses = () => enableManagedProcesses().snapshot();
+export const stopManagedProcess = (id: string) => enableManagedProcesses().stop(id);
+export const shutdownManagedProcesses = () => host[registryKey]?.shutdown() ?? Promise.resolve();
+
+/** Preserve Node's spawn overloads, including typed stdio. Cleanup helpers use raw spawn. */
+export const spawnManaged: typeof spawn = ((...args: Parameters<typeof spawn>) => {
+ const registry = host[registryKey];
+ log('spawn managed=%s', !!registry);
+ registry?.assertCanSpawn();
+ const child = spawn(...args);
+ const options = (Array.isArray(args[1]) ? args[2] : (args[1] ?? args[2])) as
+ SpawnOptions | undefined;
+ registry?.register(child, options?.detached ?? false, {
+ topicId: options?.env?.LOBEHUB_PROCESS_TOPIC || undefined,
+ agentId: options?.env?.LOBEHUB_PROCESS_AGENT || undefined,
+ label: options?.env?.LOBEHUB_PROCESS_LABEL || path.basename(args[0]),
+ });
+ return child;
+}) as typeof spawn;
+
+/** Keep ownership even when a sandbox intentionally filters the child environment. */
+export const spawnManagedFor = (owner: ProcessOwner): typeof spawn =>
+ ((...args: Parameters<typeof spawn>) => {
+ const child = spawnManaged(...args);
+ const options = (Array.isArray(args[1]) ? args[2] : (args[1] ?? args[2])) as
+ SpawnOptions | undefined;
+ host[registryKey]?.register(child, options?.detached ?? false, owner);
+ return child;
+ }) as typeof spawn;
diff --git a/src/features/BackgroundActivity/ActivityTable.tsx b/src/features/BackgroundActivity/ActivityTable.tsx
new file mode 100644
index 00000000000..bfc11e18c5e
--- /dev/null
+++ b/src/features/BackgroundActivity/ActivityTable.tsx
@@ -0,0 +1,313 @@
+import { Empty, Flexbox, Icon } from '@lobehub/ui';
+import { Button, Skeleton } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ ChevronRightIcon,
+ CpuIcon,
+ MessageSquareIcon,
+ RefreshCwIcon,
+ TriangleAlertIcon,
+} from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+import {
+ type Activity,
+ formatCpu,
+ formatMemory,
+ processTree,
+ refreshActivities,
+ useActivities,
+} from './state';
+import StopButton from './StopButton';
+
+export const topicName = (id?: string) => {
+ if (!id) return undefined;
+ const state = useChatStore.getState();
+ return (
+ state.topicDetailMap[id]?.title ??
+ Object.values(state.topicDataMap)
+ .flatMap((data) => data.items)
+ .find((topic) => topic.id === id)?.title
+ );
+};
+
+const GRID = '16px minmax(0, 1fr) 88px 72px 56px 28px';
+
+const tableStyles = createStaticStyles(({ css }) => ({
+ alert: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 12px;
+ color: ${cssVar.colorError};
+
+ background: ${cssVar.colorErrorBg};
+ `,
+ chevron: css`
+ color: ${cssVar.colorTextQuaternary};
+ transition: transform 0.15s ease;
+ `,
+ chevronOpen: css`
+ transform: rotate(90deg);
+ `,
+ critical: css`
+ color: ${cssVar.colorError};
+ `,
+ group: css`
+ position: sticky;
+ z-index: 1;
+ inset-block-start: 0;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ height: 30px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorBgLayout};
+ `,
+ head: css`
+ display: grid;
+ gap: 8px;
+ align-items: center;
+
+ height: 28px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ headLabel: css`
+ font-size: 11px;
+ font-weight: 600;
+ color: ${cssVar.colorTextTertiary};
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ `,
+ headNum: css`
+ text-align: end;
+ `,
+ label: css`
+ overflow: hidden;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+
+ font-size: 13px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ num: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+ text-align: end;
+ `,
+ proc: css`
+ display: grid;
+ gap: 8px;
+ align-items: center;
+
+ height: 26px;
+ padding-inline: 12px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11.5px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ procName: css`
+ overflow: hidden;
+ min-width: 0;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ row: css`
+ cursor: pointer;
+
+ display: grid;
+ gap: 8px;
+ align-items: center;
+
+ height: 36px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ selected: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ stale: css`
+ opacity: 0.55;
+ `,
+ warning: css`
+ color: ${cssVar.colorWarning};
+ `,
+}));
+
+export function TopicTitle({ id }: { id: string }) {
+ const { t } = useTranslation('chat');
+ const title = useChatStore(() => topicName(id));
+ const useFetchTopicDetail = useChatStore((s) => s.useFetchTopicDetail);
+ useFetchTopicDetail(title ? undefined : id);
+ return title || t('backgroundActivity.topic');
+}
+
+function ActivityRows({ activity, selected }: { activity: Activity; selected: boolean }) {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(selected);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!selected) return;
+ setOpen(true);
+ ref.current?.scrollIntoView({ block: 'nearest' });
+ }, [selected]);
+ const alert = activity.severity !== 'normal';
+ const tone = activity.severity === 'critical' ? tableStyles.critical : tableStyles.warning;
+ return (
+ <>
+ <div
+ aria-expanded={open}
+ className={cx(tableStyles.row, selected && tableStyles.selected)}
+ ref={ref}
+ role={'button'}
+ style={{ gridTemplateColumns: GRID }}
+ tabIndex={0}
+ onClick={() => setOpen(!open)}
+ onKeyDown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setOpen(!open);
+ }
+ }}
+ >
+ <Icon
+ className={cx(tableStyles.chevron, open && tableStyles.chevronOpen)}
+ icon={ChevronRightIcon}
+ size={14}
+ />
+ <span className={tableStyles.label} title={activity.label}>
+ {alert && <Icon className={tone} icon={TriangleAlertIcon} size={14} />}
+ {activity.label}
+ </span>
+ <span className={tableStyles.num}>
+ {t('backgroundActivity.processCount', { count: activity.processes.length })}
+ </span>
+ <span className={cx(tableStyles.num, alert && tone)}>
+ {formatMemory(activity.memoryMB)}
+ </span>
+ <span className={tableStyles.num}>{formatCpu(activity.cpuPercent)}</span>
+ <StopButton rootId={activity.rootId} />
+ </div>
+ {open &&
+ processTree(activity.processes).map(({ depth, row }) => (
+ <div className={tableStyles.proc} key={row.id} style={{ gridTemplateColumns: GRID }}>
+ <span />
+ <span className={tableStyles.procName} style={{ paddingInlineStart: depth * 14 }}>
+ {depth > 0 && '└ '}
+ {row.name}
+ </span>
+ <span className={tableStyles.num}>{row.pid}</span>
+ <span className={tableStyles.num}>{formatMemory(row.memoryMB)}</span>
+ <span className={tableStyles.num}>{formatCpu(row.cpuPercent)}</span>
+ <span />
+ </div>
+ ))}
+ </>
+ );
+}
+
+export default function ActivityTable() {
+ const { t } = useTranslation('chat');
+ const state = useActivities();
+ if (!state.loaded)
+ return (
+ <Flexbox padding={12}>
+ <Skeleton.Text rows={3} />
+ </Flexbox>
+ );
+ const groups = [...new Set(state.activities.map((row) => row.topicId))].sort(
+ (a, b) => Number(a === undefined) - Number(b === undefined),
+ );
+ return (
+ <Flexbox>
+ {state.error && (
+ <div className={tableStyles.alert} role={'alert'}>
+ <Icon icon={TriangleAlertIcon} size={14} />
+ <Flexbox flex={1}>{t('backgroundActivity.unavailable')}</Flexbox>
+ <Button
+ icon={<Icon icon={RefreshCwIcon} size={12} />}
+ size={'small'}
+ onClick={() => void refreshActivities()}
+ >
+ {t('backgroundActivity.retry')}
+ </Button>
+ </div>
+ )}
+ {state.activities.length === 0 ? (
+ !state.error && (
+ <Empty
+ description={t('backgroundActivity.emptyDesc')}
+ icon={CpuIcon}
+ style={{ paddingBlock: 32 }}
+ title={t('backgroundActivity.empty')}
+ />
+ )
+ ) : (
+ <div className={cx(state.error && tableStyles.stale)}>
+ <div className={tableStyles.head} style={{ gridTemplateColumns: GRID }}>
+ <span />
+ <span className={tableStyles.headLabel}>
+ {t('backgroundActivity.title')} · {state.activities.length}
+ </span>
+ <span />
+ <span className={tableStyles.headNum}>{t('backgroundActivity.memory')}</span>
+ <span className={tableStyles.headNum}>{t('backgroundActivity.cpu')}</span>
+ <span />
+ </div>
+ {groups.map((group) => (
+ <div key={group ?? 'shared'}>
+ <div className={tableStyles.group}>
+ <Icon icon={group ? MessageSquareIcon : CpuIcon} size={13} />
+ {group ? <TopicTitle id={group} /> : t('backgroundActivity.shared')}
+ </div>
+ {state.activities
+ .filter((row) => row.topicId === group)
+ .map((activity) => (
+ <ActivityRows
+ activity={activity}
+ key={activity.rootId}
+ selected={state.selected === activity.rootId}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ );
+}
diff --git a/src/features/BackgroundActivity/Monitor.tsx b/src/features/BackgroundActivity/Monitor.tsx
new file mode 100644
index 00000000000..3d6dc18e0f5
--- /dev/null
+++ b/src/features/BackgroundActivity/Monitor.tsx
@@ -0,0 +1,70 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import { toast } from '@lobehub/ui/base-ui';
+import { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useSingleton } from '@/hooks/useSingleton';
+import { electronDevtoolsService } from '@/services/electron/devtools';
+import { useGlobalStore } from '@/store/global';
+
+import { topicName } from './ActivityTable';
+import {
+ formatCpu,
+ formatMemory,
+ ResourceAlerts,
+ selectActivity,
+ stopActivity,
+ useActivities,
+} from './state';
+
+export default function BackgroundActivityMonitor() {
+ const state = useActivities();
+ const { t } = useTranslation('chat');
+ const router = useQueryRoute();
+ const alerts = useSingleton(() => new ResourceAlerts());
+ const sampled = useRef(0);
+ useEffect(() => {
+ if (state.error || sampled.current === state.sampledAt) return;
+ sampled.current = state.sampledAt;
+ for (const activity of alerts.update(state.activities)) {
+ const topic = topicName(activity.topicId);
+ toast.warning({
+ title: t('backgroundActivity.highUsage'),
+ id: `background-${activity.rootId}`,
+ description: t('backgroundActivity.alertDesc', {
+ name: topic ? `${activity.label} · ${topic}` : activity.label,
+ memory: formatMemory(activity.memoryMB),
+ cpu: formatCpu(activity.cpuPercent),
+ }),
+ actions: [
+ {
+ label: t('backgroundActivity.details'),
+ variant: 'text',
+ onClick: () => {
+ selectActivity(activity.rootId);
+ if (activity.agentId && activity.topicId) {
+ router.push(AGENT_CHAT_TOPIC_URL(activity.agentId, activity.topicId));
+ useGlobalStore.getState().toggleRightPanel(false);
+ useGlobalStore.getState().toggleWorkingOverview(true);
+ } else {
+ void electronDevtoolsService.openProcessExplorer();
+ }
+ },
+ },
+ {
+ label: t('backgroundActivity.stop'),
+ variant: 'danger',
+ onClick: () => {
+ stopActivity(activity.rootId).catch((error) => {
+ console.error(error);
+ toast.error(t('backgroundActivity.stopFailed'));
+ });
+ },
+ },
+ ],
+ });
+ }
+ }, [state, t, router, alerts]);
+ return null;
+}
diff --git a/src/features/BackgroundActivity/ProcessExplorer/buildTree.test.ts b/src/features/BackgroundActivity/ProcessExplorer/buildTree.test.ts
new file mode 100644
index 00000000000..e21f9bcdcba
--- /dev/null
+++ b/src/features/BackgroundActivity/ProcessExplorer/buildTree.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Activity } from '../state';
+import { buildProcessTree, SECTION_APP, SECTION_BACKGROUND } from './buildTree';
+
+const labels = {
+ app: 'LobeHub',
+ background: 'Background activity',
+ conversation: 'Conversation',
+ gpu: 'GPU',
+ main: 'Main process',
+ processCount: (count: number) => `${count} processes`,
+ shared: 'Shared',
+ utility: 'Utility',
+ window: 'Window',
+};
+
+const activity = (
+ rootId: string,
+ topicId: string | undefined,
+ cpu: number,
+ names: string[],
+): Activity => ({
+ cpuPercent: cpu,
+ label: rootId,
+ memoryMB: 10,
+ processes: names.map((name, index) => ({
+ cpuPercent: index === 0 ? cpu : 0,
+ id: `${rootId}:${index}`,
+ memoryMB: 10 / names.length,
+ name,
+ pid: index + rootId.length * 100,
+ ppid: index === 0 ? 1 : rootId.length * 100,
+ rootId,
+ topicId,
+ })),
+ rootId,
+ severity: 'normal',
+ topicId,
+});
+
+const build = (query = '') =>
+ buildProcessTree({
+ activities: [
+ activity('unowned', undefined, 90, ['tail']),
+ activity('slow', 't1', 1, ['sh', 'node']),
+ activity('busy', 't1', 50, ['vite']),
+ ],
+ appProcesses: [
+ { cpuPercent: 1, name: null, pid: 7, type: 'Browser', windowTitle: null, workingSetMB: 300 },
+ {
+ cpuPercent: 2,
+ name: null,
+ pid: 8,
+ type: 'Tab',
+ windowTitle: 'Refactor auth',
+ workingSetMB: 400,
+ },
+ ],
+ labels,
+ query,
+ sort: 'cpu',
+ topicTitle: (id) => (id === 't1' ? 'Auth topic' : undefined),
+ totalMemoryMB: 16_384,
+ });
+
+describe('buildProcessTree', () => {
+ it('keeps unassigned processes last and orders the rest by the sort column', () => {
+ const [background] = build().treeData;
+ expect(background.children!.map((node) => node.key)).toEqual([
+ 'conversation:t1',
+ 'conversation:shared',
+ ]);
+ expect(background.children![0].children!.map((node) => node.key)).toEqual([
+ 'activity:busy',
+ 'activity:slow',
+ ]);
+ });
+
+ it('names windows by their title and sums section totals', () => {
+ const { rows } = build();
+ expect(rows.get('app:8')).toMatchObject({ label: 'Refactor auth', sub: 'Window' });
+ expect(rows.get('app:7')).toMatchObject({ label: 'LobeHub', sub: 'Main process' });
+ expect(rows.get(SECTION_APP)).toMatchObject({ cpu: 3, memory: 700 });
+ expect(rows.get(SECTION_BACKGROUND)).toMatchObject({ cpu: 141, memory: 30 });
+ });
+
+ it('filters by process name while keeping the matching branch and its ancestors', () => {
+ const [background, app] = build('node').treeData;
+ expect(background.children!.map((node) => node.key)).toEqual(['conversation:t1']);
+ expect(background.children![0].children!.map((node) => node.key)).toEqual(['activity:slow']);
+ expect(app.children).toBeUndefined();
+ });
+});
diff --git a/src/features/BackgroundActivity/ProcessExplorer/buildTree.ts b/src/features/BackgroundActivity/ProcessExplorer/buildTree.ts
new file mode 100644
index 00000000000..432d034d67b
--- /dev/null
+++ b/src/features/BackgroundActivity/ProcessExplorer/buildTree.ts
@@ -0,0 +1,194 @@
+import type { AppProcessRow } from '@lobechat/electron-client-ipc';
+import type { TreeDataNode } from '@lobehub/ui/base-ui';
+
+import type { Activity, ProcessRow } from '../state';
+
+export type SortKey = 'cpu' | 'memory';
+
+export interface RowModel {
+ appType?: string;
+ cpu: number | null;
+ cpuHot?: boolean;
+ kind: 'app' | 'activity' | 'conversation' | 'process' | 'section';
+ label: string;
+ memory: number;
+ memoryHot?: boolean;
+ pid?: number;
+ stopId?: string;
+ sub?: string;
+ topicId?: string;
+}
+
+export interface TreeLabels {
+ app: string;
+ background: string;
+ conversation: string;
+ gpu: string;
+ main: string;
+ processCount: (count: number) => string;
+ shared: string;
+ utility: string;
+ window: string;
+}
+
+export interface BuildTreeInput {
+ activities: Activity[];
+ appProcesses: AppProcessRow[] | null;
+ labels: TreeLabels;
+ query: string;
+ sort: SortKey;
+ topicTitle: (id: string) => string | undefined;
+ totalMemoryMB: number;
+}
+
+export const SECTION_BACKGROUND = 'section:background';
+export const SECTION_APP = 'section:app';
+
+interface Draft {
+ children: Draft[];
+ key: string;
+ row: RowModel;
+}
+
+const metric = (row: RowModel, sort: SortKey) => (sort === 'cpu' ? (row.cpu ?? 0) : row.memory);
+
+const sum = (rows: RowModel[]) =>
+ rows.reduce(
+ (total, row) => ({
+ cpu: row.cpu === null ? total.cpu : (total.cpu ?? 0) + row.cpu,
+ memory: total.memory + row.memory,
+ }),
+ { cpu: null as number | null, memory: 0 },
+ );
+
+const appRow = (process: AppProcessRow, labels: TreeLabels): RowModel => {
+ const base = {
+ appType: process.type,
+ cpu: process.cpuPercent,
+ kind: 'app' as const,
+ memory: process.workingSetMB,
+ pid: process.pid,
+ };
+ if (process.type === 'Browser') return { ...base, label: labels.app, sub: labels.main };
+ if (process.type === 'GPU') return { ...base, label: labels.gpu };
+ if (process.type === 'Tab')
+ return { ...base, label: process.windowTitle ?? labels.window, sub: labels.window };
+ if (process.type === 'Utility')
+ return { ...base, label: process.name ?? labels.utility, sub: labels.utility };
+ return { ...base, label: process.name ?? process.type, sub: process.type };
+};
+
+const processDrafts = (processes: ProcessRow[]): Draft[] => {
+ const pids = new Set(processes.map((row) => row.pid));
+ const seen = new Set<number>();
+ const draft = (process: ProcessRow): Draft => {
+ seen.add(process.pid);
+ return {
+ children: processes
+ .filter((row) => row.ppid === process.pid && !seen.has(row.pid))
+ .map((row) => draft(row)),
+ key: `process:${process.id}`,
+ row: {
+ cpu: process.cpuPercent,
+ kind: 'process',
+ label: process.name,
+ memory: process.memoryMB,
+ pid: process.pid,
+ },
+ };
+ };
+ const roots = processes
+ .filter((row) => !pids.has(row.ppid) || row.ppid === row.pid)
+ .map((row) => draft(row));
+ for (const row of processes) if (!seen.has(row.pid)) roots.push(draft(row));
+ return roots;
+};
+
+export const buildProcessTree = ({
+ activities,
+ appProcesses,
+ labels,
+ query,
+ sort,
+ topicTitle,
+ totalMemoryMB,
+}: BuildTreeInput) => {
+ const needle = query.trim().toLowerCase();
+ const matches = (...values: (number | string | undefined)[]) =>
+ !needle ||
+ values.some((value) => value !== undefined && String(value).toLowerCase().includes(needle));
+ const memoryLimit = Math.min(2048, totalMemoryMB * 0.15 || 2048);
+
+ const topics = [...new Set(activities.map((row) => row.topicId))];
+ const conversations: Draft[] = topics.flatMap((topicId) => {
+ const title = topicId ? (topicTitle(topicId) ?? labels.conversation) : labels.shared;
+ const children = activities
+ .filter((row) => row.topicId === topicId)
+ .filter((row) => matches(title, row.label, ...row.processes.flatMap((p) => [p.name, p.pid])))
+ .map<Draft>((activity) => {
+ const hot = activity.severity !== 'normal';
+ return {
+ children: processDrafts(activity.processes),
+ key: `activity:${activity.rootId}`,
+ row: {
+ cpu: activity.cpuPercent,
+ cpuHot: hot && (activity.cpuPercent ?? 0) >= 200,
+ kind: 'activity',
+ label: activity.label ?? '',
+ memory: activity.memoryMB,
+ memoryHot: hot && activity.memoryMB >= memoryLimit,
+ stopId: activity.rootId,
+ sub:
+ activity.processes.length > 1
+ ? labels.processCount(activity.processes.length)
+ : undefined,
+ },
+ };
+ });
+ if (children.length === 0) return [];
+ return [
+ {
+ children,
+ key: `conversation:${topicId ?? 'shared'}`,
+ row: { ...sum(children.map((c) => c.row)), kind: 'conversation', label: title, topicId },
+ },
+ ];
+ });
+
+ const apps: Draft[] = (appProcesses ?? [])
+ .map((process) => appRow(process, labels))
+ .filter((row) => matches(row.label, row.sub, row.pid))
+ .map((row) => ({ children: [], key: `app:${row.pid}`, row }));
+
+ const sections: Draft[] = [
+ {
+ children: conversations,
+ key: SECTION_BACKGROUND,
+ row: { ...sum(conversations.map((c) => c.row)), kind: 'section', label: labels.background },
+ },
+ {
+ children: apps,
+ key: SECTION_APP,
+ row: { ...sum(apps.map((c) => c.row)), kind: 'section', label: labels.app },
+ },
+ ];
+
+ const rows = new Map<string, RowModel>();
+ const toNode = (draft: Draft): TreeDataNode => {
+ rows.set(draft.key, draft.row);
+ const children = [...draft.children].sort(
+ (a, b) =>
+ Number(a.row.kind === 'conversation' && !a.row.topicId) -
+ Number(b.row.kind === 'conversation' && !b.row.topicId) ||
+ metric(b.row, sort) - metric(a.row, sort),
+ );
+ return {
+ children: children.length ? children.map((child) => toNode(child)) : undefined,
+ key: draft.key,
+ selectable: draft.row.kind !== 'section',
+ title: draft.row.label,
+ };
+ };
+
+ return { rows, treeData: sections.map((section) => toNode(section)) };
+};
diff --git a/src/features/BackgroundActivity/ProcessExplorer/index.tsx b/src/features/BackgroundActivity/ProcessExplorer/index.tsx
new file mode 100644
index 00000000000..09c9693355c
--- /dev/null
+++ b/src/features/BackgroundActivity/ProcessExplorer/index.tsx
@@ -0,0 +1,258 @@
+import { BRANDING_NAME } from '@lobechat/business-const';
+import { Flexbox, Icon } from '@lobehub/ui';
+import {
+ Input,
+ showContextMenu,
+ Skeleton,
+ toast,
+ Tree,
+ type TreeDataNode,
+} from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import {
+ AppWindowIcon,
+ BoxIcon,
+ ChevronDownIcon,
+ CpuIcon,
+ GpuIcon,
+ type LucideIcon,
+ MessageSquareIcon,
+ SearchIcon,
+ SquareTerminalIcon,
+} from 'lucide-react';
+import { type KeyboardEvent, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAppProcessMetrics } from '@/features/DevDock/widgets/appProcessMetrics';
+
+import { topicName, TopicTitle } from '../ActivityTable';
+import { formatCpu, formatMemory, stopActivity, useActivities } from '../state';
+import StopButton from '../StopButton';
+import {
+ buildProcessTree,
+ type RowModel,
+ SECTION_APP,
+ SECTION_BACKGROUND,
+ type SortKey,
+} from './buildTree';
+import { styles } from './style';
+
+const APP_ICONS: Record<string, LucideIcon> = {
+ Browser: CpuIcon,
+ GPU: GpuIcon,
+ Tab: AppWindowIcon,
+ Utility: BoxIcon,
+};
+
+const rowIcon = (row: RowModel): LucideIcon | undefined => {
+ if (row.kind === 'app') return APP_ICONS[row.appType ?? ''] ?? BoxIcon;
+ if (row.kind === 'activity') return SquareTerminalIcon;
+ if (row.kind === 'conversation') return row.topicId ? MessageSquareIcon : CpuIcon;
+};
+
+function Cells({ row }: { row: RowModel }) {
+ const icon = rowIcon(row);
+ const hot = row.cpuHot || row.memoryHot;
+ return (
+ <span className={cx(styles.cells, row.kind === 'section' && styles.section)}>
+ <span className={styles.name}>
+ {icon && <Icon className={styles.kind} icon={icon} size={14} />}
+ {hot && <i className={styles.dot} />}
+ <span className={styles.label} title={row.label}>
+ {row.kind === 'conversation' && row.topicId ? <TopicTitle id={row.topicId} /> : row.label}
+ </span>
+ {row.sub && <span className={styles.sub}>{row.sub}</span>}
+ </span>
+ <span className={cx(styles.num, row.cpuHot && styles.hot)}>{formatCpu(row.cpu)}</span>
+ <span className={cx(styles.num, row.memoryHot && styles.hot)}>
+ {formatMemory(row.memory)}
+ </span>
+ <span className={styles.pid}>{row.pid}</span>
+ {row.stopId ? (
+ <span data-stop-cell className={styles.stop}>
+ <StopButton rootId={row.stopId} />
+ </span>
+ ) : (
+ <span />
+ )}
+ </span>
+ );
+}
+
+const collectExpandable = (nodes: TreeDataNode[], out: string[] = []) => {
+ for (const node of nodes)
+ if (node.children?.length) {
+ out.push(node.key);
+ collectExpandable(node.children, out);
+ }
+ return out;
+};
+
+const openByDefault = (key: string) =>
+ key === SECTION_APP || key === SECTION_BACKGROUND || key.startsWith('conversation:');
+
+export default function ProcessExplorer() {
+ const { t } = useTranslation('chat');
+ const metrics = useAppProcessMetrics();
+ const { activities, sampledAt, selected: selectedActivity, totalMemoryMB } = useActivities();
+ const [sort, setSort] = useState<SortKey>('cpu');
+ const [query, setQuery] = useState('');
+ const [selected, setSelected] = useState(
+ () => selectedActivity && `activity:${selectedActivity}`,
+ );
+ const [toggled, setToggled] = useState<ReadonlySet<string>>(() => new Set());
+
+ const { rows, treeData } = useMemo(
+ () =>
+ buildProcessTree({
+ activities,
+ appProcesses: metrics?.processes ?? null,
+ labels: {
+ app: BRANDING_NAME,
+ background: t('backgroundActivity.title'),
+ conversation: t('backgroundActivity.topic'),
+ gpu: t('processExplorer.gpu'),
+ main: t('processExplorer.main'),
+ processCount: (count) => t('backgroundActivity.processCount', { count }),
+ shared: t('backgroundActivity.shared'),
+ utility: t('processExplorer.utility'),
+ window: t('processExplorer.window'),
+ },
+ query,
+ sort,
+ topicTitle: topicName,
+ totalMemoryMB,
+ }),
+ [activities, metrics, query, sort, t, totalMemoryMB],
+ );
+
+ const expandedKeys = collectExpandable(treeData).filter(
+ (key) => !!query || openByDefault(key) !== toggled.has(key),
+ );
+ const background = rows.get(SECTION_BACKGROUND)!;
+ const app = rows.get(SECTION_APP)!;
+ const processCount =
+ (metrics?.processes.length ?? 0) +
+ activities.reduce((total, row) => total + row.processes.length, 0);
+
+ const stop = (id: string) =>
+ stopActivity(id).catch((error) => {
+ console.error(error);
+ toast.error(t('backgroundActivity.stopFailed'));
+ });
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Backspace' && event.key !== 'Delete') return;
+ const stopId = selected && rows.get(selected)?.stopId;
+ if (!stopId || (event.target as HTMLElement).closest('input')) return;
+ event.preventDefault();
+ void stop(stopId);
+ };
+
+ const sortHeader = (key: SortKey, label: string) => (
+ <button
+ className={cx(styles.sort, sort === key && styles.sortActive)}
+ type={'button'}
+ onClick={() => setSort(key)}
+ >
+ {label}
+ {sort === key && <Icon icon={ChevronDownIcon} size={12} />}
+ </button>
+ );
+
+ return (
+ <Flexbox flex={1} style={{ minHeight: 0 }}>
+ <Flexbox horizontal align={'center'} className={styles.toolbar} gap={20}>
+ <span className={styles.stat}>
+ {t('backgroundActivity.cpu')}
+ <b>{formatCpu((background.cpu ?? 0) + (app.cpu ?? 0))}</b>
+ </span>
+ <span className={styles.stat}>
+ {t('backgroundActivity.memory')}
+ <b>{formatMemory(background.memory + app.memory)}</b>
+ {totalMemoryMB > 0 && `/ ${formatMemory(totalMemoryMB)}`}
+ </span>
+ <span className={styles.stat}>
+ {t('processExplorer.processes')}
+ <b>{processCount}</b>
+ </span>
+ <Flexbox flex={1} />
+ <Input
+ placeholder={t('processExplorer.filter')}
+ prefix={<Icon icon={SearchIcon} size={14} />}
+ size={'small'}
+ style={{ width: 200 }}
+ type={'search'}
+ value={query}
+ variant={'filled'}
+ onChange={(event) => setQuery(event.target.value)}
+ />
+ </Flexbox>
+ <div className={styles.body} onKeyDown={onKeyDown}>
+ <div className={cx(styles.cells, styles.header)}>
+ <span>{t('processExplorer.name')}</span>
+ {sortHeader('cpu', t('backgroundActivity.cpu'))}
+ {sortHeader('memory', t('backgroundActivity.memory'))}
+ <span className={styles.headerPid}>{t('processExplorer.pid')}</span>
+ <span />
+ </div>
+ {metrics || activities.length > 0 ? (
+ <Tree
+ blockNode
+ showLine
+ classNames={{ node: styles.node, title: styles.title }}
+ expandedKeys={expandedKeys}
+ selectedKeys={selected ? [selected] : []}
+ styles={{ node: { height: 28 } }}
+ titleRender={(node) => <Cells row={rows.get(node.key)!} />}
+ treeData={treeData}
+ onSelect={(keys) => setSelected(keys[0])}
+ onExpand={(_, { node }) =>
+ setToggled((prev) => {
+ const next = new Set(prev);
+ if (!next.delete(node.key)) next.add(node.key);
+ return next;
+ })
+ }
+ onRightClick={({ event, node }) => {
+ const row = rows.get(node.key);
+ if (!row || row.kind === 'section') return;
+ event.preventDefault();
+ setSelected(node.key);
+ showContextMenu([
+ {
+ danger: true,
+ disabled: !row.stopId,
+ key: 'stop',
+ label: t('backgroundActivity.stop'),
+ onClick: () => row.stopId && void stop(row.stopId),
+ },
+ {
+ disabled: !row.pid,
+ key: 'copy-pid',
+ label: t('processExplorer.copyPid'),
+ onClick: () => void navigator.clipboard.writeText(String(row.pid)),
+ },
+ ]);
+ }}
+ />
+ ) : (
+ <Flexbox padding={16}>
+ <Skeleton.Text rows={4} />
+ </Flexbox>
+ )}
+ </div>
+ <Flexbox horizontal align={'center'} className={styles.status} justify={'space-between'}>
+ <span className={styles.live}>
+ <i />
+ {t('processExplorer.live')}
+ </span>
+ {sampledAt > 0 && (
+ <span>
+ {t('processExplorer.updated', { time: new Date(sampledAt).toLocaleTimeString() })}
+ </span>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+}
diff --git a/src/features/BackgroundActivity/ProcessExplorer/style.ts b/src/features/BackgroundActivity/ProcessExplorer/style.ts
new file mode 100644
index 00000000000..0f04d688e79
--- /dev/null
+++ b/src/features/BackgroundActivity/ProcessExplorer/style.ts
@@ -0,0 +1,177 @@
+import { createStaticStyles } from 'antd-style';
+
+export const styles = createStaticStyles(({ css, cssVar }) => ({
+ body: css`
+ overflow: auto;
+ flex: 1;
+
+ min-height: 0;
+ padding-block: 0 8px;
+ padding-inline: 6px;
+ `,
+ cells: css`
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 80px 88px 64px 32px;
+ flex: 1;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ dot: css`
+ flex: none;
+
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+
+ background: ${cssVar.colorWarning};
+ `,
+ header: css`
+ position: sticky;
+ z-index: 2;
+ inset-block-start: 0;
+
+ height: 30px;
+ margin-block-end: 4px;
+ margin-inline: -6px;
+ padding-inline: 36px 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11.5px;
+ color: ${cssVar.colorTextTertiary};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ headerPid: css`
+ text-align: end;
+ `,
+ hot: css`
+ font-weight: 500;
+ color: ${cssVar.colorWarning} !important;
+ `,
+ kind: css`
+ flex: none;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ label: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ live: css`
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+
+ i {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: ${cssVar.colorSuccess};
+ }
+ `,
+ name: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ min-width: 0;
+ `,
+ node: css`
+ cursor: default;
+
+ &:hover [data-stop-cell],
+ &[aria-selected='true'] [data-stop-cell],
+ &:focus-within [data-stop-cell] {
+ visibility: visible;
+ }
+ `,
+ num: css`
+ font-size: 12.5px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+ text-align: end;
+ `,
+ pid: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11.5px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: end;
+ `,
+ section: css`
+ font-size: 11px;
+ font-weight: 600;
+ color: ${cssVar.colorTextTertiary};
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ `,
+ sort: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 3px;
+ align-items: center;
+ justify-content: flex-end;
+
+ padding: 0;
+ border: 0;
+
+ font: inherit;
+ color: inherit;
+
+ background: none;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ }
+ `,
+ sortActive: css`
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ `,
+ stat: css`
+ display: inline-flex;
+ gap: 6px;
+ align-items: baseline;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ b {
+ font-size: 13px;
+ font-weight: 500;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorText};
+ }
+ `,
+ status: css`
+ flex: none;
+
+ height: 28px;
+ padding-inline: 16px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11.5px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ stop: css`
+ justify-self: end;
+ visibility: hidden;
+ `,
+ sub: css`
+ flex: none;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+ `,
+ title: css`
+ flex: 1;
+ padding-inline-end: 6px;
+ `,
+ toolbar: css`
+ flex: none;
+ height: 44px;
+ padding-inline: 16px 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+}));
diff --git a/src/features/BackgroundActivity/StopButton.tsx b/src/features/BackgroundActivity/StopButton.tsx
new file mode 100644
index 00000000000..bdccab92e70
--- /dev/null
+++ b/src/features/BackgroundActivity/StopButton.tsx
@@ -0,0 +1,32 @@
+import { ActionIcon, toast } from '@lobehub/ui/base-ui';
+import { CircleStopIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { stopActivity } from './state';
+
+export default function StopButton({ rootId }: { rootId: string }) {
+ const { t } = useTranslation('chat');
+ const [stopping, setStopping] = useState(false);
+ return (
+ <ActionIcon
+ danger
+ icon={CircleStopIcon}
+ loading={stopping}
+ size={'small'}
+ title={t('backgroundActivity.stop')}
+ onClick={async (event) => {
+ event.stopPropagation();
+ setStopping(true);
+ try {
+ await stopActivity(rootId);
+ } catch (error) {
+ console.error(error);
+ toast.error(t('backgroundActivity.stopFailed'));
+ } finally {
+ setStopping(false);
+ }
+ }}
+ />
+ );
+}
diff --git a/src/features/BackgroundActivity/TopicSection.tsx b/src/features/BackgroundActivity/TopicSection.tsx
new file mode 100644
index 00000000000..c4adc762a72
--- /dev/null
+++ b/src/features/BackgroundActivity/TopicSection.tsx
@@ -0,0 +1,143 @@
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { RefreshCwIcon, SquareTerminalIcon, TriangleAlertIcon } from 'lucide-react';
+import { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isDesktop } from '@/const/version';
+import {
+ OverviewRow,
+ rowStyles,
+} from '@/features/Conversation/WorkingSidebar/Overview/OverviewRow';
+import { sectionStyles } from '@/features/Conversation/WorkingSidebar/Overview/sectionStyles';
+
+import {
+ type Activity,
+ formatCpu,
+ formatMemory,
+ refreshActivities,
+ sumCpu,
+ useActivities,
+} from './state';
+import StopButton from './StopButton';
+
+const styles = createStaticStyles(({ css }) => ({
+ critical: css`
+ color: ${cssVar.colorError};
+ `,
+ metrics: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11.5px;
+ `,
+ selected: css`
+ @keyframes background-activity-flash {
+ from {
+ background: ${cssVar.colorWarningBg};
+ }
+ }
+
+ border-radius: 8px;
+ animation: background-activity-flash 1.6s ease-out;
+ `,
+ stale: css`
+ opacity: 0.55;
+ `,
+ warning: css`
+ color: ${cssVar.colorWarning};
+ `,
+}));
+
+function ActivityRow({ activity, selected }: { activity: Activity; selected: boolean }) {
+ const { t } = useTranslation('chat');
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (selected) ref.current?.scrollIntoView({ block: 'nearest' });
+ }, [selected]);
+ const alert = activity.severity !== 'normal';
+ const tone = activity.severity === 'critical' ? styles.critical : styles.warning;
+ return (
+ <div className={cx(selected && styles.selected)} ref={ref}>
+ <OverviewRow
+ title={t('backgroundActivity.processCount', { count: activity.processes.length })}
+ value={activity.label}
+ iconNode={
+ alert ? (
+ <Tooltip title={t('backgroundActivity.highUsage')}>
+ <Icon className={tone} icon={TriangleAlertIcon} size={16} />
+ </Tooltip>
+ ) : (
+ <Icon className={rowStyles.icon} icon={SquareTerminalIcon} size={16} />
+ )
+ }
+ trailing={
+ <>
+ <span className={cx(styles.metrics, alert && tone)}>
+ {formatMemory(activity.memoryMB)}
+ </span>
+ <span className={styles.metrics}>{formatCpu(activity.cpuPercent)}</span>
+ <StopButton rootId={activity.rootId} />
+ </>
+ }
+ />
+ </div>
+ );
+}
+
+export function TopicBackgroundActivity({ topicId }: { topicId?: string }) {
+ const { t } = useTranslation('chat');
+ const state = useActivities();
+ if (!isDesktop || !topicId || !state.loaded) return null;
+ const activities = state.activities.filter((row) => row.topicId === topicId);
+ if (activities.length === 0 && !state.error) return null;
+ return (
+ <Flexbox className={sectionStyles.section}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={sectionStyles.sectionHeader}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span className={sectionStyles.sectionTitle}>{t('backgroundActivity.title')}</span>
+ {activities.length > 0 && (
+ <span className={sectionStyles.count}>{activities.length}</span>
+ )}
+ </Flexbox>
+ {activities.length > 1 && (
+ <span className={cx(rowStyles.rowTrailing, styles.metrics)}>
+ {formatMemory(activities.reduce((sum, row) => sum + row.memoryMB, 0))} ·{' '}
+ {formatCpu(sumCpu(activities))}
+ </span>
+ )}
+ </Flexbox>
+ {state.error && (
+ <OverviewRow
+ danger
+ icon={TriangleAlertIcon}
+ iconColor={cssVar.colorError}
+ title={t('backgroundActivity.unavailable')}
+ value={t('backgroundActivity.unavailable')}
+ trailing={
+ <Button
+ icon={<Icon icon={RefreshCwIcon} size={12} />}
+ size={'small'}
+ onClick={() => void refreshActivities()}
+ >
+ {t('backgroundActivity.retry')}
+ </Button>
+ }
+ />
+ )}
+ <div className={cx(state.error && styles.stale)}>
+ {activities.map((activity) => (
+ <ActivityRow
+ activity={activity}
+ key={activity.rootId}
+ selected={state.selected === activity.rootId}
+ />
+ ))}
+ </div>
+ </Flexbox>
+ );
+}
diff --git a/src/features/BackgroundActivity/index.tsx b/src/features/BackgroundActivity/index.tsx
new file mode 100644
index 00000000000..679bc70f970
--- /dev/null
+++ b/src/features/BackgroundActivity/index.tsx
@@ -0,0 +1,27 @@
+import { Flexbox } from '@lobehub/ui';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import ActivityTable from './ActivityTable';
+import { formatCpu, formatMemory, sumCpu, useActivities } from './state';
+
+export default function BackgroundActivityPanel() {
+ const { activities, sampledAt } = useActivities();
+ const processes = activities.reduce((sum, row) => sum + row.processes.length, 0);
+ return (
+ <Flexbox className={devDockPanelStyles.root}>
+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'auto' }}>
+ <ActivityTable />
+ </Flexbox>
+ <div className={devDockPanelStyles.statusBar}>
+ <span>
+ {processes} proc · {formatMemory(activities.reduce((sum, row) => sum + row.memoryMB, 0))}{' '}
+ · {formatCpu(sumCpu(activities))} cpu
+ </span>
+ {sampledAt > 0 && (
+ <span>sampled {new Date(sampledAt).toLocaleTimeString()} · every 2s</span>
+ )}
+ </div>
+ </Flexbox>
+ );
+}
diff --git a/src/features/BackgroundActivity/state.test.ts b/src/features/BackgroundActivity/state.test.ts
new file mode 100644
index 00000000000..38ec9ff9aff
--- /dev/null
+++ b/src/features/BackgroundActivity/state.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ formatMemory,
+ groupActivities,
+ type ProcessRow,
+ type ProcessSnapshot,
+ processTree,
+ ResourceAlerts,
+} from './state';
+
+vi.mock('@/services/electron/devtools', () => ({ electronDevtoolsService: {} }));
+
+describe('background resources', () => {
+ const snapshot: ProcessSnapshot = {
+ sampledAt: 1,
+ totalMemoryMB: 16384,
+ processes: [
+ {
+ id: '1:a',
+ rootId: '1:a',
+ pid: 1,
+ ppid: 0,
+ name: 'shell',
+ topicId: 'one',
+ memoryMB: 100,
+ cpuPercent: null,
+ },
+ {
+ id: '2:a',
+ rootId: '1:a',
+ pid: 2,
+ ppid: 1,
+ name: 'node',
+ topicId: 'one',
+ memoryMB: 2500,
+ cpuPercent: 50,
+ },
+ { id: '3:a', rootId: '3:a', pid: 3, ppid: 0, name: 'shared', memoryMB: 40, cpuPercent: 1 },
+ ],
+ };
+ it('counts descendants once and leaves shared services outside topic totals', () => {
+ const activities = groupActivities(snapshot);
+ expect(activities).toHaveLength(2);
+ expect(activities[0]).toMatchObject({
+ topicId: 'one',
+ memoryMB: 2600,
+ cpuPercent: 50,
+ severity: 'warning',
+ });
+ expect(activities[1].topicId).toBeUndefined();
+ });
+ it('deduplicates sustained warnings, escalates immediately and rearms after recovery', () => {
+ const alerts = new ResourceAlerts();
+ const activities = groupActivities(snapshot);
+ expect(alerts.update(activities)).toEqual([]);
+ expect(alerts.update(activities)).toEqual([]);
+ expect(alerts.update(activities)).toHaveLength(1);
+ expect(alerts.update(activities)).toEqual([]);
+ activities[0].severity = 'critical';
+ expect(alerts.update(activities)).toHaveLength(1);
+ expect(alerts.update(activities)).toEqual([]);
+ activities[0].severity = 'normal';
+ for (let i = 0; i < 3; i++) alerts.update(activities);
+ activities[0].severity = 'critical';
+ expect(alerts.update(activities)).toHaveLength(1);
+ });
+ it('orders processes depth-first under their parent and survives pid cycles', () => {
+ const row = (pid: number, ppid: number) =>
+ ({ id: `${pid}`, pid, ppid, name: `p${pid}` }) as ProcessRow;
+ const tree = processTree([row(3, 2), row(1, 0), row(4, 1), row(2, 1), row(8, 9), row(9, 8)]);
+ expect(tree.map(({ depth, row }) => `${row.pid}:${depth}`)).toEqual([
+ '1:0',
+ '4:1',
+ '2:1',
+ '3:2',
+ '8:0',
+ '9:1',
+ ]);
+ });
+ it('switches to gigabytes at 1024 MB', () => {
+ expect(formatMemory(1023.4)).toBe('1023 MB');
+ expect(formatMemory(1536)).toBe('1.5 GB');
+ });
+});
diff --git a/src/features/BackgroundActivity/state.ts b/src/features/BackgroundActivity/state.ts
new file mode 100644
index 00000000000..3cc01efb09b
--- /dev/null
+++ b/src/features/BackgroundActivity/state.ts
@@ -0,0 +1,182 @@
+import { useSyncExternalStore } from 'react';
+
+import { isDesktop } from '@/const/version';
+import { electronDevtoolsService } from '@/services/electron/devtools';
+
+export type ProcessSnapshot = Awaited<
+ ReturnType<typeof electronDevtoolsService.getManagedProcesses>
+>;
+export type ProcessRow = ProcessSnapshot['processes'][number];
+export interface Activity extends Pick<ProcessRow, 'rootId' | 'topicId' | 'agentId' | 'label'> {
+ cpuPercent: number | null;
+ memoryMB: number;
+ processes: ProcessRow[];
+ severity: 'normal' | 'warning' | 'critical';
+}
+
+export const groupActivities = (snapshot: ProcessSnapshot): Activity[] => {
+ const groups = new Map<string, Activity>();
+ for (const row of snapshot.processes) {
+ let group = groups.get(row.rootId);
+ if (!group) {
+ group = {
+ rootId: row.rootId,
+ topicId: row.topicId,
+ agentId: row.agentId,
+ label: row.label || row.name,
+ memoryMB: 0,
+ cpuPercent: null,
+ processes: [],
+ severity: 'normal',
+ };
+ groups.set(row.rootId, group);
+ }
+ group.memoryMB += row.memoryMB;
+ if (row.cpuPercent !== null) group.cpuPercent = (group.cpuPercent ?? 0) + row.cpuPercent;
+ group.processes.push(row);
+ }
+ for (const group of groups.values()) {
+ // ponytail: resident sets can count shared pages twice; use private footprint if this becomes a memory limiter.
+ group.severity =
+ group.memoryMB >= Math.min(4096, snapshot.totalMemoryMB * 0.3)
+ ? 'critical'
+ : group.memoryMB >= Math.min(2048, snapshot.totalMemoryMB * 0.15) ||
+ (group.cpuPercent ?? 0) >= 200
+ ? 'warning'
+ : 'normal';
+ }
+ return [...groups.values()];
+};
+
+export const formatMemory = (mb: number) =>
+ mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${Math.round(mb)} MB`;
+
+export const formatCpu = (percent: number | null) =>
+ percent === null ? '—' : `${Math.round(percent)}%`;
+
+export const sumCpu = (activities: Activity[]) =>
+ activities.some((row) => row.cpuPercent !== null)
+ ? activities.reduce((sum, row) => sum + (row.cpuPercent ?? 0), 0)
+ : null;
+
+export const processTree = (processes: ProcessRow[]) => {
+ const pids = new Set(processes.map((row) => row.pid));
+ const children = new Map<number, ProcessRow[]>();
+ const roots: ProcessRow[] = [];
+ for (const row of processes) {
+ if (pids.has(row.ppid) && row.ppid !== row.pid) {
+ const siblings = children.get(row.ppid) ?? [];
+ siblings.push(row);
+ children.set(row.ppid, siblings);
+ } else roots.push(row);
+ }
+ const ordered: { depth: number; row: ProcessRow }[] = [];
+ const seen = new Set<number>();
+ const visit = (row: ProcessRow, depth: number) => {
+ if (seen.has(row.pid)) return;
+ seen.add(row.pid);
+ ordered.push({ depth, row });
+ for (const child of children.get(row.pid) ?? []) visit(child, depth + 1);
+ };
+ for (const row of roots) visit(row, 0);
+ for (const row of processes) visit(row, 0);
+ return ordered;
+};
+
+interface State {
+ activities: Activity[];
+ error: boolean;
+ loaded: boolean;
+ sampledAt: number;
+ selected?: string;
+ totalMemoryMB: number;
+}
+let state: State = { activities: [], error: false, loaded: false, sampledAt: 0, totalMemoryMB: 0 };
+const listeners = new Set<() => void>();
+let timer: ReturnType<typeof setInterval> | undefined;
+let pending: Promise<void> | undefined;
+const emit = () => {
+ for (const listener of listeners) listener();
+};
+export const selectActivity = (id: string) => {
+ state = { ...state, selected: id };
+ emit();
+};
+export const refreshActivities = () => {
+ pending ??= electronDevtoolsService
+ .getManagedProcesses()
+ .then((snapshot) => {
+ state = {
+ ...state,
+ activities: groupActivities(snapshot),
+ sampledAt: snapshot.sampledAt,
+ totalMemoryMB: snapshot.totalMemoryMB,
+ error: false,
+ loaded: true,
+ };
+ })
+ .catch((error) => {
+ console.error('Cannot sample background processes:', error);
+ state = { ...state, error: true, loaded: true };
+ })
+ .finally(() => {
+ pending = undefined;
+ emit();
+ });
+ return pending;
+};
+export const stopActivity = async (rootId: string) => {
+ await electronDevtoolsService.stopManagedProcess(rootId);
+ await refreshActivities();
+};
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ if (isDesktop && !timer) {
+ void refreshActivities();
+ timer = setInterval(refreshActivities, 2000);
+ }
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size) {
+ clearInterval(timer);
+ timer = undefined;
+ }
+ };
+};
+export const useActivities = () =>
+ useSyncExternalStore(
+ subscribe,
+ () => state,
+ () => state,
+ );
+
+/** One alert per episode, with escalation; require three sustained warning samples. */
+export class ResourceAlerts {
+ private episodes = new Map<string, { samples: number; notified: number; recovered: number }>();
+ update(activities: Activity[]) {
+ const alerts: Activity[] = [];
+ const ids = new Set(activities.map((item) => item.rootId));
+ for (const id of this.episodes.keys()) if (!ids.has(id)) this.episodes.delete(id);
+ for (const activity of activities) {
+ const episode = this.episodes.get(activity.rootId) ?? {
+ samples: 0,
+ notified: 0,
+ recovered: 0,
+ };
+ const level = activity.severity === 'critical' ? 2 : activity.severity === 'warning' ? 1 : 0;
+ if (!level) {
+ episode.samples = 0;
+ if (++episode.recovered >= 3) episode.notified = 0;
+ } else {
+ episode.recovered = 0;
+ episode.samples++;
+ if ((level === 2 || episode.samples >= 3) && level > episode.notified) {
+ alerts.push(activity);
+ episode.notified = level;
+ }
+ }
+ this.episodes.set(activity.rootId, episode);
+ }
+ return alerts;
+ }
+}
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index d6600376693..30cdf18cee1 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -27,6 +27,7 @@ import {
getPullRequestState,
PR_STATE_VISUAL,
} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';
+import { TopicBackgroundActivity } from '@/features/BackgroundActivity/TopicSection';
import BranchSwitcher from '@/features/ChatInput/ControlBar/BranchSwitcher';
import WorktreeSwitcher from '@/features/ChatInput/ControlBar/WorktreeSwitcher';
import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';
@@ -423,6 +424,7 @@ const Overview = memo<OverviewProps>(
</>
)}
+ <TopicBackgroundActivity topicId={topicId} />
{environmentAvailable && !workingDirectory && (
<Empty
className={cx(sectionStyles.section, styles.emptyWorkspace)}
diff --git a/src/features/DevDock/registerBuiltinItems.ts b/src/features/DevDock/registerBuiltinItems.ts
index 11194314793..fb4753f1862 100644
--- a/src/features/DevDock/registerBuiltinItems.ts
+++ b/src/features/DevDock/registerBuiltinItems.ts
@@ -177,6 +177,13 @@ export const registerBuiltinDevDockItems = () => {
if (isDesktop) {
items.push(
+ {
+ icon: Cpu,
+ id: 'background-processes',
+ label: 'Background Processes',
+ type: 'panel',
+ load: () => import('@/features/BackgroundActivity'),
+ },
{
defaultPinned: true,
icon: Gpu,
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index 7b4a5b2c202..d68d1a2770f 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -32,6 +32,7 @@ registerNativeContextMenuInterceptor();
const DevDock = lazy(() => import('@/features/DevDock'));
const ImperativeMountHost = lazy(() => import('@/components/ImperativeMount'));
const DynamicFavicon = lazy(() => import('@/layout/GlobalProvider/DynamicFavicon'));
+const BackgroundActivityMonitor = lazy(() => import('@/features/BackgroundActivity/Monitor'));
const TaskDock = lazy(() => import('@/features/TaskDock'));
const devDockLayoutStyle: CSSProperties = {
@@ -56,7 +57,7 @@ class DevDockBoundary extends Component<PropsWithChildren, { failed: boolean }>
}
export const DevDockLayout = memo<PropsWithChildren>(({ children }) => {
- const mounted = useDevDockMounted();
+ const mounted = useDevDockMounted() && !window.location.pathname.startsWith('/popup/processes');
return (
<>
@@ -113,6 +114,9 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
<ContextMenuHost />
<Suspense>
<TaskDock />
+ {isDesktop && !window.location.pathname.startsWith('/popup') && (
+ <BackgroundActivityMonitor />
+ )}
<ImperativeMountHost />
</Suspense>
</LazyMotion>
diff --git a/src/routes/(popup)/processes/index.tsx b/src/routes/(popup)/processes/index.tsx
new file mode 100644
index 00000000000..b463c4a989a
--- /dev/null
+++ b/src/routes/(popup)/processes/index.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ProcessExplorer from '@/features/BackgroundActivity/ProcessExplorer';
+
+import PopupTitleBar from '../_layout/TitleBar';
+
+const ProcessExplorerPage = () => {
+ const { t } = useTranslation('chat');
+ const title = t('processExplorer.title');
+ useEffect(() => {
+ document.title = title;
+ }, [title]);
+ return (
+ <Flexbox
+ height={'100%'}
+ style={{ background: cssVar.colorBgContainer, overflow: 'hidden' }}
+ width={'100%'}
+ >
+ <PopupTitleBar title={title} />
+ <ProcessExplorer />
+ </Flexbox>
+ );
+};
+
+export default ProcessExplorerPage;
diff --git a/src/services/electron/devtools.ts b/src/services/electron/devtools.ts
index 1ab2c599a48..bddf1bd8c61 100644
--- a/src/services/electron/devtools.ts
+++ b/src/services/electron/devtools.ts
@@ -1,8 +1,18 @@
import type { AppProcessMetrics, GpuStatus, MemoryDump } from '@lobechat/electron-client-ipc';
+import type { ManagedProcessSnapshot } from '@lobechat/utils/managedProcess';
import { ensureElectronIpc } from '@/utils/electron/ipc';
class DevtoolsService {
+ getManagedProcesses(): Promise<ManagedProcessSnapshot> {
+ return ensureElectronIpc().devtools.getManagedProcesses();
+ }
+ stopManagedProcess(id: string): Promise<void> {
+ return ensureElectronIpc().devtools.stopManagedProcess({ id });
+ }
+ openProcessExplorer(): Promise<void> {
+ return ensureElectronIpc().devtools.openProcessExplorer();
+ }
async openDevtools(): Promise<void> {
return ensureElectronIpc().devtools.openDevtools();
}
diff --git a/src/spa/router/popupRouter.config.tsx b/src/spa/router/popupRouter.config.tsx
index 93cb0153221..a01e4ea3304 100644
--- a/src/spa/router/popupRouter.config.tsx
+++ b/src/spa/router/popupRouter.config.tsx
@@ -6,11 +6,17 @@ import PopupLayout from '@/routes/(popup)/_layout';
import PopupAgentQuickPage from '@/routes/(popup)/agent/[aid]';
import PopupAgentTopicPage from '@/routes/(popup)/agent/[aid]/[tid]';
import PopupGroupTopicPage from '@/routes/(popup)/group/[gid]/[tid]';
+import ProcessExplorerPage from '@/routes/(popup)/processes';
import { ErrorBoundary, redirectElement } from '@/utils/router';
// Popup router configuration — dedicated SPA entry for single-topic windows.
// Desktop-only; no sidebar, no portal, hosts a single conversation per window.
export const popupRoutes: RouteObject[] = [
+ {
+ element: <ProcessExplorerPage />,
+ errorElement: <ErrorBoundary resetPath="/popup/processes" />,
+ path: '/popup/processes',
+ },
{
children: [
{