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。

feat(desktop): Agent 资源占用设置页(资源治理 3/3,接替 #1051) (#1095)

Chris Zhangeb22ff8e05e7
diff --git a/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts b/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts
index 8c899d6a20..4631e3c11a 100644
--- a/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts
@@ -1,8 +1,16 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
import { describe, expect, it, vi } from 'vitest';
+const electronMock = vi.hoisted(() => ({
+ userDataDir: '',
+}));
+
vi.mock('electron', () => ({
app: {
- getPath: vi.fn(() => ''),
+ getPath: vi.fn(() => electronMock.userDataDir),
},
}));
@@ -15,7 +23,11 @@ vi.mock('../maker-host/logger-adapter.js', () => ({
},
}));
-import { __testing } from '../maker-host/agent-resource-settings-store';
+import {
+ __testing,
+ readAgentResourceSettings,
+ writeAgentResourceSetting,
+} from '../maker-host/agent-resource-settings-store';
describe('agent resource settings store', () => {
it('defaults to unlimited concurrency (0)', () => {
@@ -56,4 +68,34 @@ describe('agent resource settings store', () => {
expect(__testing.normalize({ capToolchainThreads: 'yes' }).capToolchainThreads).toBe(false);
expect(__testing.normalize({ capToolchainThreads: 1 }).capToolchainThreads).toBe(false);
});
+
+ it('does not clobber out-of-process file edits when writing another key', () => {
+ // 隐藏配置约定:直接改文件也是正式入口。写路径必须先按 mtime 失效缓存,
+ // 否则 writePatch 基于旧 overrides 计算,把手改的其它 key 静默覆盖回去。
+ electronMock.userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-resource-store-'));
+ const file = path.join(electronMock.userDataDir, 'agent-resource-settings.json');
+ try {
+ writeAgentResourceSetting('maxConcurrentCommands', 5); // 建立缓存
+ // 进程外手改:补一个 processPriority override,并保证 mtime 前进
+ const onDisk = JSON.parse(fs.readFileSync(file, 'utf-8')) as Record<string, unknown>;
+ fs.writeFileSync(file, JSON.stringify({ ...onDisk, processPriority: 'low' }, null, 2));
+ const bumped = new Date(Date.now() + 5_000);
+ fs.utimesSync(file, bumped, bumped);
+
+ writeAgentResourceSetting('capToolchainThreads', true);
+
+ const finalOnDisk = JSON.parse(fs.readFileSync(file, 'utf-8')) as Record<string, unknown>;
+ expect(finalOnDisk.processPriority).toBe('low'); // 手改不被覆盖
+ expect(finalOnDisk.maxConcurrentCommands).toBe(5);
+ expect(finalOnDisk.capToolchainThreads).toBe(true);
+ expect(readAgentResourceSettings()).toEqual({
+ maxConcurrentCommands: 5,
+ processPriority: 'low',
+ capToolchainThreads: true,
+ });
+ } finally {
+ fs.rmSync(electronMock.userDataDir, { recursive: true, force: true });
+ electronMock.userDataDir = '';
+ }
+ });
});
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 52380dca7a..498b73ef92 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
@@ -109,6 +109,10 @@ export function writeAgentResourceSetting<K extends keyof AgentResourceSettings>
key: K,
value: AgentResourceSettings[K],
): void {
+ // 写前同样按 mtime 失效缓存:隐藏配置约定允许直接改文件即生效,不失效的话
+ // writePatch 会基于旧缓存的 overrides 计算,把进程外修改的其它 key 静默
+ // 覆盖回去(bot review P1)。
+ store.invalidateIfChanged();
store.writePatch({ [key]: value } as Partial<AgentResourceSettings>);
log.info('agent resource setting written', { key, value });
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentResourceSettingsIpc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentResourceSettingsIpc.test.ts
new file mode 100644
index 0000000000..d2be333a57
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentResourceSettingsIpc.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { AgentResourceSettings } from '../../maker-host/agent-resource-settings-store';
+import { createAgentResourceSettingsIpc } from '../agent-resource-settings-ipc';
+
+const DEFAULTS: AgentResourceSettings = {
+ maxConcurrentCommands: 0,
+ processPriority: 'normal',
+ capToolchainThreads: false,
+};
+
+function makeIpc(overrides?: {
+ assertTrustedSender?: (event: unknown) => void;
+ writeThrows?: boolean;
+ resetThrows?: boolean;
+}) {
+ let value: AgentResourceSettings = { ...DEFAULTS };
+ const customized = new Set<string>();
+ const assertTrustedSender = vi.fn(overrides?.assertTrustedSender ?? (() => {}));
+ const write = vi.fn(
+ (key: keyof AgentResourceSettings, v: AgentResourceSettings[keyof AgentResourceSettings]) => {
+ if (overrides?.writeThrows) throw new Error('EACCES: /internal/abs/path readonly');
+ value = { ...value, [key]: v };
+ customized.add(key);
+ },
+ );
+ const reset = vi.fn(() => {
+ if (overrides?.resetThrows) throw new Error('EROFS: /internal/abs/path readonly');
+ value = { ...DEFAULTS };
+ customized.clear();
+ return value;
+ });
+ const ipc = createAgentResourceSettingsIpc({
+ assertTrustedSender,
+ readState: () => ({
+ value: { ...value },
+ isCustomized: customized.size > 0,
+ defaults: { ...DEFAULTS },
+ customizedKeys: [...customized],
+ }),
+ write,
+ reset,
+ });
+ return { ipc, assertTrustedSender, write, reset };
+}
+
+const EVENT = { senderFrame: 'fake' };
+
+describe('agent resource settings IPC business body', () => {
+ it('rejects untrusted senders on all three routes before any side effect', () => {
+ const untrusted = () => {
+ throw new Error('untrusted sender');
+ };
+ const { ipc, write, reset } = makeIpc({ assertTrustedSender: untrusted });
+ expect(() => ipc.get(EVENT)).toThrow('untrusted sender');
+ expect(() => ipc.set(EVENT, { key: 'maxConcurrentCommands', value: 2 })).toThrow(
+ 'untrusted sender',
+ );
+ expect(() => ipc.reset(EVENT)).toThrow('untrusted sender');
+ expect(write).not.toHaveBeenCalled();
+ expect(reset).not.toHaveBeenCalled();
+ });
+
+ it('returns the wire shape with defaults and customization state', () => {
+ const { ipc } = makeIpc();
+ expect(ipc.get(EVENT)).toEqual({
+ ...DEFAULTS,
+ isCustomized: false,
+ customizedKeys: [],
+ defaults: DEFAULTS,
+ });
+ const next = ipc.set(EVENT, { key: 'processPriority', value: 'low' });
+ expect(next.processPriority).toBe('low');
+ expect(next.isCustomized).toBe(true);
+ expect(next.customizedKeys).toEqual(['processPriority']);
+ });
+
+ it.each([
+ [{ key: 'nope', value: 1 }, 'unknown key'],
+ [{}, 'key required'],
+ [{ key: 'maxConcurrentCommands', value: '5' }, 'must be an integer'],
+ [{ key: 'maxConcurrentCommands', value: 3.5 }, 'must be an integer'],
+ [{ key: 'maxConcurrentCommands', value: -1 }, 'must be >= 0'],
+ [{ key: 'maxConcurrentCommands', value: 65 }, 'must be <= 64'],
+ [{ key: 'processPriority', value: 'turbo' }, 'must be one of'],
+ [{ key: 'processPriority', value: 19 }, 'must be one of'],
+ [{ key: 'capToolchainThreads', value: 1 }, 'must be a boolean'],
+ [{ key: 'capToolchainThreads', value: 'yes' }, 'must be a boolean'],
+ ])('hard-rejects invalid payload %j with INVALID_PARAMS', (body, messagePart) => {
+ const { ipc, write } = makeIpc();
+ expect(() => ipc.set(EVENT, body)).toThrow(`[INVALID_PARAMS]`);
+ expect(() => ipc.set(EVENT, body)).toThrow(messagePart);
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['maxConcurrentCommands', 0],
+ ['maxConcurrentCommands', 64],
+ ['processPriority', 'lowest'],
+ ['capToolchainThreads', true],
+ ] as const)('accepts boundary/valid value %s=%j', (key, value) => {
+ const { ipc } = makeIpc();
+ const next = ipc.set(EVENT, { key, value });
+ expect(next[key]).toBe(value);
+ });
+
+ it('converts store write failures to [INTERNAL] without leaking fs details', () => {
+ const { ipc } = makeIpc({ writeThrows: true });
+ let caught: Error | null = null;
+ try {
+ ipc.set(EVENT, { key: 'maxConcurrentCommands', value: 2 });
+ } catch (err) {
+ caught = err as Error;
+ }
+ expect(caught?.message).toContain('[INTERNAL]');
+ // 原始 fs 异常里的内部绝对路径不得透出
+ expect(caught?.message).not.toContain('/internal/abs/path');
+ });
+
+ it('converts store reset failures to [INTERNAL] without leaking fs details', () => {
+ const { ipc } = makeIpc({ resetThrows: true });
+ let caught: Error | null = null;
+ try {
+ ipc.reset(EVENT);
+ } catch (err) {
+ caught = err as Error;
+ }
+ expect(caught?.message).toContain('[INTERNAL]');
+ expect(caught?.message).not.toContain('/internal/abs/path');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-resource-settings-ipc.ts b/apps/desktop/src/main/maker-ipc/agent-resource-settings-ipc.ts
new file mode 100644
index 0000000000..2554dbd153
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/agent-resource-settings-ipc.ts
@@ -0,0 +1,113 @@
+/**
+ * agent-resource-settings IPC 业务体 —— 与 ipcMain adapter 分离,依赖可注入,
+ * 免 Electron 直测三类路径:sender 可信校验、逐 key 运行时校验、存储失败转
+ * INTERNAL(engineering-conventions §3:main 侧业务逻辑默认带测试)。
+ *
+ * register.ts 只做 adapter:ipcMain.handle(channel, (e, body) => ipc.xxx(e, body))。
+ */
+
+import {
+ MAX_CONCURRENT_COMMANDS_CAP,
+ type AgentResourceSettings,
+} from '../maker-host/agent-resource-settings-store.js';
+import type { OverrideSettingsState } from '../maker-host/override-settings-file.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+const AGENT_RESOURCE_SETTING_KEYS = [
+ 'maxConcurrentCommands',
+ 'processPriority',
+ 'capToolchainThreads',
+] as const;
+export type AgentResourceSettingKey = (typeof AGENT_RESOURCE_SETTING_KEYS)[number];
+const AGENT_RESOURCE_PRIORITIES = ['normal', 'low', 'lowest'] as const;
+
+export interface AgentResourceSettingsIpcDeps {
+ /** 校验事件来自可信应用 renderer;不可信时抛错。写路径会持久改变 agent 行为,属特权 IPC。 */
+ assertTrustedSender: (event: unknown) => void;
+ readState: () => OverrideSettingsState<AgentResourceSettings>;
+ write: (
+ key: keyof AgentResourceSettings,
+ value: AgentResourceSettings[keyof AgentResourceSettings],
+ ) => void;
+ reset: () => AgentResourceSettings;
+}
+
+function isAgentResourceSettingKey(key: unknown): key is AgentResourceSettingKey {
+ return typeof key === 'string'
+ && (AGENT_RESOURCE_SETTING_KEYS as readonly string[]).includes(key);
+}
+
+/** store 层 clamp 容错读盘;IPC 写路径按惯例硬拒非法值(INVALID_PARAMS)。 */
+function validateAgentResourceSettingValue(
+ key: AgentResourceSettingKey,
+ value: unknown,
+): AgentResourceSettings[AgentResourceSettingKey] {
+ if (key === 'maxConcurrentCommands') {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {
+ throwIpcError('INVALID_PARAMS', `${key} must be an integer`);
+ }
+ if (value < 0) throwIpcError('INVALID_PARAMS', `${key} must be >= 0`);
+ if (value > MAX_CONCURRENT_COMMANDS_CAP) {
+ throwIpcError('INVALID_PARAMS', `${key} must be <= ${MAX_CONCURRENT_COMMANDS_CAP}`);
+ }
+ return value;
+ }
+ if (key === 'processPriority') {
+ if (typeof value !== 'string'
+ || !(AGENT_RESOURCE_PRIORITIES as readonly string[]).includes(value)) {
+ throwIpcError('INVALID_PARAMS', `${key} must be one of ${AGENT_RESOURCE_PRIORITIES.join('/')}`);
+ }
+ return value as AgentResourceSettings['processPriority'];
+ }
+ if (typeof value !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', `${key} must be a boolean`);
+ }
+ return value;
+}
+
+export function createAgentResourceSettingsIpc(deps: AgentResourceSettingsIpcDeps) {
+ const wire = () => {
+ const state = deps.readState();
+ return {
+ ...state.value,
+ isCustomized: state.isCustomized,
+ customizedKeys: state.customizedKeys,
+ defaults: state.defaults,
+ };
+ };
+
+ return {
+ get(event: unknown) {
+ deps.assertTrustedSender(event);
+ return wire();
+ },
+
+ set(event: unknown, body: unknown) {
+ deps.assertTrustedSender(event);
+ const b = body as Record<string, unknown> | null | undefined;
+ if (!b || typeof b.key !== 'string') throwIpcError('INVALID_PARAMS', 'key required');
+ if (!isAgentResourceSettingKey(b.key)) {
+ throwIpcError('INVALID_PARAMS', `unknown key: ${b.key}`);
+ }
+ const value = validateAgentResourceSettingValue(b.key, b.value);
+ try {
+ deps.write(b.key, value);
+ } catch {
+ // 落盘失败(只读目录/磁盘满等):按 IPC 错误协议包装,不把原始 fs 异常
+ // (含内部绝对路径)透给 renderer。
+ throwIpcError('INTERNAL', 'agent resource settings write failed');
+ }
+ return wire();
+ },
+
+ reset(event: unknown) {
+ deps.assertTrustedSender(event);
+ try {
+ deps.reset();
+ } catch {
+ throwIpcError('INTERNAL', 'agent resource settings reset failed');
+ }
+ return wire();
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 92dcb20e53..5b600c7b1a 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -522,6 +522,9 @@ export const MAKER_INVOKE = {
COLLABORATION_SETTINGS_GET: 'maker:collaboration-settings:get',
COLLABORATION_SETTINGS_SET: 'maker:collaboration-settings:set',
COLLABORATION_SETTINGS_RESET: 'maker:collaboration-settings:reset',
+ AGENT_RESOURCE_SETTINGS_GET: 'maker:agent-resource-settings:get',
+ AGENT_RESOURCE_SETTINGS_SET: 'maker:agent-resource-settings:set',
+ AGENT_RESOURCE_SETTINGS_RESET: 'maker:agent-resource-settings:reset',
// Plugin system (Phase 1)
PLUGINS_LIST: 'maker:plugins:list',
// Read one plugin's enable state by id — works for plugins hidden from
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 357318379a..7067840962 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -178,6 +178,12 @@ import {
resetCollaborationSettings,
writeCollaborationSetting,
} from '../maker-host/collaboration-settings-store.js';
+import {
+ readAgentResourceSettingsState,
+ resetAgentResourceSettings,
+ writeAgentResourceSetting,
+} from '../maker-host/agent-resource-settings-store.js';
+import { createAgentResourceSettingsIpc } from './agent-resource-settings-ipc.js';
import { createGitSnapshotCoordinator } from '../maker-host/git-snapshot-host.js';
import {
cancelCodexAuthModeChange,
@@ -723,6 +729,17 @@ function collaborationSettingsWire() {
};
}
+// agent-resource-settings 的 key 白名单/校验/wire 组装已抽到
+// agent-resource-settings-ipc.ts(可注入依赖免 Electron 直测,含 sender 校验、
+// 逐 key 校验、存储失败转 INTERNAL 的全套测试)。这里只保留 adapter 接线。
+const agentResourceSettingsIpc = createAgentResourceSettingsIpc({
+ assertTrustedSender: (event) =>
+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),
+ readState: readAgentResourceSettingsState,
+ write: writeAgentResourceSetting,
+ reset: resetAgentResourceSettings,
+});
+
function memorySettingsWire() {
const state = readMemorySettingsState();
return {
@@ -6525,6 +6542,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return collaborationSettingsWire();
});
+ // ─── Agent resource settings IPC(命令并发/进程优先级/工具链限核)──────────
+ // 业务体在 agent-resource-settings-ipc.ts(sender 校验/逐 key 校验/存储失败
+ // 转 INTERNAL),这里是纯 adapter。
+ ipcMain.handle(MAKER_INVOKE.AGENT_RESOURCE_SETTINGS_GET, async (e) =>
+ agentResourceSettingsIpc.get(e),
+ );
+ ipcMain.handle(MAKER_INVOKE.AGENT_RESOURCE_SETTINGS_SET, async (e, body: unknown) =>
+ agentResourceSettingsIpc.set(e, body),
+ );
+ ipcMain.handle(MAKER_INVOKE.AGENT_RESOURCE_SETTINGS_RESET, async (e) =>
+ agentResourceSettingsIpc.reset(e),
+ );
+
// ─── Idle watcher ────────────────────────────────────────────────────────
// 只扫描 active team/session,避免已归档 Worker 被终态筛选重新捞起。
idleReleaseWatcher?.stop();
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 69c45c22a0..5a57ca0a9b 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4463,6 +4463,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
subagentModelSettingsReset: (): Promise<SubagentModelSettingsState> =>
ipcRenderer.invoke('maker:subagent-model-settings:reset'),
+ // Agent 资源占用治理(命令并发上限/进程优先级/工具链限核)。
+ // 并发上限即刻生效;优先级降档对在跑 agent 进程约 15s 内生效(watcher 轮询);
+ // 调回 normal 与限核 env 只对新启动的 agent 进程生效。
+ agentResourceSettingsGet: (): Promise<unknown> =>
+ ipcRenderer.invoke('maker:agent-resource-settings:get'),
+ agentResourceSettingsSet: (key: string, value: number | string | boolean): Promise<unknown> =>
+ ipcRenderer.invoke('maker:agent-resource-settings:set', { key, value }),
+ agentResourceSettingsReset: (): Promise<unknown> =>
+ ipcRenderer.invoke('maker:agent-resource-settings:reset'),
+
silentEncryptedRetryGet: (): Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }> =>
ipcRenderer.invoke('maker:silent-encrypted-retry:get'),
silentEncryptedRetrySet: (enabled: boolean): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }> =>
diff --git a/apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx b/apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx
new file mode 100644
index 0000000000..ce3cd2dd49
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx
@@ -0,0 +1,330 @@
+/**
+ * AgentResourceSection — Agent 资源占用设置(命令并发上限/进程优先级/工具链限核)。
+ *
+ * 三档预设(全速/均衡/后台)只是三个底层字段的组合快捷方式,不单独持久化档位名;
+ * 字段与任何预设组合都不匹配时,预设条不高亮(= 自定义状态)。
+ * 均衡档的并发值按本机核数派生,换机器后读出的旧值可能不再匹配预设 —— 属预期,
+ * 显示为自定义即可,不做迁移。
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { Switch } from '@/components/ui/switch';
+import { cn } from '@/lib/utils';
+import { toast } from '@/lib/toast';
+import { DefaultOverrideControls } from './DefaultOverrideControls';
+
+type Wire = AgentResourceSettingsWire;
+type SettingKey = 'maxConcurrentCommands' | 'processPriority' | 'capToolchainThreads';
+
+type PresetId = 'full' | 'balanced' | 'background';
+
+const PRIORITY_OPTIONS: AgentResourceProcessPriority[] = ['normal', 'low', 'lowest'];
+const MAX_CONCURRENT_CAP = 64;
+
+/**
+ * 均衡档并发值:本机核数的一半,至少 2(与 main 侧 toolchain-thread-cap 的口径一致),
+ * 且不超过 IPC 校验上限 —— 超高核数工作站(>128 核)算出的值若越过 cap,首个 IPC 写
+ * 会被硬拒,预设应用直接失败(bot review P1)。
+ */
+function balancedConcurrency(): number {
+ const cores =
+ typeof navigator !== 'undefined' && navigator.hardwareConcurrency
+ ? navigator.hardwareConcurrency
+ : 8;
+ return Math.min(MAX_CONCURRENT_CAP, Math.max(2, Math.ceil(cores / 2)));
+}
+
+function presetValues(id: PresetId): Pick<Wire, SettingKey> {
+ switch (id) {
+ case 'full':
+ return { maxConcurrentCommands: 0, processPriority: 'normal', capToolchainThreads: false };
+ case 'balanced':
+ return {
+ maxConcurrentCommands: balancedConcurrency(),
+ processPriority: 'low',
+ capToolchainThreads: true,
+ };
+ case 'background':
+ return { maxConcurrentCommands: 2, processPriority: 'lowest', capToolchainThreads: true };
+ }
+}
+
+function matchPreset(s: Pick<Wire, SettingKey>): PresetId | null {
+ for (const id of ['full', 'balanced', 'background'] as const) {
+ const p = presetValues(id);
+ if (
+ s.maxConcurrentCommands === p.maxConcurrentCommands &&
+ s.processPriority === p.processPriority &&
+ s.capToolchainThreads === p.capToolchainThreads
+ ) {
+ return id;
+ }
+ }
+ return null;
+}
+
+export function AgentResourceSection() {
+ const { t } = useTranslation();
+ const [settings, setSettings] = useState<Wire | null>(null);
+ // 预设三键写入的 in-flight 闸:防并发点击交错出"杂交档位"落盘。
+ const [applyingPreset, setApplyingPreset] = useState(false);
+ // 并发上限输入框的本地草稿:一切编辑中间态(清空、"10"删掉首位剩"0"等)都
+ // 只进草稿,blur/Enter 才校验提交 —— 任何 onChange 即写盘的变体都会把中间值
+ // 瞬态落成"0=不限"并放行排队命令(bot review 连续四轮触碰同一根因,改为
+ // 提交制一次收口)。
+ const [maxDraft, setMaxDraft] = useState<string | null>(null);
+ // 写序号:每次以写类 IPC 响应落地 settings 时 +1。失败回读的 GET 是异步的,
+ // 且发起后操作闸已解除 —— 期间用户的成功修改不能被迟到的旧 GET 快照覆盖,
+ // 回读响应只在序号未前进时生效(bot review P1)。
+ const writeSeqRef = useRef(0);
+
+ const applyServerState = (next: Wire) => {
+ writeSeqRef.current += 1;
+ setSettings(next);
+ };
+
+ useEffect(() => {
+ void window.electronAPI.maker
+ .agentResourceSettingsGet()
+ .then((s) => {
+ if (s && typeof s.maxConcurrentCommands === 'number') setSettings(s);
+ })
+ .catch(() => {
+ // 读失败时按默认态渲染,写路径仍可用(main 侧会兜底校验)
+ setSettings({
+ maxConcurrentCommands: 0,
+ processPriority: 'normal',
+ capToolchainThreads: false,
+ isCustomized: false,
+ customizedKeys: [],
+ defaults: {
+ maxConcurrentCommands: 0,
+ processPriority: 'normal',
+ capToolchainThreads: false,
+ },
+ });
+ });
+ }, []);
+
+ const activePreset = useMemo(() => (settings ? matchPreset(settings) : null), [settings]);
+
+ /**
+ * 写失败后从 main 重新拉权威状态,替换乐观值 —— UI 与磁盘不留分叉。
+ * 迟到守卫:发起后若有新的写响应落地(写序号前进),本次回读结果作废,
+ * 不覆盖用户随后的成功修改。
+ */
+ const refetchAuthoritative = () => {
+ const seqAtIssue = writeSeqRef.current;
+ void window.electronAPI.maker
+ .agentResourceSettingsGet()
+ .then((s) => {
+ if (writeSeqRef.current === seqAtIssue) setSettings(s);
+ })
+ .catch(() => {});
+ };
+
+ const persist = (key: SettingKey, value: number | string | boolean) => {
+ if (applyingPreset) return; // 预设三键序列在途时所有控件已禁用,这里兜底防交错
+ setSettings((prev) => (prev ? { ...prev, [key]: value, isCustomized: true } : prev));
+ void window.electronAPI.maker
+ .agentResourceSettingsSet(key, value)
+ .then((next) => applyServerState(next))
+ .catch(() => {
+ // IPC 错误统一显示本地化文案,不透出原始异常(可能含内部路径)
+ toast.error(t('settings.agentResource.saveFailed'));
+ refetchAuthoritative();
+ });
+ };
+
+ const applyPreset = async (id: PresetId) => {
+ if (applyingPreset) return; // 三键序列非原子,靠 in-flight 闸禁止交错
+ setApplyingPreset(true);
+ setMaxDraft(null); // 预设接管并发值,废弃输入框草稿
+ const values = presetValues(id);
+ setSettings((prev) => (prev ? { ...prev, ...values } : prev));
+ try {
+ await window.electronAPI.maker.agentResourceSettingsSet(
+ 'maxConcurrentCommands',
+ values.maxConcurrentCommands,
+ );
+ await window.electronAPI.maker.agentResourceSettingsSet(
+ 'processPriority',
+ values.processPriority,
+ );
+ const next = await window.electronAPI.maker.agentResourceSettingsSet(
+ 'capToolchainThreads',
+ values.capToolchainThreads,
+ );
+ applyServerState(next);
+ } catch {
+ // 中途失败 = 只落了部分字段;拉回权威状态,不让乐观值假装写成功了
+ toast.error(t('settings.agentResource.saveFailed'));
+ refetchAuthoritative();
+ } finally {
+ setApplyingPreset(false);
+ }
+ };
+
+ // 取数时序契约(engineering-conventions §7):本地 IPC 数据毫秒级到达,获取期间
+ // 界面不发生变化、不做 loading 态 —— 瞬时占位行会在数据到达时被更高的控件顶开,
+ // 造成后续 section 可见位移。
+ if (!settings) return null;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">
+ {t('settings.agentResource.title')}
+ </h2>
+ <DefaultOverrideControls
+ isCustomized={Boolean(settings.isCustomized)}
+ disabled={applyingPreset}
+ onReset={() => {
+ if (applyingPreset) return;
+ void window.electronAPI.maker
+ .agentResourceSettingsReset()
+ .then((next) => {
+ applyServerState(next);
+ toast.success(t('settings.defaults.restored'));
+ })
+ .catch(() => {
+ toast.error(t('settings.defaults.restoreFailed'));
+ });
+ }}
+ />
+ </div>
+
+ <p className="text-11 leading-relaxed text-[var(--text-tertiary)]">
+ {t('settings.agentResource.description')}
+ </p>
+
+ {/* 预设条:三个字段的组合快捷方式;都不匹配 = 自定义,均不高亮 */}
+ <div className="flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-primary)]">
+ {t('settings.agentResource.preset')}
+ </span>
+ <div
+ role="radiogroup"
+ aria-label={t('settings.agentResource.preset')}
+ className="flex w-fit shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5"
+ >
+ {(['full', 'balanced', 'background'] as const).map((id) => {
+ const active = activePreset === id;
+ return (
+ <button
+ key={id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={applyingPreset}
+ onClick={() => void applyPreset(id)}
+ className={cn(
+ 'rounded-full px-2.5 py-1 text-xs transition-colors',
+ active
+ ? 'bg-[var(--chat-input-chip-bg)] font-medium text-[var(--msg-assistant-text)]'
+ : 'text-[var(--settings-section-sublabel)] hover:bg-sidebar-item-hover',
+ applyingPreset && 'opacity-60',
+ )}
+ >
+ {t(`settings.agentResource.presets.${id}`)}
+ </button>
+ );
+ })}
+ </div>
+ <span className="text-11 text-[var(--text-tertiary)]">
+ {activePreset
+ ? t(`settings.agentResource.presetHints.${activePreset}`)
+ : t('settings.agentResource.presetHints.custom')}
+ </span>
+ </div>
+
+ {/* 并发命令上限 */}
+ <label className="flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-primary)]">
+ {t('settings.agentResource.maxConcurrent')}
+ </span>
+ <span className="text-11 text-[var(--text-tertiary)]">
+ {t('settings.agentResource.maxConcurrentHint')}
+ </span>
+ <input
+ type="number"
+ min={0}
+ max={MAX_CONCURRENT_CAP}
+ disabled={applyingPreset}
+ value={maxDraft ?? String(settings.maxConcurrentCommands)}
+ onChange={(e) => setMaxDraft(e.target.value)}
+ onBlur={() => {
+ // 唯一提交点(DESIGN §14.3:Settings 单行编辑器 Enter 不得提交):
+ // 仅 0..64 的整数且与当前值不同才写盘;非法/未变草稿作废,
+ // 回显权威值(clamp 会绕过 main 侧硬拒语义,一律拒绝不改写)
+ const text = (maxDraft ?? '').trim();
+ setMaxDraft(null);
+ if (!/^\d+$/.test(text)) return;
+ const raw = Number(text);
+ if (raw > MAX_CONCURRENT_CAP) return;
+ if (raw === settings.maxConcurrentCommands) return;
+ persist('maxConcurrentCommands', raw);
+ }}
+ className="mt-0.5 w-24 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-1.5 text-13 text-[var(--settings-input-text)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
+ />
+ </label>
+
+ {/* 进程优先级 */}
+ <div className="flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-primary)]">
+ {t('settings.agentResource.priority')}
+ </span>
+ <span className="text-11 text-[var(--text-tertiary)]">
+ {t('settings.agentResource.priorityHint')}
+ </span>
+ <div
+ role="radiogroup"
+ aria-label={t('settings.agentResource.priority')}
+ className="mt-0.5 flex w-fit shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5"
+ >
+ {PRIORITY_OPTIONS.map((tier) => {
+ const active = settings.processPriority === tier;
+ return (
+ <button
+ key={tier}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={applyingPreset}
+ onClick={() => persist('processPriority', tier)}
+ className={cn(
+ 'rounded-full px-2.5 py-1 text-xs transition-colors',
+ active
+ ? 'bg-[var(--chat-input-chip-bg)] font-medium text-[var(--msg-assistant-text)]'
+ : 'text-[var(--settings-section-sublabel)] hover:bg-sidebar-item-hover',
+ )}
+ >
+ {t(`settings.agentResource.priorityOptions.${tier}`)}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* 工具链限核 */}
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col gap-1.5">
+ <span className="text-12 font-medium text-[var(--text-primary)]">
+ {t('settings.agentResource.capThreads')}
+ </span>
+ <span className="text-11 text-[var(--text-tertiary)]">
+ {t('settings.agentResource.capThreadsHint')}
+ </span>
+ </div>
+ <Switch
+ checked={settings.capToolchainThreads}
+ disabled={applyingPreset}
+ onCheckedChange={(next) => persist('capToolchainThreads', next)}
+ aria-label={t('settings.agentResource.capThreads')}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index babf32f7ec..0fc697b487 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -33,6 +33,7 @@ import { GitSafetySection } from './GitSafetySection';
import { SessionImportSection } from './SessionImportSection';
import { HelpSection } from './HelpSection';
import { HelpAssistantPanel } from './HelpAssistantPanel';
+import { AgentResourceSection } from './AgentResourceSection';
import { CollaborationSection } from './CollaborationSection';
import { BuiltinToolsSection } from './BuiltinToolsSection';
import { ContactsSection } from './contacts/ContactsSection';
@@ -316,6 +317,16 @@ export function SettingsView() {
<CollaborationSection />
</section>
+ {/* Section — Agent resource usage (命令并发/进程优先级/工具链限核)。
+ 与 Collaboration(worker 上限)相邻:同属"agent 吃多少机器资源"的治理面。 */}
+ <section
+ id="settings-agent-resource"
+ className="py-[18px]"
+ aria-label={t('settings.sections.agentResource')}
+ >
+ <AgentResourceSection />
+ </section>
+
{/* Section — Git safety savepoints (formal setting, not experimental). */}
<section className="py-[18px]" aria-label={t('settings.sections.gitSafety')}>
<GitSafetySection />
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AgentResourceSectionRendering.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AgentResourceSectionRendering.test.tsx
new file mode 100644
index 0000000000..107bc90a6c
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AgentResourceSectionRendering.test.tsx
@@ -0,0 +1,289 @@
+// @vitest-environment jsdom
+
+/**
+ * Agent 资源占用设置面板的渲染与交互回归:
+ * 1. 默认态(全速)下预设条高亮 full,三个字段回显默认值;
+ * 2. 点预设按三键顺序写入组合值(maxConcurrentCommands → processPriority →
+ * capToolchainThreads),UI 用最后一次返回的 wire 状态;
+ * 3. 与任何预设不匹配的值组合 → 预设条不高亮,提示 custom;
+ * 4. 单字段修改走 agentResourceSettingsSet 且不写档位名。
+ */
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentResourceSection } from '../AgentResourceSection';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@/components/ui/switch', () => ({
+ Switch: (props: { checked: boolean; onCheckedChange: (next: boolean) => void; ['aria-label']?: string }) => (
+ <button
+ role="switch"
+ aria-checked={props.checked}
+ aria-label={props['aria-label']}
+ onClick={() => props.onCheckedChange(!props.checked)}
+ />
+ ),
+}));
+
+type WireShape = {
+ maxConcurrentCommands: number;
+ processPriority: 'normal' | 'low' | 'lowest';
+ capToolchainThreads: boolean;
+ isCustomized: boolean;
+ customizedKeys: string[];
+ defaults: {
+ maxConcurrentCommands: number;
+ processPriority: 'normal' | 'low' | 'lowest';
+ capToolchainThreads: boolean;
+ };
+};
+
+const DEFAULT_WIRE: WireShape = {
+ maxConcurrentCommands: 0,
+ processPriority: 'normal',
+ capToolchainThreads: false,
+ isCustomized: false,
+ customizedKeys: [],
+ defaults: { maxConcurrentCommands: 0, processPriority: 'normal', capToolchainThreads: false },
+};
+
+function installElectronApi(initial: WireShape) {
+ let current = { ...initial };
+ const settingsGet = vi.fn(async () => current);
+ const settingsSet = vi.fn(async (key: string, value: number | string | boolean) => {
+ current = { ...current, [key]: value, isCustomized: true };
+ return current;
+ });
+ const settingsReset = vi.fn(async () => {
+ current = { ...DEFAULT_WIRE };
+ return current;
+ });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ agentResourceSettingsGet: settingsGet,
+ agentResourceSettingsSet: settingsSet,
+ agentResourceSettingsReset: settingsReset,
+ },
+ };
+ return { settingsGet, settingsSet, settingsReset };
+}
+
+describe('AgentResourceSection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('renders defaults with the full-speed preset highlighted', async () => {
+ installElectronApi(DEFAULT_WIRE);
+ render(<AgentResourceSection />);
+
+ await waitFor(() => {
+ expect(screen.getByText('settings.agentResource.title')).toBeTruthy();
+ });
+ const fullBtn = screen.getByText('settings.agentResource.presets.full');
+ expect(fullBtn.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('settings.agentResource.presetHints.full')).toBeTruthy();
+ const numberInput = screen.getByRole('spinbutton') as HTMLInputElement;
+ expect(numberInput.value).toBe('0');
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('applies a preset by writing all three fields', async () => {
+ const api = installElectronApi(DEFAULT_WIRE);
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByText('settings.agentResource.presets.background'));
+
+ fireEvent.click(screen.getByText('settings.agentResource.presets.background'));
+
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledTimes(3);
+ });
+ expect(api.settingsSet).toHaveBeenNthCalledWith(1, 'maxConcurrentCommands', 2);
+ expect(api.settingsSet).toHaveBeenNthCalledWith(2, 'processPriority', 'lowest');
+ expect(api.settingsSet).toHaveBeenNthCalledWith(3, 'capToolchainThreads', true);
+ await waitFor(() => {
+ expect(
+ screen
+ .getByText('settings.agentResource.presets.background')
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ });
+ });
+
+ it('shows the custom hint when values match no preset', async () => {
+ installElectronApi({
+ ...DEFAULT_WIRE,
+ maxConcurrentCommands: 7,
+ processPriority: 'lowest',
+ capToolchainThreads: false,
+ isCustomized: true,
+ customizedKeys: ['maxConcurrentCommands', 'processPriority'],
+ });
+ render(<AgentResourceSection />);
+
+ await waitFor(() => {
+ expect(screen.getByText('settings.agentResource.presetHints.custom')).toBeTruthy();
+ });
+ for (const preset of ['full', 'balanced', 'background']) {
+ expect(
+ screen.getByText(`settings.agentResource.presets.${preset}`).getAttribute('aria-checked'),
+ ).toBe('false');
+ }
+ });
+
+ it('refetches authoritative state when a preset write fails mid-sequence', async () => {
+ const api = installElectronApi(DEFAULT_WIRE);
+ // 第 2 键(processPriority)写失败 → 只落了 maxConcurrentCommands
+ api.settingsSet.mockImplementationOnce(async (key: string, value: number | string | boolean) => {
+ return { ...DEFAULT_WIRE, [key]: value, isCustomized: true };
+ });
+ api.settingsSet.mockImplementationOnce(async () => {
+ throw new Error('write failed');
+ });
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByText('settings.agentResource.presets.background'));
+ const getCallsBefore = api.settingsGet.mock.calls.length;
+
+ fireEvent.click(screen.getByText('settings.agentResource.presets.background'));
+
+ // 失败后必须重新拉权威状态,不能让乐观值假装写成功
+ await waitFor(() => {
+ expect(api.settingsGet.mock.calls.length).toBeGreaterThan(getCallsBefore);
+ });
+ });
+
+ it('ignores a second preset click while the first three-key sequence is in flight', async () => {
+ const api = installElectronApi(DEFAULT_WIRE);
+ let releaseFirstWrite: (() => void) | null = null;
+ api.settingsSet.mockImplementationOnce(
+ (key: string, value: number | string | boolean) =>
+ new Promise((resolve) => {
+ releaseFirstWrite = () =>
+ resolve({ ...DEFAULT_WIRE, [key]: value, isCustomized: true });
+ }),
+ );
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByText('settings.agentResource.presets.background'));
+
+ fireEvent.click(screen.getByText('settings.agentResource.presets.background'));
+ fireEvent.click(screen.getByText('settings.agentResource.presets.full')); // in-flight 期间的点击被闸掉
+
+ releaseFirstWrite!();
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledTimes(3); // 只有第一次点击的三键序列
+ });
+ expect(api.settingsSet.mock.calls.map((c) => c[0])).toEqual([
+ 'maxConcurrentCommands',
+ 'processPriority',
+ 'capToolchainThreads',
+ ]);
+ });
+
+ it('discards a late failure-refetch snapshot when a newer write landed meanwhile', async () => {
+ const api = installElectronApi(DEFAULT_WIRE);
+ // 预设第 2 键写失败 → 触发失败回读;把回读 GET 挂起,晚于用户的下一次成功写返回
+ api.settingsSet.mockImplementationOnce(async (key: string, value: number | string | boolean) => {
+ return { ...DEFAULT_WIRE, [key]: value, isCustomized: true };
+ });
+ api.settingsSet.mockImplementationOnce(async () => {
+ throw new Error('write failed');
+ });
+ let releaseStaleGet: (() => void) | null = null;
+ api.settingsGet.mockImplementationOnce(async () => DEFAULT_WIRE); // 初始加载
+ api.settingsGet.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ // 回读返回"失败预设的部分状态"旧快照
+ releaseStaleGet = () => resolve({ ...DEFAULT_WIRE, maxConcurrentCommands: 2 });
+ }),
+ );
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByText('settings.agentResource.presets.background'));
+
+ fireEvent.click(screen.getByText('settings.agentResource.presets.background'));
+ // 等预设序列失败、操作闸解除(回读 GET 仍挂起)
+ await waitFor(() => {
+ expect(api.settingsGet).toHaveBeenCalledTimes(2);
+ });
+
+ // 用户随后的成功修改
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '7' } });
+ fireEvent.blur(screen.getByRole('spinbutton')); // 提交制:blur 落盘
+ await waitFor(() => {
+ expect((screen.getByRole('spinbutton') as HTMLInputElement).value).toBe('7');
+ });
+
+ // 迟到的旧快照返回:必须被丢弃,不得覆盖用户的新值
+ releaseStaleGet!();
+ await new Promise((r) => setTimeout(r, 0));
+ expect((screen.getByRole('spinbutton') as HTMLInputElement).value).toBe('7');
+ });
+
+ it('keeps concurrency edits as draft and only commits valid values on blur', async () => {
+ const api = installElectronApi({
+ ...DEFAULT_WIRE,
+ maxConcurrentCommands: 10,
+ isCustomized: true,
+ });
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByRole('spinbutton'));
+
+ // 编辑中间态一律不写盘:"10"删掉首位剩"0"若被提交,会瞬间解除限制放行排队命令
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '0' } });
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '20' } });
+ expect(api.settingsSet).not.toHaveBeenCalled();
+
+ // blur = 提交点:只落最终值
+ fireEvent.blur(screen.getByRole('spinbutton'));
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledTimes(1);
+ });
+ expect(api.settingsSet).toHaveBeenCalledWith('maxConcurrentCommands', 20);
+
+ // 非法草稿(负值/小数/越界/空)blur 时作废,回显权威值,不写盘
+ for (const bad of ['-1', '3.5', '99', '']) {
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: bad } });
+ fireEvent.blur(screen.getByRole('spinbutton'));
+ }
+ expect(api.settingsSet).toHaveBeenCalledTimes(1);
+ expect((screen.getByRole('spinbutton') as HTMLInputElement).value).toBe('20');
+
+ // 与当前值相同的提交不产生冗余写
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '20' } });
+ fireEvent.blur(screen.getByRole('spinbutton'));
+ expect(api.settingsSet).toHaveBeenCalledTimes(1);
+ });
+
+ it('persists single-field edits through the settings IPC', async () => {
+ const api = installElectronApi(DEFAULT_WIRE);
+ render(<AgentResourceSection />);
+ await waitFor(() => screen.getByRole('spinbutton'));
+
+ fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '5' } });
+ fireEvent.blur(screen.getByRole('spinbutton')); // 提交制:blur 落盘
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledWith('maxConcurrentCommands', 5);
+ });
+
+ fireEvent.click(screen.getByText('settings.agentResource.priorityOptions.low'));
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledWith('processPriority', 'low');
+ });
+
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => {
+ expect(api.settingsSet).toHaveBeenCalledWith('capToolchainThreads', true);
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6eb6ba3509..ee05b4beb8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -115,6 +115,7 @@
"notifications": "Notifications",
"agentIsland": "Agent Island",
"collaboration": "Collaboration",
+ "agentResource": "Agent Resource Usage",
"gitSafety": "Git Safety",
"language": "Language",
"experimental": "Experimental",
@@ -2032,6 +2033,34 @@
"idleRelease": "Idle Release (minutes)",
"idleReleaseHint": "Set 0 to disable background auto-release; positive values release workers after this many idle minutes."
},
+ "agentResource": {
+ "saveFailed": "Failed to save. Try again.",
+ "title": "Agent Resource Usage",
+ "description": "Limit how much system capacity Agent command-line work can consume, so parallel tests or builds don't freeze your machine. Defaults to full speed (no intervention). The concurrency limit applies immediately; priority lowering reaches running Agent processes within about 15 seconds; raising priority back to Normal and toolchain thread caps only apply to newly started Agent processes. Applies to local Agents only; Agents on remote (SSH) machines are not governed by these settings.",
+ "preset": "Profile",
+ "presets": {
+ "full": "Full Speed",
+ "balanced": "Balanced",
+ "background": "Background"
+ },
+ "presetHints": {
+ "full": "No limits (default). Agents use the machine at full speed; when switching back from another profile, Agents already running only fully recover after they restart.",
+ "balanced": "Command queueing + lower priority + toolchain thread caps: Agents keep working while foreground apps always come first.",
+ "background": "Lowest priority (efficiency cores on macOS) + a strict concurrency limit: quiet and responsive, but Agents run noticeably slower.",
+ "custom": "Custom combination. Adjust the fields below directly."
+ },
+ "maxConcurrent": "Concurrent Command Limit",
+ "maxConcurrentHint": "Maximum number of commands the Claude Code engine may run at once; extra commands wait in a queue. 0 means unlimited. Codex commands run inside their own sandbox without a per-command hook and are covered by the priority and thread-cap layers instead.",
+ "priority": "Process Priority",
+ "priorityHint": "Lower it so Agents only use idle capacity and foreground apps stay responsive. Raising it back only applies to newly started Agent processes.",
+ "priorityOptions": {
+ "normal": "Normal",
+ "low": "Low",
+ "lowest": "Lowest"
+ },
+ "capThreads": "Cap Toolchain Parallelism",
+ "capThreadsHint": "Injects environment variables such as VITEST_MAX_FORKS and MAKEFLAGS so a single test or build command can't take every CPU core. Variables you set yourself are never overridden."
+ },
"computerUse": {
"title": "Automation",
"description": "Let agents use your computer and connected devices to get things done for you. Browser automation uses an isolated browser; Android automation uses ADB; computer automation relies on a local driver.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index fea716dc3b..43cb8786e0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -115,6 +115,7 @@
"notifications": "通知",
"agentIsland": "Agent Island",
"collaboration": "コラボレーション",
+ "agentResource": "Agent リソース使用量",
"gitSafety": "Git セーフティ",
"language": "言語",
"experimental": "実験的機能",
@@ -2031,6 +2032,34 @@
"idleRelease": "アイドル解放(分)",
"idleReleaseHint": "0 にするとバックグラウンド自動解放を無効化します。正の値では、その分数だけアイドルだった Worker を自動解放します。"
},
+ "agentResource": {
+ "saveFailed": "保存に失敗しました。もう一度お試しください。",
+ "title": "Agent リソース使用量",
+ "description": "Agent のコマンドライン作業によるシステム負荷を制限し、並列テストやビルドでマシンが固まるのを防ぎます。デフォルトはフルスピード(制限なし)。同時実行上限は即時反映されます。優先度の引き下げは実行中の Agent プロセスにも約 15 秒以内に適用されます。優先度を標準へ戻す操作とツールチェーンのスレッド上限は、新しく起動した Agent プロセスにのみ適用されます。本設定はローカルの Agent にのみ適用され、リモート(SSH)マシン上の Agent には影響しません。",
+ "preset": "プロファイル",
+ "presets": {
+ "full": "フルスピード",
+ "balanced": "バランス",
+ "background": "バックグラウンド"
+ },
+ "presetHints": {
+ "full": "制限なし(デフォルト)。Agent はマシンをフルに使います。他のプロファイルから戻した場合、実行中の Agent は再起動後に完全なフルスピードへ戻ります。",
+ "balanced": "コマンドのキューイング + 低優先度 + ツールチェーンのスレッド上限。Agent は動き続けつつ、前面のアプリが常に優先されます。",
+ "background": "最低優先度(macOS では高効率コア)+ 厳格な同時実行制限。静かで快適になりますが、Agent は明らかに遅くなります。",
+ "custom": "カスタム設定です。下の項目を直接調整できます。"
+ },
+ "maxConcurrent": "同時実行コマンド数の上限",
+ "maxConcurrentHint": "Claude Code エンジンが同時に実行できるコマンド数の上限です。超えた分はキューで待機します。0 は無制限です。Codex のコマンドは自身のサンドボックス内で実行されるためこの上限の対象外で、優先度とスレッド上限でカバーされます。",
+ "priority": "プロセス優先度",
+ "priorityHint": "下げると Agent はアイドルリソースのみを使い、前面のアプリが優先されます。上げ直した場合は新しく起動した Agent プロセスにのみ適用されます。",
+ "priorityOptions": {
+ "normal": "標準",
+ "low": "低",
+ "lowest": "最低"
+ },
+ "capThreads": "ツールチェーンの並列度を制限",
+ "capThreadsHint": "VITEST_MAX_FORKS や MAKEFLAGS などの環境変数を注入し、1 つのテストやビルドが全 CPU コアを占有しないようにします。自分で設定した同名の変数は上書きされません。"
+ },
"computerUse": {
"title": "自動操作",
"description": "エージェントがコンピュータと接続済みデバイスを使ってあなたの代わりに作業します。ブラウザ自動操作は独立したブラウザを使い、Android 自動操作は ADB を使い、コンピュータ自動操作はローカルドライバーに依存します。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 859b60f189..aada31ef19 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -115,6 +115,7 @@
"notifications": "알림",
"agentIsland": "Agent Island",
"collaboration": "협업",
+ "agentResource": "Agent 리소스 사용량",
"gitSafety": "Git 안전",
"language": "언어",
"experimental": "실험적 기능",
@@ -2031,6 +2032,34 @@
"idleRelease": "유휴 해제(분)",
"idleReleaseHint": "0으로 설정하면 백그라운드 자동 해제를 끕니다. 양수 값은 해당 시간(분) 동안 유휴 상태인 Worker 를 자동 해제합니다."
},
+ "agentResource": {
+ "saveFailed": "저장하지 못했습니다. 다시 시도해 주세요.",
+ "title": "Agent 리소스 사용량",
+ "description": "Agent의 명령줄 작업이 시스템 자원을 과도하게 사용하지 않도록 제한하여, 병렬 테스트나 빌드로 컴퓨터가 느려지는 것을 방지합니다. 기본값은 전속력(제한 없음)입니다. 동시 실행 상한은 즉시 적용됩니다. 우선순위 낮추기는 실행 중인 Agent 프로세스에도 약 15초 이내에 적용됩니다. 우선순위를 보통으로 되돌리는 것과 툴체인 스레드 상한은 새로 시작된 Agent 프로세스에만 적용됩니다. 이 설정은 로컬 Agent에만 적용되며, 원격(SSH) 컴퓨터의 Agent에는 적용되지 않습니다.",
+ "preset": "프로필",
+ "presets": {
+ "full": "전속력",
+ "balanced": "균형",
+ "background": "백그라운드"
+ },
+ "presetHints": {
+ "full": "제한 없음(기본값). Agent가 시스템 자원을 최대로 사용합니다. 다른 프로필에서 전환한 경우, 실행 중인 Agent는 재시작 후에야 완전히 전속력으로 돌아갑니다.",
+ "balanced": "명령 대기열 + 낮은 우선순위 + 툴체인 스레드 상한. Agent는 계속 작동하면서도 전면 앱이 항상 우선됩니다.",
+ "background": "최저 우선순위(macOS에서는 효율 코어) + 엄격한 동시 실행 제한. 조용하고 쾌적하지만 Agent는 눈에 띄게 느려집니다.",
+ "custom": "사용자 지정 조합입니다. 아래 항목을 직접 조정할 수 있습니다."
+ },
+ "maxConcurrent": "동시 실행 명령 상한",
+ "maxConcurrentHint": "Claude Code 엔진이 동시에 실행할 수 있는 명령 수의 상한이며, 초과분은 대기열에서 기다립니다. 0은 무제한입니다. Codex 명령은 자체 샌드박스에서 실행되어 이 상한의 적용을 받지 않으며, 우선순위와 스레드 상한으로 보완됩니다.",
+ "priority": "프로세스 우선순위",
+ "priorityHint": "낮추면 Agent는 유휴 자원만 사용하고 전면 앱이 우선됩니다. 다시 높이면 새로 시작된 Agent 프로세스에만 적용됩니다.",
+ "priorityOptions": {
+ "normal": "보통",
+ "low": "낮음",
+ "lowest": "최저"
+ },
+ "capThreads": "툴체인 병렬 처리 제한",
+ "capThreadsHint": "VITEST_MAX_FORKS, MAKEFLAGS 등의 환경 변수를 주입하여 단일 테스트나 빌드 명령이 모든 CPU 코어를 점유하지 않도록 합니다. 직접 설정한 동일한 변수는 덮어쓰지 않습니다."
+ },
"computerUse": {
"title": "자동 조작",
"description": "에이전트가 컴퓨터와 연결된 기기를 사용해 사용자를 대신해 작업합니다. 브라우저 자동화는 독립 브라우저를 사용하고, Android 자동화는 ADB를 사용하며, 컴퓨터 자동화는 로컬 드라이버에 의존합니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e525d7d2bb..02d07140ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -115,6 +115,7 @@
"notifications": "通知",
"agentIsland": "灵动岛",
"collaboration": "协同",
+ "agentResource": "Agent 资源占用",
"gitSafety": "Git 安全",
"language": "语言",
"experimental": "实验性功能",
@@ -2031,6 +2032,34 @@
"idleRelease": "空闲释放(分钟)",
"idleReleaseHint": "设为 0 时关闭后台自动释放;正数表示空闲超过该时长后自动释放。"
},
+ "agentResource": {
+ "saveFailed": "保存失败,请重试。",
+ "title": "Agent 资源占用",
+ "description": "限制 Agent 命令行任务的系统资源占用,避免并行测试、构建把机器拖卡。默认全速(不干预)。并发上限即刻生效;优先级降档对已在跑的 Agent 进程约 15 秒内生效;把优先级调回正常和工具链限核只对新启动的 Agent 进程生效。仅作用于本机 Agent;远端(SSH)机器上的 Agent 不受本设置约束。",
+ "preset": "档位",
+ "presets": {
+ "full": "全速",
+ "balanced": "均衡",
+ "background": "后台"
+ },
+ "presetHints": {
+ "full": "不限制(默认),Agent 全速使用系统资源;从其他档位切回时,已在跑的 Agent 重启后才完全恢复全速。",
+ "balanced": "命令排队 + 低优先级 + 工具链限核:Agent 照常干活,前台操作永远优先。",
+ "background": "最低优先级(macOS 上压到能效核)+ 严格限并发:机器安静流畅,Agent 明显变慢。",
+ "custom": "当前为自定义组合,可直接调节下方各项。"
+ },
+ "maxConcurrent": "并发命令上限",
+ "maxConcurrentHint": "Claude Code 引擎所有命令的并发上限,超出的排队等待;0 表示不限。Codex 命令在自身沙箱内执行、不经此闸门,由优先级与限核层覆盖。",
+ "priority": "进程优先级",
+ "priorityHint": "调低后 Agent 只用空闲资源,前台应用优先。从低档调回后只对新启动的 Agent 进程生效。",
+ "priorityOptions": {
+ "normal": "正常",
+ "low": "低",
+ "lowest": "最低"
+ },
+ "capThreads": "限制工具链并行度",
+ "capThreadsHint": "注入 VITEST_MAX_FORKS、MAKEFLAGS 等环境变量,防止单条测试或构建命令占满全部 CPU 核心;你自己设置过的同名变量不会被覆盖。"
+ },
"computerUse": {
"title": "自动操作",
"description": "让 Agent 使用电脑和已连接设备替你完成任务。浏览器自动化使用独立浏览器;Android 自动化使用 ADB;电脑自动化依赖本机 driver。",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6f54a43576..292982cdcf 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -240,6 +240,21 @@ type ImDefaultSettingsChannel = import('../shared/imDefaultSettings').ImDefaultS
type SubagentModelSettingsPatch = import('../shared/subagentModelSettings').SubagentModelSettingsPatch;
type SubagentModelSettingsState = import('../shared/subagentModelSettings').SubagentModelSettingsState;
+/** Agent 资源占用设置的 IPC wire 形状(main 侧 agentResourceSettingsWire)。 */
+type AgentResourceProcessPriority = 'normal' | 'low' | 'lowest';
+type AgentResourceSettingsWire = {
+ maxConcurrentCommands: number;
+ processPriority: AgentResourceProcessPriority;
+ capToolchainThreads: boolean;
+ isCustomized: boolean;
+ customizedKeys: string[];
+ defaults: {
+ maxConcurrentCommands: number;
+ processPriority: AgentResourceProcessPriority;
+ capToolchainThreads: boolean;
+ };
+};
+
interface VoiceInputShortcut {
trigger?: 'keyboard' | 'modifier';
code: string;
@@ -4250,6 +4265,14 @@ interface ElectronAPI {
subagentModelSettingsSet: (patch: SubagentModelSettingsPatch) => Promise<SubagentModelSettingsState>;
subagentModelSettingsReset: () => Promise<SubagentModelSettingsState>;
+ /** Agent 资源占用治理(命令并发上限/进程优先级/工具链限核)。 */
+ agentResourceSettingsGet: () => Promise<AgentResourceSettingsWire>;
+ agentResourceSettingsSet: (
+ key: 'maxConcurrentCommands' | 'processPriority' | 'capToolchainThreads',
+ value: number | string | boolean,
+ ) => Promise<AgentResourceSettingsWire>;
+ agentResourceSettingsReset: () => Promise<AgentResourceSettingsWire>;
+
/** Silent invalid_encrypted_content recovery setting. */
silentEncryptedRetryGet: () => Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }>;
/** Takes effect immediately for proxy recovery. */