Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(remote-agent): batch startup plugin manifest probes
DavidShenba281d66a34f
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerStartupBatch.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerStartupBatch.test.tsnew file mode 100644index 0000000000..ab8993fe01--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerStartupBatch.test.ts@@ -0,0 +1,112 @@+/**+ * Production startup batch: serial manifest probes must become pipelined native RPCs,+ * without treating existing/denied/unknown paths as absent (remote adaptation contract).+ * Existing mirror tests cover static absence, not speculative replies or invalidation.+ * Minimal input: one manifest metadata query plus out-of-order native replies. Unit tier,+ * no filesystem/socket/process; real process timing is in startupProbe.e2e.test.ts.+ * Standalone measured wall time: 265ms.+ */+import path from 'node:path';+import { pathToFileURL } from 'node:url';++import { describe, expect, it } from 'vitest';++import { createExecServerStartupBatch } from '../host/execServerStartupBatch';++const base = path.resolve('batch-fixture');+const uri = (dir: string, marker = '.codex-plugin') => pathToFileURL(path.join(dir, marker, 'plugin.json')).href;+const query = (id: string | number, target = uri(base), extra = {}) => JSON.stringify({ id, method: 'fs/getMetadata', params: { path: target, ...extra } });+function fixture(shortcut: (data: string) => string | null = () => null) {+ const forwarded: string[] = [];+ const answered: string[] = [];+ const batch = createExecServerStartupBatch({ shortcut, forward: data => forwarded.push(data), answer: data => answered.push(data) });+ const reply = (target: string, value: object) => {+ const request = forwarded.map(data => JSON.parse(data)).find(rpc => rpc.params.path === target);+ expect(request).toBeDefined();+ return batch.response(JSON.stringify({ id: request.id, ...value }));+ };+ return { batch, forwarded, answered, reply };+}++describe('native startup manifest batching', () => {+ it('leaves malformed and unrelated messages to the original transport', () => {+ for (const data of ['null', '{', JSON.stringify({ id: 1, method: 5 }), query(1, 'file://bad-host/path')]) {+ const f = fixture();+ expect(f.batch.request(data)).toBe(false);+ expect(f.forwarded).toEqual([]);+ expect(f.answered).toEqual([]);+ }+ });+ it('pipelines all candidates before receiving a reply and matches out-of-order absence to original ids', () => {+ const f = fixture();+ expect(f.batch.request(query(1))).toBe(true);+ expect(f.forwarded.length).toBeGreaterThan(3);+ expect(f.forwarded.length).toBeLessThanOrEqual(192);+ expect(f.answered).toEqual([]);+ const second = uri(base, '.claude-plugin');+ f.reply(second, { error: { code: -32004, message: 'missing' } });+ expect(f.batch.request(query('second', second))).toBe(true);+ expect(JSON.parse(f.answered[0])).toMatchObject({ id: 'second', error: { code: -32004 } });+ f.reply(uri(base), { error: { code: -32004, message: 'missing' } });+ expect(JSON.parse(f.answered[1])).toMatchObject({ id: 1, error: { code: -32004 } });+ expect(f.batch.response(JSON.stringify({ id: 'unrelated', result: {} }))).toBe(false);+ });++ it.each([+ { result: { isFile: true } },+ { error: { code: -32001, message: 'denied' } },+ { error: { code: -32601, message: 'unsupported' } },+ ])('forwards the original request for existing files and non-NotFound errors: %j', value => {+ const f = fixture();+ const original = query('original');+ f.batch.request(original);+ f.reply(uri(base), value);+ expect(f.forwarded.at(-1)).toBe(original);+ expect(f.answered).toEqual([]);+ expect(f.batch.request(query('again'))).toBe(false);+ });++ it('consumes a large internal error reply and releases the original query', () => {+ const f = fixture();+ const original = query('original');+ expect(f.batch.request(original)).toBe(true);+ // The tunnel permits replies larger than the 16 KiB request optimization budget.+ expect(f.reply(uri(base), { error: { code: -32001, message: 'x'.repeat(20 * 1024) } })).toBe(true);+ expect(f.forwarded.at(-1)).toBe(original);+ expect(f.answered).toEqual([]);+ });++ it('uses the original sandbox and never reuses a result under different permissions or for file content', () => {+ const f = fixture();+ const sandbox = { permissions: 'read-only' };+ f.batch.request(query(1, uri(base), { sandbox }));+ expect(f.forwarded.map(data => JSON.parse(data).params.sandbox)).toEqual(f.forwarded.map(() => sandbox));+ f.reply(uri(base), { error: { code: -32004 } });+ expect(f.batch.request(query(2, uri(base), { sandbox: { permissions: 'other' } }))).toBe(false);+ expect(f.batch.request(JSON.stringify({ id: 3, method: 'fs/readFile', params: { path: uri(base), sandbox } }))).toBe(false);+ expect(f.batch.request(query(4, uri(base), { sandbox }))).toBe(true);+ });++ it.each(['finish', 'fs/writeFile', 'process/start'])('discards negatives and releases held queries on %s, consuming late internal replies', reason => {+ const f = fixture();+ const held = query(1);+ f.batch.request(held);+ const second = uri(base, '.claude-plugin');+ f.reply(second, { error: { code: -32004 } });+ if (reason === 'finish') f.batch.finish();+ else expect(f.batch.request(JSON.stringify({ id: 2, method: reason, params: {} }))).toBe(false);+ expect(f.forwarded.at(-1)).toBe(held);+ expect(f.batch.request(query(3, second))).toBe(false);+ expect(f.reply(uri(base), { error: { code: -32004 } })).toBe(true);+ expect(f.answered).toEqual([]);+ });++ it('does not forward known-absent candidates, and bounds deep ancestry without guessing beyond it', () => {+ const deep = path.join(base, ...Array.from({ length: 80 }, () => 'level'));+ const f = fixture(data => JSON.parse(data).params.path.includes('.cursor-plugin') ? '{}' : null);+ f.batch.request(query(1, uri(deep)));+ expect(f.forwarded).toHaveLength(128);+ expect(f.batch.request(query(2, uri(path.parse(base).root)))).toBe(false);+ expect(f.batch.request(query(3, uri(path.join(base, 'unrelated'))))).toBe(false);+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/startupProbe.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/startupProbe.e2e.test.tsindex 8efd5a7e94..221511fc6d 100644--- a/apps/desktop/src/main/remote-agent/__tests__/startupProbe.e2e.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/startupProbe.e2e.test.ts@@ -22,7 +22,8 @@ import { startRemoteAgentSession } from '../controller/startRemote';import { createRemoteAgentHost } from '../host/runHost';import { hostedStartOptions } from '../host/service';import * as shortcutModule from '../host/execServerShortcut';-import { collectAncestorMarkers } from '../controller/projectFiles';+import * as batchModule from '../host/execServerStartupBatch';+import { collectProjectInstructionFiles as collectProjectFiles, collectAncestorMarkers } from '../controller/projectFiles';import type { StartupExecServerStats } from '../startupTiming';const REPO = path.resolve(__dirname, '../../../../../..');@@ -164,10 +165,14 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {];const original = shortcutModule.createExecServerShortcut;const results = [];- for (const { optimized, delayMs } of [- { optimized: false, delayMs: 0 }, { optimized: true, delayMs: 0 },- { optimized: false, delayMs: 100 }, { optimized: true, delayMs: 100 },+ const originalBatch = batchModule.createExecServerStartupBatch;+ for (const { optimized, delayMs, batched } of [+ { optimized: false, delayMs: 0, batched: false }, { optimized: true, delayMs: 0, batched: false },+ { optimized: false, delayMs: 100, batched: false }, { optimized: true, delayMs: 100, batched: false },+ { optimized: true, delayMs: 0, batched: true },]) {+ const batchSpy = vi.spyOn(batchModule, 'createExecServerStartupBatch').mockImplementation(deps =>+ batched ? originalBatch(deps) : { request: () => false, response: () => false, finish() {} });bodies.length = 0;pluginCalls = 0;let shortcutHits = 0;@@ -179,14 +184,14 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {return reply;};});- const agent = new CodexAgent(codexDeps(path.join(root, `home-${optimized}-${delayMs}`)));+ const agent = new CodexAgent(codexDeps(path.join(root, `home-${optimized}-${delayMs}-${batched}`)));const counts: Record<string, number> = {};let startupStats: StartupExecServerStats | undefined;const host = createRemoteAgentHost({isAgentAvailable: () => true,startHosted: input => agent.startSession(hostedStartOptions(input)),isControllerAuthorized: () => true, captureOwner: () => 'owner', isOwnerCurrent: () => true,- runsRoot: path.join(root, `host-${optimized}-${delayMs}`),+ runsRoot: path.join(root, `host-${optimized}-${delayMs}-${batched}`),log: {info() {}, warn() {},debug(_message, fields) {@@ -227,7 +232,8 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {const durationMs = Math.round(performance.now() - before);const startupCounts = { ...counts };const startupHits = shortcutHits;- expect(startupStats).toMatchObject({ shortcutEnabled: true, connections: 1, answered: startupHits });+ expect(startupStats).toMatchObject({ shortcutEnabled: true, connections: 1 });+ if (!batched) expect(startupStats!.answered).toBe(startupHits);expect(startupStats!.ancestorLevels).toBeGreaterThan(0);const done = (async () => {for await (const event of handle!.events()) {@@ -241,7 +247,7 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {const skillBodyRead = bodies.at(-1)!.includes('QA_SKILL_BODY_SENTINEL');const pluginDiscovered = bodies.at(-1)!.includes('QA_PLUGIN_DISCOVERY_SENTINEL');const pluginCalled = bodies.at(-1)!.includes('QA_PLUGIN_CALL_SENTINEL') && pluginCalls === 1;- results.push({ optimized, delayMs, durationMs, counts: startupCounts, shortcutHits: startupHits, startupStats, skillPresent, skillBodyRead, pluginDiscovered, pluginCalled });+ results.push({ optimized, batched, delayMs, durationMs, counts: startupCounts, shortcutHits: startupHits, startupStats, skillPresent, skillBodyRead, pluginDiscovered, pluginCalled });expect(skillPresent).toBe(true);expect(skillBodyRead).toBe(true);expect(pluginDiscovered).toBe(true);@@ -249,11 +255,88 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {expect(shortcutHits > 0).toBe(optimized);} finally {await handle?.close({ reason: 'navigation' });- await agent.dispose(); host.dispose(); spy.mockRestore();+ await agent.dispose(); host.dispose(); spy.mockRestore(); batchSpy.mockRestore();}}expect(results[1].counts['fs/getMetadata']).toBeLessThan(results[0].counts['fs/getMetadata']);expect(results[3].counts['fs/getMetadata']).toBeLessThan(results[2].counts['fs/getMetadata']);console.log('STARTUP_AB_RESULT', JSON.stringify(results));});++ // Production startup with the same eight-Skill/400ms fixture as the incident investigation.+ // Unlike the causal probe, this uses real native metadata replies, including prefetch cost.+ it('batches eight-Skill startup queries across a delayed transport', { timeout: 240_000 }, async () => {+ const taskHome = path.join(root, 'isolated-task-home');+ fs.mkdirSync(taskHome);+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(taskHome);+ vi.stubEnv('USERPROFILE', taskHome);+ vi.stubEnv('HOME', taskHome);+ const project = path.join(root, 'batch-project');+ fs.mkdirSync(path.join(project, '.git'), { recursive: true });+ for (const tier of ['.agents', '.claude']) for (let i = 0; i < 8; i += 1) {+ const dir = path.join(project, tier, 'skills', `qa-${i}`);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'SKILL.md'), `---\nname: qa-${i}\ndescription: Project startup investigation ${i}\n---\nTest fixture only.\n`);+ }+ const originalShortcut = shortcutModule.createExecServerShortcut;+ // Model the lack of raw absolute-path snapshots across Windows/POSIX; real RPCs still run on Windows.+ const shortcutSpy = vi.spyOn(shortcutModule, 'createExecServerShortcut').mockImplementation(layout =>+ originalShortcut({ ...layout, taskAncestorAbsence: [] }));+ const originalBatch = batchModule.createExecServerStartupBatch;+ const results: Array<{ batched: boolean; durationMs: number; pushes: number; startupStats?: StartupExecServerStats }> = [];+ try {+ for (const [index, batched] of [false, true, false, true].entries()) {+ const batchSpy = vi.spyOn(batchModule, 'createExecServerStartupBatch').mockImplementation(deps =>+ batched ? originalBatch(deps) : { request: () => false, response: () => false, finish() {} });+ const agent = new CodexAgent(codexDeps(path.join(root, `batch-home-${index}`)));+ let startupStats: StartupExecServerStats | undefined;+ const host = createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: input => agent.startSession(hostedStartOptions(input)),+ isControllerAuthorized: () => true, captureOwner: () => 'owner', isOwnerCurrent: () => true,+ runsRoot: path.join(root, `batch-host-${index}`),+ log: { info() {}, warn() {}, debug(_message, fields) {+ if (fields?.side === 'host' && fields?.stage === 'total') startupStats = fields.execServer as StartupExecServerStats;+ } },+ });+ let handle;+ let pushes = 0;+ const before = performance.now();+ try {+ handle = await startRemoteAgentSession('codex', {+ sessionId: randomUUID(), workingDir: project, model: 'gpt-5.5', permissionMode: 'default',+ }, {+ invoke: async args => {+ const req = JSON.parse(JSON.stringify(args[0]));+ if (req.op === 'push') pushes += 1;+ const result = JSON.parse(JSON.stringify(await host.handle('controller-1', req) ?? null));+ // real-wait: manual e2e benchmark includes poll/push latency from the incident probe.+ if (req.op === 'poll' || req.op === 'push') await new Promise(r => setTimeout(r, 400));+ return result;+ },+ rgPath: RG, codexPath: () => CODEX,+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),+ collectProjectFiles, collectAncestorMarkers,+ isGitRepo: async () => true, newId: randomUUID,+ });+ const result = { batched, durationMs: Math.round(performance.now() - before), pushes, startupStats };+ results.push(result);+ console.log('STARTUP_BATCH_RESULT', JSON.stringify(result));+ expect(startupStats?.connections).toBe(1);+ } finally {+ await handle?.close({ reason: 'navigation' });+ await agent.dispose(); host.dispose(); batchSpy.mockRestore();+ }+ }+ for (const index of [0, 2]) {+ // A regression to serial traversal must fail, even if all four startups succeed.+ expect(results[index + 1].pushes).toBeLessThan(results[index].pushes / 2);+ expect(results[index + 1].durationMs).toBeLessThan(results[index].durationMs * 0.7);+ }+ } finally {+ console.log('STARTUP_BATCH_AB_RESULT', JSON.stringify(results));+ shortcutSpy.mockRestore(); homeSpy.mockRestore(); vi.unstubAllEnvs();+ }+ });+});diff --git a/apps/desktop/src/main/remote-agent/host/execServerStartupBatch.ts b/apps/desktop/src/main/remote-agent/host/execServerStartupBatch.tsnew file mode 100644index 0000000000..c9a76707a0--- /dev/null+++ b/apps/desktop/src/main/remote-agent/host/execServerStartupBatch.ts@@ -0,0 +1,139 @@+import { randomUUID } from 'node:crypto';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++import { EXEC_SERVER_NOT_FOUND_CODE } from './execServerShortcut';++const MANIFEST_DIRS = ['.codex-plugin', '.claude-plugin', '.cursor-plugin'];+// Includes the virtual workspace padding and host ancestors; bounded per connection.+const MAX_LEVELS = 64;+const MAX_MESSAGE_CHARS = 16 * 1024;+const READ_ONLY = new Set(['fs/getMetadata', 'fs/canonicalize', 'fs/readFile', 'fs/readDirectory', 'fs/readDir', 'fs/listDirectory', 'fs/walk']);++interface Rpc {+ id?: string | number;+ method?: string;+ params?: Record<string, unknown>;+ error?: { code?: number };+}++function parse(data: string): Rpc | null {+ try {+ const value = JSON.parse(data);+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;+ } catch { return null; }+}++interface BatchDeps {+ shortcut(data: string): string | null;+ forward(data: string): void;+ answer(data: string): void;+}++/**+ * Codex probes three plugin manifests serially up the Skill's ancestry. Pipeline these+ * ordinary metadata RPCs over the existing tunnel; the task's native exec-server still+ * resolves every unknown path and enforces its sandbox. No new wire method or capability.+ * Only native NotFound replies are reused, for this connection's startup and exact params.+ * Existing files, permission failures and unsupported operations are queried normally.+ */+export function createExecServerStartupBatch(deps: BatchDeps) {+ const prefix = `cindy-startup-${randomUUID()}-`;+ const pending = new Map<string, string>(); // internal id -> original file URI+ const absent = new Set<string>();+ const waiters = new Map<string, string[]>();+ let scope: string | undefined;+ let active = true;+ let attempted = false;++ function finish(): void {+ active = false;+ absent.clear();+ for (const messages of waiters.values()) for (const message of messages) deps.forward(message);+ waiters.clear();+ // Retain pending ids until their replies arrive, so synthetic replies never reach Codex.+ }++ function request(data: string): boolean {+ if (!active) return false;+ if (data.length > MAX_MESSAGE_CHARS) { finish(); return false; }+ const rpc = parse(data);+ if (!rpc) { finish(); return false; }+ if (typeof rpc.method !== 'string') return false;+ if (rpc.method === 'process/start' || (rpc.method?.startsWith('fs/') && !READ_ONLY.has(rpc.method))) {+ finish();+ return false;+ }+ if (rpc.method !== 'fs/getMetadata' || (typeof rpc.id !== 'string' && typeof rpc.id !== 'number')) return false;+ const uri = rpc.params?.path;+ if (typeof uri !== 'string' || !uri.startsWith('file://')) return false;+ let target: string;+ try { target = fileURLToPath(uri); } catch { return false; }+ if (path.basename(target) !== 'plugin.json' || !MANIFEST_DIRS.includes(path.basename(path.dirname(target)))) return false;+ const rest = { ...rpc.params };+ delete rest.path;+ const currentScope = JSON.stringify(rest);+ if (attempted && currentScope !== scope) return false;++ if (!attempted) {+ attempted = true;+ scope = currentScope;+ // Build the whole batch before forwarding: even a synchronous test transport may reply.+ const batch: string[] = [];+ let dir = path.dirname(path.dirname(target));+ for (let level = 0; level < MAX_LEVELS; level += 1) {+ for (const marker of MANIFEST_DIRS) {+ const candidate = pathToFileURL(path.join(dir, marker, 'plugin.json')).href;+ const id = `${prefix}${batch.length}`;+ const message = JSON.stringify({ ...rpc, id, params: { ...rpc.params, path: candidate } });+ if (deps.shortcut(message) !== null) continue;+ pending.set(id, candidate);+ batch.push(message);+ }+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ // Match exact URIs; unfamiliar encodings keep their original query semantics.+ const held = [...pending.values()].includes(uri);+ if (held) waiters.set(uri, [data]);+ for (const message of batch) deps.forward(message);+ return held;+ }+ if (absent.has(uri)) {+ deps.answer(JSON.stringify({ id: rpc.id, error: { code: EXEC_SERVER_NOT_FOUND_CODE, message: 'No such file or directory (os error 2)' } }));+ return true;+ }+ if ([...pending.values()].includes(uri)) {+ const messages = waiters.get(uri) ?? [];+ // Native startup is serial; cap retained duplicate queries if a peer misbehaves.+ if (messages.length >= 16) return false;+ messages.push(data);+ waiters.set(uri, messages);+ return true;+ }+ return false;+ }++ function response(data: string): boolean {+ // Replies are already bounded/reassembled by the tunnel. Applying the request+ // optimization limit here would leak internal ids and strand their original queries.+ if (!pending.size) return false;+ const rpc = parse(data);+ if (!rpc || rpc.method !== undefined || typeof rpc.id !== 'string') return false;+ const uri = pending.get(rpc.id);+ if (uri === undefined) return false;+ pending.delete(rpc.id);+ if (active && rpc.error?.code === EXEC_SERVER_NOT_FOUND_CODE) absent.add(uri);+ const messages = waiters.get(uri) ?? [];+ waiters.delete(uri);+ for (const message of messages) {+ if (active && absent.has(uri)) {+ deps.answer(JSON.stringify({ ...rpc, id: parse(message)!.id }));+ } else deps.forward(message);+ }+ return true;+ }++ return { request, response, finish };+}diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 109282324d..82325d9029 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -60,6 +60,7 @@ import { EXEC_SERVER_WS_PATH } from '../controller/execServerRelay';import { RemoteAgentRunClient, type RemoteAgentInvoke, type RemoteAgentPoller } from '../controller/runClient';import { EventLog, waitForAny } from '../eventLog';import { createExecServerShortcut, type ExecServerShortcutLayout } from './execServerShortcut';+import { createExecServerStartupBatch } from './execServerStartupBatch';import { createGuestUsageMeter, type GuestUsageSample } from './guestUsage';import {GROUP_SWITCH_STATE_KEY,@@ -412,6 +413,7 @@ interface Run {closing: boolean;handle?: AgentSessionHandle;tunnel?: RunTunnel;+ execStartupBatches?: Map<string, ReturnType<typeof createExecServerStartupBatch>>;attachmentsDir: string;/** 影子工作区根(按 hostSessionId 复用,任务收尾后清理)。 */workspaceDir?: string;@@ -1302,6 +1304,19 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (wsPath.split('?')[0] === EXEC_SERVER_WS_PATH) {execConns.add(connId);if (!startupComplete) execServerStats.connections += 1;+ if (!startupComplete && shortcut) {+ (run.execStartupBatches ??= new Map()).set(connId, createExecServerStartupBatch({+ shortcut,+ forward: data => {+ if (!startupComplete) execServerStats.forwarded += 1;+ append(run, { t: 'ws', connId, kind: 'message', data });+ },+ answer: data => {+ if (!startupComplete) execServerStats.answered += 1;+ run.tunnel?.sendWs(connId, data);+ },+ }));+ }}append(run, { t: 'ws', connId, kind: 'open', path: wsPath });},@@ -1312,12 +1327,14 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {run.tunnel?.sendWs(connId, local);return;}+ if (run.execStartupBatches?.get(connId)?.request(data)) return;if (!startupComplete && execConns.has(connId)) execServerStats.forwarded += 1;append(run, { t: 'ws', connId, kind: 'message', data });},wsClose: (connId) => {run.localWs?.delete(connId);execConns.delete(connId);+ run.execStartupBatches?.delete(connId);append(run, { t: 'ws', connId, kind: 'close' });},}),@@ -1435,6 +1452,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {await finishRun(run, 'start-failed', 'navigation', false);} finally {startupComplete = true;+ for (const batch of run.execStartupBatches?.values() ?? []) batch.finish();timing.finish(status, execServerStats);}}@@ -1486,6 +1504,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {run.ownerRoute?.release();run.ownerRoute = undefined;await run.tunnel?.close().catch(() => undefined);+ run.execStartupBatches?.clear();await imagePreparation.get(run);run.tunnel = undefined;// 本机这次尝试里已告诉受邀者打开的连接一并关掉(隧道关闭不会逐个回调);中转的连接编号带尝试前缀,不会撞上。@@ -2134,6 +2153,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {run.ownerRoute?.release();run.ownerRoute = undefined;await run.tunnel?.close().catch(() => undefined);+ run.execStartupBatches?.clear();// Native image materialization must finish before the log becomes unreadable.await imagePreparation.get(run);// 收尾事件绕过 closing 判断直接写入。@@ -2945,14 +2965,17 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {// 单条消息拼接上限与反向请求载荷一致,防止无限累积。if (joined.length > REMOTE_AGENT_MAX_PAYLOAD_BYTES) {run.pushParts.delete(frame.connId);+ run.execStartupBatches?.delete(frame.connId);run.tunnel?.closeWs(frame.connId);} else run.pushParts.set(frame.connId, joined);continue;}run.pushParts.delete(frame.connId);- run.tunnel?.sendWs(frame.connId, joined);+ if (!run.execStartupBatches?.get(frame.connId)?.response(joined)) run.tunnel?.sendWs(frame.connId, joined);} else {run.pushParts.delete(frame.connId);+ // closeWs removes its connection before the close event; wsClose will not run.+ run.execStartupBatches?.delete(frame.connId);run.tunnel?.closeWs(frame.connId);}}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 981ae31172..b2117940ec 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1738,6 +1738,17 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加一律原样保留;用户目录对不上时换成 A 本机的(Codex 缺了它会把 `~/…` 规则当解析失败、一律拒绝读取);`file:///C:/…` 是否为盘符按 B 的路径约定(虚拟工作区路径)判断;网络与 Windows 沙箱档位不动。原样转发时两端系统不同会被 A 的 exec-server 拒绝(`invalid sandbox permission path URI`)。+- **Codex 启动清单批量探测(2026-10-29)**:B 在单条 exec-server 连接启动时,把首个插件清单所在+ 目录及其祖先的三种清单检查提前发送(最多 64 层/192 条)。全部仍是旧协议支持的普通+ `fs/getMetadata`,使用独立字符串 ID,保留原 params/sandbox,经 A 的原路径映射和原生执行器;+ 不添加 wire 字段、方法、IPC、权限或能力协商。只有原生 NotFound 可在本次启动复用,已有文件、+ 权限错误、未知目标和不同 sandbox 回落原查询。启动结束或写入/进程启动即停止复用,连接关闭清理;+ 迟到内部回复仅在本连接消费,不重放写操作、不重置 peer/relay、不影响其它任务。+ 新 B 配旧 A 可直接使用;旧 B 保持串行。供应商组与自建中转只转发既有不透明 ws 数据及有界+ poll/push 批次,不解析内部 JSON-RPC ID,因此无需中转、服务端或 Mobile 同步修改,+ 帧大小、鉴权、签名、ACK 和恢复策略不变。回归为 `execServerStartupBatch.test.ts`、+ `startupProbe.e2e.test.ts`、`mirror.test.ts`、`groupRelay.test.ts` 与 `hostLifecycle.test.ts`;+ 真实跨系统及线上分享运行端尚未验收,性能数据与复跑命令见远程适配文档。- **影子目录与配置同步**:`open` 载荷除项目说明文件(含 `.claude/CLAUDE.md`、`.claude/rules`、`.codex/skills`)外还带 `ancestorFiles`(项目上级目录里的`CLAUDE.md` / `CLAUDE.local.md` / `AGENTS.md` / `AGENTS.override.md`,按层级 `up`,最多 24 级)与diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex f3ffb9bf2b..cd6e070a3e 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -718,6 +718,37 @@ Git 元数据查询可以成批并发,不能仅按总查询数推断耗时;本次补齐命中统计与可重复对照;测试还修正了 mock 调用方式,并阻止测试引擎后台同步原生插件目录,避免 Windows 遗留 Git 子进程影响收尾。+2026-10-29 补充:已有短路仍会留下插件清单的串行检查。`host/execServerStartupBatch.ts`+在启动阶段第一次遇到未短路的插件清单 `fs/getMetadata` 时,沿该目录向上最多 64 层,+为三种清单提前发送普通原生查询(最多 192 条,已知不存在的虚拟路径仍由旧短路排除)。+复用既有 poll/push 批次、路径投影和原生 sandbox,不添加协议字段、方法或能力。+只有原生 `-32004` 才能回答同连接、同参数/sandbox 的后续元数据查询;已有文件、权限错误、+未知路径及超出预算的路径继续按原查询处理。不缓存文件内容或成功元数据。+启动结束、出现写操作/启动进程时停止复用并释放等待中的原查询;连接关闭时清理。+内部查询 ID 与原生 ID 隔离,迟到的内部回复不能送给 Codex。每条连接只提前查询一次。+请求的 16 KiB 优化预算不用于回复解析,否则较大错误回复会漏消费内部 ID,并使原查询继续等待。+对端关闭及超限分片主动关连接时显式清理批处理状态,不能依赖不会触发的 `wsClose` 回调。++同日 Windows 隔离基准:真实 Codex 0.159.2、原生 exec-server、生产 Controller/Host,+同一项目 8 个合成 Skill(`.agents` 与 `.claude` 各一份),每次 poll/push 返回增加 400ms。+两侧实际均为 Windows,仅移除原始绝对路径缺失快照,模拟跨系统时不能复用该快照的分支;+不读取真实项目 Skill 或分享者数据,不请求线上模型。仅开关新增批量实现,按关/开/关/开运行:++| 样本 | 批量关闭 | 批量开启 | 回传批次(关闭 → 开启) |+| --- | ---: | ---: | ---: |+| 1 | 24,282ms | 7,469ms | 56 → 15 |+| 2 | 24,214ms | 7,434ms | 56 → 15 |+| 均值 | 24,248ms | 7,451.5ms | 56 → 15 |++启动耗时下降 **69.3%**。真实转发查询仍为 78 条,优化的是串行往返;全部提前查询的实际+处理和回传成本已计入(此前直接复用已知缺失结果的 6.2s 只是因果实验,不是实现后的数字)。+启动本地回答 100 → 142;`forwarded` 包括提前查询,`answered` 包括复用结果,两者相加不再+代表原生 Agent 发起的原始请求总数。完整基准命令:+`pnpm --dir apps/desktop exec vitest run src/main/remote-agent/__tests__/startupProbe.e2e.test.ts -t 'batches eight-Skill' --maxWorkers=1`。+实测测试体 67.02s、含模块加载 107.45s;默认 unit 不运行此手动 e2e。+这证明受控慢链路的因果收益,不承诺现场 95s 变成 7.5s;真实 Windows/macOS 跨设备及原分享供应商仍未验收。+优化需实际运行 Agent 的电脑更新,任务所在电脑和中转可保持旧版。+复跑:`pnpm --dir apps/desktop exec vitest run src/main/remote-agent/__tests__/startupProbe.e2e.test.ts --maxWorkers=1`。该文件登记在手动 e2e tier,真实进程与延迟不进入默认 unit。单文件两组对照实测 56.11s(含加载);最终四组测试体 31.14s,与 roundtrip 合跑共 71.68s。其余相关定向回归 77 通过、1 跳过。