Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): Agent 进程优先级治理覆盖 pi 会话

Zhang Yunjin3e2c4701558b
diff --git a/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
index b45ae3e87c..d5e2dae93f 100644
--- a/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
+++ b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
@@ -37,6 +37,26 @@ vi.mock('node:os', () => {
};
});
+// scanWindows 经 execFileAsync 拉 powershell;测试里喂 CIM 输出行,不真起进程。
+// 真实 execFile 的 promisify 版走 custom symbol 解析成 {stdout, stderr},mock 同构
+const cpMock = vi.hoisted(() => ({ stdout: '' }));
+vi.mock('node:child_process', () => ({
+ execFile: Object.assign(
+ (
+ _file: unknown,
+ _args: unknown,
+ _opts: unknown,
+ cb: (err: null, stdout: string, stderr: string) => void,
+ ) => {
+ cb(null, cpMock.stdout, '');
+ },
+ {
+ [Symbol.for('nodejs.util.promisify.custom')]: () =>
+ Promise.resolve({ stdout: cpMock.stdout, stderr: '' }),
+ },
+ ),
+}));
+
import { allUserDataDirNames } from '@cindy/maker-shared/brand-identity';
import {
@@ -45,6 +65,7 @@ import {
createAgentProcessPriorityWatcher,
parsePosixAgentProcesses,
registerUserDataMarkers,
+ WINDOWS_AGENT_PROCESS_NAMES,
type AgentProcessRow,
type ApplyPriorityResult,
} from '../agent-process-priority';
@@ -227,6 +248,8 @@ describe('agent process discovery', () => {
const devClaudeCmd = '/repo/apps/claude-code-bin/darwin-arm64/claude';
const devCodexPackageCmd = '/repo/apps/codex-package-bin/darwin-arm64/bin/codex app-server';
const externalClaudeCmd = '/usr/local/bin/claude';
+ const piCmd = `/users/me/library/application support/${userDataDir}/pi/1.3.0-9272a77/pi --mode rpc`;
+ const devPiCmd = '/repo/apps/pi-bin/darwin-arm64/pi --mode rpc';
it('classifies bundled claude/codex command lines and rejects external installs', () => {
expect(classifyAgentCommandLine(claudeCmd)).toBe('claude');
@@ -238,6 +261,21 @@ describe('agent process discovery', () => {
expect(classifyAgentCommandLine('/usr/bin/node some-script.js')).toBeNull();
});
+ it('classifies bundled pi command lines (priority governance covers pi sessions)', () => {
+ // 回归依据:pi 会话此前对治理完全失明(2026-10-25 本机:pi 会话全速清理
+ // 脚本占满一核,设置里降优先级对它无效)。最小失败输入 = 托管安装的 pi 命令行
+ expect(classifyAgentCommandLine(piCmd)).toBe('pi');
+ expect(
+ classifyAgentCommandLine(
+ `c:\\users\\me\\appdata\\roaming\\${userDataDir}\\pi\\1.3.0-9272a77\\pi.exe --mode rpc`,
+ ),
+ ).toBe('pi');
+ expect(classifyAgentCommandLine(devPiCmd)).toBe('pi');
+ expect(classifyAgentCommandLine(`/home/u/.config/${userDataDir}/pi/1.3.0-9272a77/pi`)).toBe('pi');
+ // 外部自装的 pi(如全局 npm)不认领,与 claude/codex 同一条安全边界
+ expect(classifyAgentCommandLine('/usr/local/bin/pi --mode rpc')).toBeNull();
+ });
+
it('classifies packaged Linux layouts (legacy managed + agent-runtime fallback)', () => {
// Linux userData 在 ~/.config/<dir>/;linux-runtime-fallback 的 privateBinaryPath
// 布局是 <userData>/agent-runtime/<kind>/bin/<cmd>
@@ -266,10 +304,12 @@ describe('agent process discovery', () => {
expect(
classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/claude-code/bin/claude`),
).toBeNull(); // 注册前:不认识
+ expect(classifyAgentCommandLine(`${redirected.toLowerCase()}/pi/1.3.0/pi --mode rpc`)).toBeNull();
registerUserDataMarkers(redirected);
expect(
classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/claude-code/bin/claude`),
).toBe('claude');
+ expect(classifyAgentCommandLine(`${redirected.toLowerCase()}/pi/1.3.0/pi --mode rpc`)).toBe('pi');
expect(
classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/codex/bin/codex`),
).toBe('codex');
@@ -323,6 +363,7 @@ describe('agent process discovery', () => {
const psOutput = [
` 100 ${selfPid} ${claudeCmd}`,
` 101 ${selfPid} ${codexCmd}`,
+ ` 105 ${selfPid} ${piCmd}`,
` 102 9999 ${claudeCmd}`, // 别的进程的孩子(如另一个 Cindy 实例)
` 103 ${selfPid} ${externalClaudeCmd}`,
` 104 ${selfPid} /applications/cindy.app/contents/macos/cindy helper`,
@@ -331,6 +372,19 @@ describe('agent process discovery', () => {
expect(parsePosixAgentProcesses(psOutput, selfPid)).toEqual([
{ pid: 100, kind: 'claude' },
{ pid: 101, kind: 'codex' },
+ { pid: 105, kind: 'pi' },
]);
});
+
+ it('windows CIM scan queries pi.exe and keeps only direct children', async () => {
+ // Windows 侧按进程名过滤;pi.exe 不在查询名单 = 整条 pi 治理在 Windows 失明
+ expect([...WINDOWS_AGENT_PROCESS_NAMES]).toContain('pi.exe');
+ const piCmdLine = `C:\\Users\\u\\AppData\\Roaming\\${userDataDir}\\pi\\1.3.0\\pi.exe --mode rpc`;
+ cpMock.stdout = [
+ `9001|${process.pid}|${piCmdLine}`,
+ `9002|999999|${piCmdLine}`, // 别的实例的孩子,绝不碰
+ `9003|${process.pid}|C:\\Windows\\System32\\cmd.exe /c dir`, // 非 agent 子进程
+ ].join('\r\n');
+ await expect(__testing.scanWindows()).resolves.toEqual([{ pid: 9001, kind: 'pi' }]);
+ });
});
diff --git a/apps/desktop/src/main/agent-process-priority.ts b/apps/desktop/src/main/agent-process-priority.ts
index 4094faf955..6181aa98c1 100644
--- a/apps/desktop/src/main/agent-process-priority.ts
+++ b/apps/desktop/src/main/agent-process-priority.ts
@@ -5,7 +5,7 @@
* 对 agent 进程树里的一切子进程(bash / 测试 / 构建)都生效:降档后 agent 照常
* 用满空闲核,但用户前台应用永远优先,机器不再卡顿。
*
- * 实现方式: claude 子进程由 Claude SDK 内部 spawn(host 拿不到 pid),codex 由
+ * 实现方式: claude 子进程由 Claude SDK 内部 spawn(host 拿不到 pid),codex / pi 由
* maker-core spawn —— 统一用周期扫描:找到"当前主进程直接子进程 + 命中本产品
* agent 二进制路径 marker"的进程,按设置档位调 os.setPriority;后续 spawn 的
* 子进程(bash / 测试 worker)自动继承。发现窗口 ≤ intervalMs,即会话最初几秒
@@ -46,7 +46,7 @@ const DEFAULT_INTERVAL_MS = 15_000;
export interface AgentProcessRow {
pid: number;
- kind: 'claude' | 'codex';
+ kind: 'claude' | 'codex' | 'pi';
}
/**
@@ -139,6 +139,26 @@ const CODEX_MARKERS = [
'apps/codex-bin/',
];
+/**
+ * pi 二进制路径 marker,布局见 agent-binaries/index.ts CONFIG.pi:托管装在
+ * <userData>/pi/<version>/,dev 为 apps/pi-bin/<platform>/。与 process-monitor/
+ * agent-scan 的 buildPiPathMarkers 是同一套路径;那边 import 本文件(分类复用),
+ * 反向复用会成环,两处需同步修改。
+ */
+const PI_MARKERS = [
+ 'apps\\pi-bin\\',
+ 'apps/pi-bin/',
+ ...allUserDataDirNames(CURRENT_CINDY_REGION).flatMap((dirName) => {
+ const dir = dirName.toLowerCase();
+ return [
+ `appdata\\roaming\\${dir}\\pi\\`,
+ `appdata/roaming/${dir}/pi/`,
+ `/library/application support/${dir}/pi/`,
+ `/.config/${dir}/pi/`,
+ ];
+ }),
+];
+
/**
* 运行时 userData 派生 marker:Linux 的 userData 可被 XDG_CONFIG_HOME /
* --user-data-dir 重定向,静态 ~/.config/<brand>/ 形态的 marker 会整体失配,
@@ -146,10 +166,14 @@ const CODEX_MARKERS = [
* 实际解析值补一组 marker;静态品牌 marker 仍保留(覆盖历史目录名与另一实例
* 的标准布局)。start 入口注册,重复调用整组替换(幂等)。
*/
-const runtimeUserDataMarkers: { claude: string[]; codex: string[] } = { claude: [], codex: [] };
+const runtimeUserDataMarkers: { claude: string[]; codex: string[]; pi: string[] } = {
+ claude: [],
+ codex: [],
+ pi: [],
+};
export function registerUserDataMarkers(userDataPath: string): void {
- const markersFor = (kind: 'claude-code' | 'codex'): string[] => {
+ const markersFor = (kind: 'claude-code' | 'codex' | 'pi'): string[] => {
const lower = userDataPath.toLowerCase();
// 命令行里的分隔符形态可能与 app.getPath 返回值不同(Windows 下 / 与 \ 混用),
// 两种形态都登记;非本平台形态的变体永不命中,无害。
@@ -167,10 +191,13 @@ export function registerUserDataMarkers(userDataPath: string): void {
};
runtimeUserDataMarkers.claude = markersFor('claude-code');
runtimeUserDataMarkers.codex = markersFor('codex');
+ runtimeUserDataMarkers.pi = markersFor('pi');
}
/** 命令行(已小写)→ agent 种类;不命中任何 marker = 不是我们的 agent 进程。 */
-export function classifyAgentCommandLine(cmdLineLower: string): 'claude' | 'codex' | null {
+export function classifyAgentCommandLine(
+ cmdLineLower: string,
+): 'claude' | 'codex' | 'pi' | null {
if (
CLAUDE_MARKERS.some((m) => cmdLineLower.includes(m)) ||
runtimeUserDataMarkers.claude.some((m) => cmdLineLower.includes(m))
@@ -183,6 +210,12 @@ export function classifyAgentCommandLine(cmdLineLower: string): 'claude' | 'code
) {
return 'codex';
}
+ if (
+ PI_MARKERS.some((m) => cmdLineLower.includes(m)) ||
+ runtimeUserDataMarkers.pi.some((m) => cmdLineLower.includes(m))
+ ) {
+ return 'pi';
+ }
return null;
}
@@ -219,10 +252,18 @@ async function scanPosix(): Promise<AgentProcessRow[]> {
return parsePosixAgentProcesses(stdout, process.pid);
}
+/**
+ * Windows CIM 扫描按进程名过滤(命令行全表扫描太慢)。新增受治理的 agent 二进制
+ * 时同步这里;漏名等于该类 agent 的优先级治理在 Windows 整体失明(2026-10-25
+ * 本机事故:pi 会话全速清理脚本占满一核,治理设置对 pi 无效,即此漏名)。
+ */
+export const WINDOWS_AGENT_PROCESS_NAMES = ['claude.exe', 'codex.exe', 'pi.exe'] as const;
+
async function scanWindows(): Promise<AgentProcessRow[]> {
// 与 claude-orphan-reaper 的 Windows 扫描同一套写法(含行尾管道符的坑,见其注释)。
+ const filter = WINDOWS_AGENT_PROCESS_NAMES.map((name) => `Name='${name}'`).join(' OR ');
const script = [
- 'Get-CimInstance Win32_Process -Filter "Name=\'claude.exe\' OR Name=\'codex.exe\'" |',
+ `Get-CimInstance Win32_Process -Filter "${filter}" |`,
'ForEach-Object {',
' $cmd = ([string]$_.CommandLine) -replace "`r|`n", " "',
' Write-Output ("{0}|{1}|{2}" -f $_.ProcessId, $_.ParentProcessId, $cmd)',
@@ -409,7 +450,7 @@ export function createAgentProcessPriorityWatcher(
};
}
-export const __testing = { makeDefaultApplyPriority };
+export const __testing = { makeDefaultApplyPriority, scanWindows };
/** 生产入口:默认依赖(设置 store + 平台扫描 + os.setPriority/taskpolicy)组装并启动。 */
export function startAgentProcessPriorityWatcher(): AgentProcessPriorityWatcher {
diff --git a/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts b/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts
index 498b73ef92..b332182173 100644
--- a/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts
@@ -43,7 +43,7 @@ export interface AgentResourceSettings {
* 超出的命令在启动前排队等待。0 = 不限(默认,历史行为)。
*/
maxConcurrentCommands: number;
- /** agent 进程(claude / codex 及其子进程)的调度优先级档位。 */
+ /** agent 进程(claude / codex / pi 及其子进程)的调度优先级档位。 */
processPriority: AgentProcessPriority;
/**
* 是否向 agent 进程注入工具链限核 env(VITEST_MAX_FORKS / MAKEFLAGS 等),