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。

chore(remote-agent): 补齐启动计时与短路命中诊断 (#7257)

DavidShenXD99143af8ab7e
diff --git a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
index 9db5cb755c..4981b30a96 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts
@@ -525,6 +525,11 @@ describe('shadow on the other computer', () => {
write(path.join(project, 'hello.txt'), 'hi');
write(path.join(root, 'work', '.git', 'HEAD'), 'ref: refs/heads/main\n');
write(path.join(root, '.bashrc'), 'export TASK_SHELL_CONFIG=1\n');
+ // Regression: ancestor absence must preserve existing plugin roots, including their files.
+ const pluginMarkers = ['.codex-plugin', '.claude-plugin', '.cursor-plugin'];
+ for (const marker of pluginMarkers) {
+ write(path.join(root, 'work', marker, 'plugin.json'), JSON.stringify({ name: 'qa-plugin' }));
+ }
const inputs: HostedStartInput[] = [];
let stop!: () => void;
const stopped = new Promise<void>((resolve) => { stop = resolve; });
@@ -604,13 +609,17 @@ describe('shadow on the other computer', () => {
{ target: path.join(input.shadowDir, '.git'), local: false },
{ target: path.join(parent, '.git'), local: false },
{ target: path.join(parent, '.git', 'HEAD'), local: false },
+ ...pluginMarkers.flatMap(marker => [
+ { target: path.join(parent, marker, 'plugin.json'), local: false },
+ { target: path.join(root, 'work', marker, 'plugin.json'), local: false },
+ ]),
{ target: path.join(top, 'not-a-marker'), local: false },
{ target: path.join(input.mirrorRoot, 'home', '.agents', 'skills'), local: false },
{ target: path.join(path.parse(input.mirrorRoot).root, 'not-a-cindy-dir', 'tool'), local: false },
// 镜像外的绝对路径会原样交给任务电脑;同一路径下的隐藏文件/已存在标记不能凭点前缀判不存在。
{ target: path.join(root, '.bashrc'), local: false },
{ target: path.join(root, 'work', '.git', 'HEAD'), local: false },
- { target: path.join(root, 'work', '.codex-plugin', 'plugin.json'), local: true },
+ { target: path.join(root, '.codex-plugin', 'plugin.json'), local: true },
{ target: path.join(grandparent, '.git'), local: true },
{ target: path.join(grandparent, '.cursor-plugin', 'plugin.json'), local: true },
{ target: path.join(padded, '.git'), local: true },
diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
index ab5eca409c..85e4af37f4 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts
@@ -185,7 +185,10 @@ afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});
-function createHost(readLimits: () => RemoteAgentLimits = () => DEFAULT_REMOTE_AGENT_LIMITS) {
+function createHost(
+ readLimits: () => RemoteAgentLimits = () => DEFAULT_REMOTE_AGENT_LIMITS,
+ log?: StartRemoteAgentDeps['log'],
+) {
return createRemoteAgentHost({
readLimits,
isAgentAvailable: () => true,
@@ -197,10 +200,117 @@ function createHost(readLimits: () => RemoteAgentLimits = () => DEFAULT_REMOTE_A
captureOwner: () => 'owner',
isOwnerCurrent: () => true,
runsRoot: hostRoot,
+ log,
});
}
describe('remote agent round trip', () => {
+ // 测试价值:真实两端启动入口的诊断协议;此前 24 秒创建等待无阶段记录。
+ // 原覆盖只验证执行结果,未保护成功/失败计时及内容不入日志。最小输入:一次启动或 MCP 拒绝。
+ // tier: unit,沿用本文件 loopback fixture,不启动真实 Agent、不做真实等待。
+ // 本机单文件 Vitest 5.62s(既有 19 项共用 fixture,collect 3.29s;本次两项不另开测试文件)。
+ it('reports controller, transport and host startup stages without configuration contents', async () => {
+ const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() };
+ const host = createHost(undefined, log);
+ let handle: AgentSessionHandle | undefined;
+ try {
+ handle = await startRemoteAgentSession(
+ 'codex',
+ {
+ sessionId: 'startup-timing-task',
+ workingDir: project,
+ model: 'm',
+ userPrompt: 'private user instruction',
+ },
+ { ...makeDeps(host), log },
+ );
+ expect(handle.id).toBe('sdk-session-1');
+ const fields = log.debug.mock.calls.map(([, data]) => data);
+ expect(fields).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ side: 'controller', stage: 'mcp-prepare', status: 'ok' }),
+ expect.objectContaining({ side: 'controller', stage: 'personal-config', status: 'ok' }),
+ expect.objectContaining({
+ side: 'controller',
+ stage: 'capability-handshake',
+ status: 'ok',
+ }),
+ expect.objectContaining({
+ side: 'transport',
+ stage: 'session-ready',
+ status: 'ok',
+ sessionRef: 'startup-',
+ }),
+ expect.objectContaining({
+ side: 'host',
+ stage: 'agent-session',
+ status: 'ok',
+ sessionRef: 'startup-',
+ }),
+ ]),
+ );
+ const transport = fields.find((data) => data.side === 'transport' && data.stage === 'total');
+ expect(fields.find(data => data.side === 'host' && data.stage === 'total')?.execServer).toEqual({
+ shortcutEnabled: true, ancestorLevels: 0, connections: 0, answered: 0, forwarded: 0,
+ });
+ expect(fields).toContainEqual(
+ expect.objectContaining({
+ side: 'host',
+ stage: 'total',
+ status: 'ok',
+ runRef: transport.runRef,
+ }),
+ );
+ const serialized = JSON.stringify(log.debug.mock.calls);
+ for (const secret of [
+ project,
+ 'private user instruction',
+ Buffer.from('# rules').toString('base64'),
+ ]) {
+ expect(serialized).not.toContain(secret);
+ }
+ } finally {
+ await handle?.close();
+ await host.dispose();
+ }
+ });
+
+ it('attributes failed MCP preparation without changing or logging its original error', async () => {
+ const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() };
+ const host = createHost();
+ const failure = new Error('private endpoint credential');
+ try {
+ await expect(
+ startRemoteAgentSession(
+ 'codex',
+ {
+ sessionId: 'startup-failure-task',
+ workingDir: project,
+ model: 'm',
+ },
+ {
+ ...makeDeps(host),
+ log,
+ prepareMcp: async () => {
+ throw failure;
+ },
+ },
+ ),
+ ).rejects.toBe(failure);
+ const fields = log.debug.mock.calls.map(([, data]) => data);
+ expect(fields).toContainEqual(
+ expect.objectContaining({ stage: 'mcp-prepare', status: 'failed' }),
+ );
+ expect(fields).toContainEqual(
+ expect.objectContaining({ side: 'controller', stage: 'total', status: 'failed' }),
+ );
+ expect(fields.some((data) => data.stage === 'capability-handshake')).toBe(false);
+ expect(JSON.stringify(log.debug.mock.calls)).not.toContain(failure.message);
+ } finally {
+ await host.dispose();
+ }
+ });
+
// provider-sharing §9:走 HTTP → 执行器 → Session → 真实交互路由,检查取消卡片及迟到授权。
// 现有往返用例没有挂起确认后取消;最小输入是一次 .env 读取,tier: unit(仅 loopback)。
it.each(['request', 'stop', 'permission', 'close'])('dismisses a shared-provider credential card on %s cancellation', async (end) => {
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.ts
new file mode 100644
index 0000000000..8efd5a7e94
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/startupProbe.e2e.test.ts
@@ -0,0 +1,259 @@
+/**
+ * 测试价值:生产 startRemoteAgentSession → Host → 原生 Codex → 本机 Responses/MCP。
+ * 2026-10-26 一个 Skill 引发 108 次串行插件归属查询;mirror 单测未覆盖原生扫描与启动耗时。
+ * 最小输入:一个项目 Skill,关闭/开启短路,固定链路延迟;查询应减少且 Skill/插件结果完整。
+ * e2e tier:真实进程、socket 与链路延迟;独立文件覆盖 Windows(codexHosted 含 Unix 命令)。
+ * 模型回复和插件业务为 mock;插件 MCP 网关、文件查询与 Codex 引擎是真实实现。
+ * 运行端原生插件按 guest 隔离停用;不替代第三方插件安装或 UI 验收。
+ * 依赖 apps/codex-package-bin 和 ripgrep;缺失时跳过。实测耗时见远程适配文档。
+ */
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+
+import { CodexAgent, type AgentDeps, type Logger } from '@cindy/maker-core';
+import { createCindyGhostsMcpServer, type CindyGhostsMcpDeps } from 'cindy-tools';
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+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 type { StartupExecServerStats } from '../startupTiming';
+
+const REPO = path.resolve(__dirname, '../../../../../..');
+const ARCH = `${process.platform}-${process.arch}`;
+const CODEX = path.join(REPO, 'apps', 'codex-package-bin', ARCH, 'bin', process.platform === 'win32' ? 'codex.exe' : 'codex');
+const RG = path.join(REPO, 'apps', 'ripgrep-bin', ARCH, process.platform === 'win32' ? 'rg.exe' : 'rg');
+const available = fs.existsSync(CODEX) && fs.existsSync(RG);
+
+const noopLogger: Logger = {
+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
+ child: () => noopLogger,
+};
+
+type Step = { kind: 'exec'; cmd: string } | { kind: 'tool'; name: string; args: Record<string, unknown> };
+
+describe.skipIf(!available)('remote agent with a real Codex', () => {
+ let server: Server;
+ let endpoint = '';
+ let root = '';
+ let steps: Step[] = [];
+ const bodies: string[] = [];
+ let pluginCalls = 0;
+ const plugin = {
+ id: 'qa-plugin', name: 'QA plugin', command: 'qa-plugin', recall: 'QA_PLUGIN_DISCOVERY_SENTINEL',
+ tools: [{ name: 'ping', description: 'Return a test value', parameters: { type: 'object' as const } }],
+ };
+ const unsupported = async (): Promise<never> => { throw new Error('Not part of this fixture'); };
+ const pluginDeps: CindyGhostsMcpDeps = {
+ listAwakeGhosts: async () => [plugin],
+ getAwakeGhost: async id => id === plugin.id ? { ok: true, ghost: plugin }
+ : { ok: false, errorCode: 'GHOST_NOT_FOUND', message: 'Unknown test plugin' },
+ readGhostManual: async () => ({ ok: true, manual: [], content: '' }),
+ callGhostTool: async ({ ghostId, tool }) => {
+ if (ghostId !== plugin.id || tool !== 'ping') throw new Error('Wrong plugin route');
+ pluginCalls += 1;
+ return { ok: true, result: { value: 'QA_PLUGIN_CALL_SENTINEL' } };
+ },
+ forgeGuide: unsupported, forgeScaffold: unsupported, forgePack: unsupported,
+ forgeInstall: unsupported, forgePublish: unsupported, forgePublishStatus: unsupported,
+ };
+
+ beforeAll(async () => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-hosted-')));
+ server = createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => { body += chunk; });
+ req.on('end', async () => {
+ if (req.url === '/mcp') {
+ const mcp = createCindyGhostsMcpServer(pluginDeps);
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
+ res.on('close', () => { void transport.close(); void mcp.close(); });
+ await mcp.connect(transport);
+ await transport.handleRequest(req, res, body ? JSON.parse(body) : undefined);
+ return;
+ }
+ if (!req.url?.includes('/responses')) {
+ res.writeHead(404).end('{}');
+ return;
+ }
+ bodies.push(body);
+ let parsed: { input?: Array<{ type?: string }> } = {};
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ parsed = {};
+ }
+ const done = (parsed.input ?? []).filter((item) => item.type === 'function_call_output' || item.type === 'custom_tool_call_output').length;
+ const step = steps[done];
+ const id = `resp_${bodies.length}`;
+ const item = step?.kind === 'exec'
+ ? { type: 'function_call', id: `fc_${done}`, call_id: `call_${done}`, name: 'exec_command', arguments: JSON.stringify({ cmd: step.cmd }), status: 'completed' }
+ : step?.kind === 'tool'
+ ? { type: 'custom_tool_call', id: `fc_${done}`, call_id: `call_${done}`, name: 'exec', input: `text(await tools.${step.name}(${JSON.stringify(step.args)}));`, status: 'completed' }
+ : { type: 'message', id: `msg_${done}`, role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'DONE', annotations: [] }] };
+ const events = [
+ { type: 'response.created', response: { id, status: 'in_progress', output: [] } },
+ { type: 'response.output_item.added', output_index: 0, item },
+ { type: 'response.output_item.done', output_index: 0, item },
+ { type: 'response.completed', response: { id, status: 'completed', output: [item], usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 } } },
+ ];
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });
+ res.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''));
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}/v1`;
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
+ });
+
+ function codexDeps(home: string): AgentDeps {
+ fs.mkdirSync(home, { recursive: true });
+ fs.writeFileSync(path.join(home, 'config.toml'), [
+ 'model="gpt-5.5"',
+ 'model_provider="fixture"',
+ 'cli_auth_credentials_store="ephemeral"',
+ 'check_for_update_on_startup=false',
+ '[analytics]', 'enabled=false',
+ // Match hosted guest isolation: provider-side native plugins must not leak into the task.
+ // Task-side Cindy plugins remain available through their real MCP gateway below.
+ '[features]', 'plugins=false', 'remote_plugin=false',
+ '[features.code_mode]', 'enabled=true',
+ '[model_providers.fixture]', 'name="Fixture"',
+ `base_url="${endpoint}"`, 'wire_api="responses"',
+ 'requires_openai_auth=false', 'request_max_retries=0', 'supports_websockets=false',
+ ].join('\n'));
+ return {
+ binaryPath: CODEX,
+ logger: noopLogger,
+ runtimeConfig: {},
+ resolveCodexLocalAuthPolicy: () => 'isolated',
+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),
+ auth: {
+ getState: async () => ({ authenticated: true }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({
+ HOME: path.dirname(home), CODEX_HOME: home, OPENAI_API_KEY: '', CODEX_API_KEY: '',
+ }),
+ },
+ } as AgentDeps;
+ }
+
+ it('compares native startup with and without shortcuts', { timeout: 180_000 }, async () => {
+ const project = path.join(root, 'project');
+ const skillDir = path.join(project, '.agents', 'skills', 'qa-discovery');
+ fs.mkdirSync(skillDir, { recursive: true });
+ fs.mkdirSync(path.join(project, '.git'));
+ fs.writeFileSync(path.join(skillDir, 'SKILL.md'), '---\nname: qa-discovery\ndescription: QA_SKILL_DISCOVERY_SENTINEL\n---\nReply QA_SKILL_BODY_SENTINEL when invoked.\n');
+ steps = [{ kind: 'exec', cmd: process.platform === 'win32'
+ ? "Get-Content .agents/skills/qa-discovery/SKILL.md"
+ : 'cat .agents/skills/qa-discovery/SKILL.md' },
+ { kind: 'tool', name: 'mcp__cindy__ghost_list', args: {} },
+ { kind: 'tool', name: 'mcp__cindy__ghost_info', args: { ghost_id: plugin.id } },
+ { kind: 'tool', name: 'mcp__cindy__ghost_call', args: { ghost_id: plugin.id, tool: 'ping', args: {} } },
+ ];
+ 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 },
+ ]) {
+ bodies.length = 0;
+ pluginCalls = 0;
+ let shortcutHits = 0;
+ const spy = vi.spyOn(shortcutModule, 'createExecServerShortcut').mockImplementation(layout => {
+ const shortcut = original(layout);
+ return data => {
+ const reply = optimized ? shortcut(data) : null;
+ if (reply !== null) shortcutHits += 1;
+ return reply;
+ };
+ });
+ const agent = new CodexAgent(codexDeps(path.join(root, `home-${optimized}-${delayMs}`)));
+ 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}`),
+ log: {
+ info() {}, warn() {},
+ debug(_message, fields) {
+ if (fields?.side === 'host' && fields?.stage === 'total') startupStats = fields.execServer as StartupExecServerStats;
+ },
+ },
+ });
+ let handle;
+ 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]));
+ const result = JSON.parse(JSON.stringify(await host.handle('controller-1', req) ?? null));
+ if (req.op === 'poll') {
+ for (const run of result?.runs ?? []) for (const line of Buffer.from(run.data ?? '', 'base64').toString().split('\n').filter(Boolean)) {
+ const item = JSON.parse(line);
+ if (item.t === 'ws' && item.kind === 'message') {
+ const rpc = JSON.parse(item.data);
+ counts[rpc.method] = (counts[rpc.method] ?? 0) + 1;
+ }
+ }
+ }
+ // real-wait: e2e fixed link latency measures serial native RPC round trips.
+ if (delayMs && (req.op === 'poll' || req.op === 'push')) await new Promise(r => setTimeout(r, delayMs));
+ return result;
+ },
+ rgPath: RG, codexPath: () => CODEX,
+ prepareMcp: async () => ({ servers: new Map([
+ ['cindy', { url: endpoint.replace('/v1', '/mcp'), headers: {} }],
+ ]), dispose() {} }),
+ collectProjectFiles: async () => [], collectAncestorMarkers,
+ isGitRepo: async () => true, newId: randomUUID,
+ });
+ handle.setInteractionResolver(async () => ({ kind: 'permission', behavior: 'allow' }));
+ const durationMs = Math.round(performance.now() - before);
+ const startupCounts = { ...counts };
+ const startupHits = shortcutHits;
+ expect(startupStats).toMatchObject({ shortcutEnabled: true, connections: 1, answered: startupHits });
+ expect(startupStats!.ancestorLevels).toBeGreaterThan(0);
+ const done = (async () => {
+ for await (const event of handle!.events()) {
+ if (event.type === 'error') throw new Error(JSON.stringify(event.data));
+ if (event.type === 'done') break;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'Reply DONE.' }, { throwOnStartFailure: true });
+ await done;
+ const skillPresent = bodies.at(-1)!.includes('QA_SKILL_DISCOVERY_SENTINEL');
+ 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 });
+ expect(skillPresent).toBe(true);
+ expect(skillBodyRead).toBe(true);
+ expect(pluginDiscovered).toBe(true);
+ expect(pluginCalled).toBe(true);
+ expect(shortcutHits > 0).toBe(optimized);
+ } finally {
+ await handle?.close({ reason: 'navigation' });
+ await agent.dispose(); host.dispose(); spy.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));
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/controller/runClient.ts b/apps/desktop/src/main/remote-agent/controller/runClient.ts
index 2a72439399..8f5dd05c6b 100644
--- a/apps/desktop/src/main/remote-agent/controller/runClient.ts
+++ b/apps/desktop/src/main/remote-agent/controller/runClient.ts
@@ -32,6 +32,7 @@ import {
} from '@cindy/device-link';
import { LineSplitter } from '../eventLog';
+import { remoteAgentStartupTiming } from '../startupTiming';
import { isRetryableLinkError, RemoteAgentPoller, type PolledRun, type RemoteAgentInvoke } from './poller';
export { isRetryableLinkError, RemoteAgentPoller, type RemoteAgentInvoke } from './poller';
@@ -91,7 +92,10 @@ export class RemoteAgentRunClient implements PolledRun {
private readonly poller: RemoteAgentPoller,
private readonly handlers: RemoteAgentRunHandlers,
private readonly newId: () => string,
- private readonly log?: { warn(message: string, meta?: Record<string, unknown>): void },
+ private readonly log?: {
+ debug?(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+ },
) {
this.invoke = poller.invoke;
this.drained = new Promise<void>((resolve) => {
@@ -123,26 +127,48 @@ export class RemoteAgentRunClient implements PolledRun {
*/
async open(agentKind: RemoteAgentKind, openPayload: unknown): Promise<Record<string, unknown>> {
if (this.closed) throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
- const payload = await this.payload(openPayload);
- if (this.closed) throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
- const started = new Promise<Record<string, unknown>>((resolve, reject) => {
- this.started = { resolve, reject };
+ const sessionId =
+ openPayload &&
+ typeof openPayload === 'object' &&
+ 'sessionId' in openPayload &&
+ typeof openPayload.sessionId === 'string'
+ ? openPayload.sessionId
+ : undefined;
+ const timing = remoteAgentStartupTiming(this.log, {
+ side: 'transport',
+ kind: agentKind,
+ sessionId,
+ runId: this.runId,
});
+ let status: 'ok' | 'failed' = 'failed';
try {
- await this.invoke([{ op: 'open', runId: this.runId, agentKind, payload }]);
- } catch (error) {
- this.started = null;
- throw error;
- }
- if (this.closed) {
- // 打开途中本机关掉了这个任务:对方可能先收到关闭(那时还没有这个任务)再收到打开,补发一次关闭。
- void started.catch(() => undefined);
- void this.invoke([{ op: 'close', runId: this.runId, mode: 'close', reason: 'navigation' }]).catch(() => undefined);
- throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
+ const payload = await timing.measure('payload-upload', () => this.payload(openPayload));
+ if (this.closed) throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
+ const started = new Promise<Record<string, unknown>>((resolve, reject) => {
+ this.started = { resolve, reject };
+ });
+ try {
+ await timing.measure('open-request', () =>
+ this.invoke([{ op: 'open', runId: this.runId, agentKind, payload }]),
+ );
+ } catch (error) {
+ this.started = null;
+ throw error;
+ }
+ if (this.closed) {
+ // 打开途中本机关掉了这个任务:对方可能先收到关闭(那时还没有这个任务)再收到打开,补发一次关闭。
+ void started.catch(() => undefined);
+ void this.invoke([{ op: 'close', runId: this.runId, mode: 'close', reason: 'navigation' }]).catch(() => undefined);
+ throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
+ }
+ this.registered = true;
+ this.poller.register(this);
+ const result = await timing.measure('session-ready', () => started);
+ status = 'ok';
+ return result;
+ } finally {
+ timing.finish(status);
}
- this.registered = true;
- this.poller.register(this);
- return started;
}
/** 调用对方会话的一个方法,等结果。 */
diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.ts
index 1818ff2bc6..10458866f6 100644
--- a/apps/desktop/src/main/remote-agent/controller/service.ts
+++ b/apps/desktop/src/main/remote-agent/controller/service.ts
@@ -23,6 +23,7 @@ import type {
StartSessionOptions,
} from '@cindy/maker-core';
import { resolveMemoryScopeKey } from '@cindy/maker-core';
+import { createLogger } from '../../logger.js';
import { credentialGrantFor } from '../executor/credentialGrants';
import type { ExecutorCaptureHooks } from '../executor/executor';
@@ -154,6 +155,8 @@ export function remoteAgentPollerFor(
/** Maker 的 startDeviceAgentSession 实现。 */
export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
const log = deps.logger.child('remote-agent');
+ // Agent 统一流有突发限流;启动阶段日志必须完整落在 main 流,才能解释慢启动。
+ const startupLog = createLogger('remote-agent:startup');
const pollerFor = (deviceId: string): RemoteAgentPoller => remoteAgentPollerFor(deviceId, deps.remoteInvoke, log);
// 每台运行 Agent 的电脑一个连接池:对方按这台设备计名额,池里算的是本机在那台上开着的连接;
// 闲置多久可以让出按那台主人设置的闲置收回时长(打开前与主动让出前从 caps 读)。
@@ -262,7 +265,11 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {
...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),
mapEvent: deps.mapEvent ?? remoteAgentEventMapper,
newId: randomUUID,
- log,
+ log: {
+ debug: (message, fields) => startupLog.debug(message, fields),
+ info: (message, fields) => log.info(message, fields),
+ warn: (message, fields) => log.warn(message, fields),
+ },
});
};
}
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index d12b163789..863b49bc18 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -33,6 +33,7 @@ import { ExecutorGate, executorGateModeFor, type ExecutorAction } from '../execu
import { GitCredentialHistory } from '../executor/gitCredentials';
import type { GuardedFetch } from '../executor/webFetch';
import { ExecutorWorkspace, projectPathText } from '../executor/workspace';
+import { remoteAgentStartupTiming } from '../startupTiming';
import type {
RemoteAgentOpenPayload,
RemoteAgentWireAncestorFile,
@@ -132,6 +133,7 @@ export interface StartRemoteAgentDeps {
groupSwitch?: { token?: string; offer(token: string): void; takeNewRound?(): boolean };
newId(): string;
log?: {
+ debug?(message: string, meta?: Record<string, unknown>): void;
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
};
@@ -308,9 +310,14 @@ export async function startRemoteAgentSession(
const cancels = pendingStarts.get(sessionId) ?? new Set<() => void>();
pendingStarts.set(sessionId, cancels);
cancels.add(cancel);
+ const timing = remoteAgentStartupTiming(deps.log, { side: 'controller', kind, sessionId });
+ let status: 'ok' | 'failed' = 'failed';
try {
- return await prepareAndStartRemoteAgentSession(kind, opts, deps, abort.signal);
+ const handle = await prepareAndStartRemoteAgentSession(kind, opts, deps, abort.signal, timing);
+ status = 'ok';
+ return handle;
} finally {
+ timing.finish(status);
cancels.delete(cancel);
if (!cancels.size && pendingStarts.get(sessionId) === cancels) pendingStarts.delete(sessionId);
}
@@ -321,6 +328,7 @@ async function prepareAndStartRemoteAgentSession(
opts: StartSessionOptions,
deps: StartRemoteAgentDeps,
signal: AbortSignal,
+ startupTiming: ReturnType<typeof remoteAgentStartupTiming>,
): Promise<AgentSessionHandle> {
// 附加目录(只读引用)与可写目录分开跟踪,运行中任一侧变化都重算执行器根目录:
// 否则新授予的目录过不了本机 shell/root 判定,撤掉的还被本机上限当可信根。
@@ -370,10 +378,12 @@ async function prepareAndStartRemoteAgentSession(
: {}),
});
const vendorOptions: Record<string, unknown> = { ...(opts.vendorOptions ?? {}) };
- const mcp = await deps.prepareMcp({ kind, opts, vendorOptions }).catch((error) => {
- void executor.close();
- throw error;
- });
+ const mcp = await startupTiming
+ .measure('mcp-prepare', () => deps.prepareMcp({ kind, opts, vendorOptions }))
+ .catch((error) => {
+ void executor.close();
+ throw error;
+ });
if (signal.aborted) {
try { mcp.dispose(); } finally { await executor.close(); }
throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
@@ -686,22 +696,47 @@ async function prepareAndStartRemoteAgentSession(
return next;
}
- async function buildPayload(reconnect: boolean): Promise<RemoteAgentOpenPayload> {
+ async function buildPayload(
+ reconnect: boolean,
+ timing: ReturnType<typeof remoteAgentStartupTiming>,
+ ): Promise<RemoteAgentOpenPayload> {
// 每次打开都读最新的图片清空代次:让出期间清空过的,连回的新进程按新代次交付。
- const imageDeliveryEpoch = await deps.readImageDeliveryEpoch?.(opts.sessionId!);
+ const imageDeliveryEpoch = await timing.measure('image-epoch', async () =>
+ deps.readImageDeliveryEpoch?.(opts.sessionId!),
+ );
const startOptions = openOptions(reconnect);
- const projectFiles = await deps.collectProjectFiles(opts.workingDir).catch(() => []);
- const ancestorFiles = await (deps.collectAncestorFiles?.(opts.workingDir) ?? Promise.resolve([])).catch(() => []);
+ const projectFiles = await timing
+ .measure('project-files', () => deps.collectProjectFiles(opts.workingDir))
+ .catch(() => []);
+ const ancestorFiles = await timing
+ .measure(
+ 'ancestor-files',
+ () => (deps.collectAncestorFiles?.(opts.workingDir) ?? Promise.resolve([])),
+ )
+ .catch(() => []);
// 每次打开(含连回)都重新看一遍:上级目录里的标记以这次打开时为准。
- const ancestorMarkers = await (deps.collectAncestorMarkers?.(opts.workingDir) ?? Promise.resolve(undefined))
+ const ancestorMarkers = await timing
+ .measure(
+ 'ancestor-markers',
+ () => (deps.collectAncestorMarkers?.(opts.workingDir) ?? Promise.resolve(undefined)),
+ )
.catch(() => undefined);
- const collectedPersonal = await (deps.collectPersonal?.(kind, projectFiles) ?? Promise.resolve(null))
+ const collectedPersonal = await timing
+ .measure(
+ 'personal-config',
+ () => (deps.collectPersonal?.(kind, projectFiles) ?? Promise.resolve(null)),
+ )
.catch(() => null);
personalRoots = collectedPersonal?.roots ?? [];
const personal = collectedPersonal?.personal ?? { files: [] };
- const importFiles = kind === 'claude-code' && deps.collectImports
- ? await deps.collectImports({ workingDir: opts.workingDir, projectFiles, ancestorFiles, personal }).catch(() => [])
- : [];
+ const importFiles =
+ kind === 'claude-code' && deps.collectImports
+ ? await timing
+ .measure('instruction-imports', () =>
+ deps.collectImports!({ workingDir: opts.workingDir, projectFiles, ancestorFiles, personal }),
+ )
+ .catch(() => [])
+ : [];
return {
sessionId: opts.sessionId!,
acceptsImageDeliveryReceipts: true,
@@ -716,7 +751,9 @@ async function prepareAndStartRemoteAgentSession(
osVersion: `${os.type()} ${os.release()}`,
// 仅供被控端把项目说明中的本机 Home 路径投影到虚拟工作区;不会进入 deviceHosted。
homeDir: os.homedir(),
- isGitRepo: await deps.isGitRepo(opts.workingDir).catch(() => false),
+ isGitRepo: await timing
+ .measure('git-probe', () => deps.isGitRepo(opts.workingDir))
+ .catch(() => false),
},
projectFiles,
ancestorFiles,
@@ -739,26 +776,49 @@ async function prepareAndStartRemoteAgentSession(
reconnect: boolean,
onOpened: (started: RemoteStartedInfo) => void,
): Promise<RemoteAgentRunClient> {
- // 重启恢复可能撞上 relay 尚未上线/拥堵冷却;只重试无副作用的能力读取,
- // 等既有链路自行恢复。open/upload/send 的交付不确定时不能整次重放。
- const caps = await withTransientRemoteRetry(() => {
- if (linkState === 'closed') {
- throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
- }
- return RemoteAgentRunClient.caps(deps.invoke);
- });
- if (caps.virtualWorkspace !== true) {
- throw new Error('[REMOTE_AGENT_UNSUPPORTED] The other computer does not support the virtual workspace required to protect local paths.');
- }
- deps.pool?.noteMaxRuns(caps.maxRuns);
- deps.pool?.noteIdleReclaimMinutes(caps.idleReclaimMinutes);
- await deps.pool?.beforeOpen(member);
- const payload = await buildPayload(reconnect);
+ const timing = reconnect
+ ? remoteAgentStartupTiming(deps.log, {
+ side: 'controller',
+ kind,
+ sessionId: opts.sessionId,
+ reconnect,
+ })
+ : startupTiming;
+ let status: 'ok' | 'failed' = 'failed';
try {
- return await openRun(payload, reconnect, onOpened);
- } catch (error) {
- if (!deps.pool || linkState === 'closed' || !isRemoteRunLimitError(error) || !await deps.pool.releaseForRetry(member)) throw error;
- return await openRun(payload, reconnect, onOpened);
+ // 重启恢复可能撞上 relay 尚未上线/拥堵冷却;只重试无副作用的能力读取,
+ // 等既有链路自行恢复。open/upload/send 的交付不确定时不能整次重放。
+ const caps = await timing.measure('capability-handshake', () =>
+ withTransientRemoteRetry(() => {
+ if (linkState === 'closed') {
+ throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
+ }
+ return RemoteAgentRunClient.caps(deps.invoke);
+ }),
+ );
+ if (caps.virtualWorkspace !== true) {
+ throw new Error('[REMOTE_AGENT_UNSUPPORTED] The other computer does not support the virtual workspace required to protect local paths.');
+ }
+ deps.pool?.noteMaxRuns(caps.maxRuns);
+ deps.pool?.noteIdleReclaimMinutes(caps.idleReclaimMinutes);
+ await timing.measure('connection-slot', async () => deps.pool?.beforeOpen(member));
+ const payload = await buildPayload(reconnect, timing);
+ try {
+ const client = await timing.measure('remote-open', () =>
+ openRun(payload, reconnect, onOpened),
+ );
+ status = 'ok';
+ return client;
+ } catch (error) {
+ if (!deps.pool || linkState === 'closed' || !isRemoteRunLimitError(error) || !await deps.pool.releaseForRetry(member)) throw error;
+ const client = await timing.measure('remote-open', () =>
+ openRun(payload, reconnect, onOpened),
+ );
+ status = 'ok';
+ return client;
+ }
+ } finally {
+ if (reconnect) timing.finish(status);
}
}
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index 6b0c867750..0c322ff18b 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -1,4 +1,5 @@
import type { GeneratedImageUpstream } from '../../cindy-media/generatedImageJournal';
+import { remoteAgentStartupTiming } from '../startupTiming';
import { parseProviderSharePeer } from '@cindy/device-link';
import { DEFAULT_REMOTE_AGENT_LIMITS, type RemoteAgentLimits, type RemoteAgentLimitUsage } from '../../../shared/remoteAgentLimits.js';
/**
@@ -262,6 +263,7 @@ export interface RemoteAgentHostDeps {
runsRoot: string;
now?: () => number;
log?: {
+ debug?(message: string, meta?: Record<string, unknown>): void;
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
};
@@ -1206,77 +1208,110 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
async function startRun(run: Run, payload: RemoteAgentOpenPayload): Promise<void> {
run.imageDeliveryEpoch = payload.imageDeliveryEpoch;
+ const timing = remoteAgentStartupTiming(deps.log, {
+ side: 'host',
+ kind: run.kind,
+ sessionId: payload.sessionId,
+ runId: run.id,
+ });
+ let status: 'ok' | 'failed' = 'failed';
+ let startupComplete = false;
+ const execServerStats = {
+ shortcutEnabled: false,
+ ancestorLevels: payload.ancestorMarkers?.levels.length ?? 0,
+ connections: 0,
+ answered: 0,
+ forwarded: 0,
+ };
try {
// 中转过来的任务按(控制端, relay)派生:不同受邀者即使任务 id 相同也不会共用本机侧任务。
const hostSessionId = hostSessionIdFor(guestScopeOf(run.controller, run.relayKey), payload.sessionId);
run.hostSessionId = hostSessionId;
- run.forkWorkspaceIds = await forkWorkspacesFor(guestScopeOf(run.controller, run.relayKey), payload.options.resumeSessionId);
+ run.forkWorkspaceIds = await timing.measure('resume-workspaces', () =>
+ forkWorkspacesFor(guestScopeOf(run.controller, run.relayKey), payload.options.resumeSessionId),
+ );
const previousMirrorRoots = run.forkWorkspaceIds.map((id) => path.join(shadowSessionRoot(run.controller, id), 'fs'));
let guestHome: string | undefined;
if (run.trust === 'guest') {
// 先登记再启动:启动中途失败时,受邀者目录与会话记录也能在分享删除时被找到并清理。
- await recordGuestSession(run.controller, run.relayKey, hostSessionId, []);
+ await timing.measure('guest-registration', () =>
+ recordGuestSession(run.controller, run.relayKey, hostSessionId, []),
+ );
guestHome = guestHomeFor(guestScopeOf(run.controller, run.relayKey));
await fsp.mkdir(guestHome, { recursive: true, mode: 0o700 });
}
- const { shadowDir, mirrorRoot, shortcutLayout, sessionRoot, extraDirs, writableDirs, projectText } = await withShadowLock(hostSessionId, async () => {
- // 断线后旧实例还没清理就重新打开同一任务时,新旧实例共用同一个影子目录:
- // 先结束旧实例再重建,避免删掉旧 Agent 还在使用的目录,或两个实例争用重建后的目录。
- for (const other of runs.values()) {
- if (other !== run && other.controller === run.controller && other.hostSessionId === hostSessionId && !other.closing) {
- await finishRun(other, 'superseded', 'navigation');
+ const { shadowDir, mirrorRoot, shortcutLayout, sessionRoot, extraDirs, writableDirs, projectText } = await timing.measure('shadow-workspace', () =>
+ withShadowLock(hostSessionId, async () => {
+ // 断线后旧实例还没清理就重新打开同一任务时,新旧实例共用同一个影子目录:
+ // 先结束旧实例再重建,避免删掉旧 Agent 还在使用的目录,或两个实例争用重建后的目录。
+ for (const other of runs.values()) {
+ if (other !== run && other.controller === run.controller && other.hostSessionId === hostSessionId && !other.closing) {
+ await finishRun(other, 'superseded', 'navigation');
+ }
}
- }
- return prepareShadow(run.controller, payload, hostSessionId, run.trust);
- });
+ return prepareShadow(run.controller, payload, hostSessionId, run.trust);
+ }),
+ );
run.workspaceDir = sessionRoot;
run.virtualRoot = payload.virtualWorkspace ? mirrorRoot : undefined;
// 虚拟工作区里注定不存在的路径查询由本机直接回答,不再逐条跨设备往返(见 execServerShortcut)。
const shortcut = payload.virtualWorkspace ? createExecServerShortcut(shortcutLayout) : null;
+ execServerStats.shortcutEnabled = shortcut !== null;
const execConns = new Set<string>();
- const tunnel = await createRunTunnel({
- http: async (request, signal) => {
- // Pi API-key providers keep their native transports. Their adapter
- // checks this authenticated, run-local endpoint before opening a stream.
- if (request.path === '/cindy/model-access') {
- let model: unknown;
- let providerId: unknown;
- try { ({ model, providerId } = JSON.parse(request.body?.toString('utf8') ?? '{}')); } catch { /* deny */ }
- const current = () => !run.closing && !signal.aborted && deps.isOwnerCurrent(run.owner)
- && deps.isControllerAuthorized(run.controller);
- let allowed = false;
- try {
- if (request.method === 'POST' && current() && typeof model === 'string' && model && model.length <= 512) {
- allowed = run.trust === 'guest'
- ? (providerId === undefined || providerId === run.providerId) && await run.guestRoute?.allowsModel?.(model) === true
- : typeof providerId === 'string' && !!providerId && providerId.length <= 512 && !!run.ownerRoute
- && deps.ownerModelAllowed?.(hostSessionId, providerId, run.kind, model) === true;
- allowed = allowed && current();
+ const tunnel = await timing.measure('tunnel-prepare', () =>
+ createRunTunnel({
+ http: async (request, signal) => {
+ // Pi API-key providers keep their native transports. Their adapter
+ // checks this authenticated, run-local endpoint before opening a stream.
+ if (request.path === '/cindy/model-access') {
+ let model: unknown;
+ let providerId: unknown;
+ try { ({ model, providerId } = JSON.parse(request.body?.toString('utf8') ?? '{}')); } catch {
+ /* deny */
}
- } catch { /* Failed authorization must never open a native stream. */ }
- return { status: 200, headers: [['content-type', 'application/json']], body: Buffer.from(JSON.stringify({ allowed })) };
- }
- return reverseHttp(run, request, signal);
- },
- wsOpen: (connId, wsPath) => {
- (run.localWs ??= new Set()).add(connId);
- if (wsPath.split('?')[0] === EXEC_SERVER_WS_PATH) execConns.add(connId);
- append(run, { t: 'ws', connId, kind: 'open', path: wsPath });
- },
- wsMessage: (connId, data) => {
- const local = shortcut && execConns.has(connId) ? shortcut(data) : null;
- if (local !== null) {
- run.tunnel?.sendWs(connId, local);
- return;
- }
- append(run, { t: 'ws', connId, kind: 'message', data });
- },
- wsClose: (connId) => {
- run.localWs?.delete(connId);
- execConns.delete(connId);
- append(run, { t: 'ws', connId, kind: 'close' });
- },
- });
+ const current = () => !run.closing && !signal.aborted && deps.isOwnerCurrent(run.owner)
+ && deps.isControllerAuthorized(run.controller);
+ let allowed = false;
+ try {
+ if (request.method === 'POST' && current() && typeof model === 'string' && model && model.length <= 512) {
+ allowed = run.trust === 'guest'
+ ? (providerId === undefined || providerId === run.providerId) && await run.guestRoute?.allowsModel?.(model) === true
+ : typeof providerId === 'string' && !!providerId && providerId.length <= 512 && !!run.ownerRoute
+ && deps.ownerModelAllowed?.(hostSessionId, providerId, run.kind, model) === true;
+ allowed = allowed && current();
+ }
+ } catch {
+ /* Failed authorization must never open a native stream. */
+ }
+ return { status: 200, headers: [['content-type', 'application/json']], body: Buffer.from(JSON.stringify({ allowed })) };
+ }
+ return reverseHttp(run, request, signal);
+ },
+ wsOpen: (connId, wsPath) => {
+ (run.localWs ??= new Set()).add(connId);
+ if (wsPath.split('?')[0] === EXEC_SERVER_WS_PATH) {
+ execConns.add(connId);
+ if (!startupComplete) execServerStats.connections += 1;
+ }
+ append(run, { t: 'ws', connId, kind: 'open', path: wsPath });
+ },
+ wsMessage: (connId, data) => {
+ const local = shortcut && execConns.has(connId) ? shortcut(data) : null;
+ if (local !== null) {
+ if (!startupComplete) execServerStats.answered += 1;
+ run.tunnel?.sendWs(connId, local);
+ 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);
+ append(run, { t: 'ws', connId, kind: 'close' });
+ },
+ }),
+ );
run.tunnel = tunnel;
if (run.closing) return;
// 必须先发布映射,再启动 Agent。Codex startSession 会在 started 之前读取 exec-server 环境。
@@ -1297,14 +1332,16 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
if (!Array.isArray(models) || !models.every(model => typeof model === 'string')) failProviderNotAllowed();
relayModelAccess = { models, allows: async model => await checkRelayModel(model) === true };
}
- const binding = await deps.bindGuestProviderRoute({
- kind: run.kind,
- hostSessionId,
- providerId: run.providerId,
- controller: run.controller,
- isCurrent: () => !run.closing,
- ...(relayModelAccess ? { relayModelAccess } : {}),
- });
+ const binding = await timing.measure('provider-route', () =>
+ deps.bindGuestProviderRoute!({
+ kind: run.kind,
+ hostSessionId,
+ providerId: run.providerId!,
+ controller: run.controller,
+ isCurrent: () => !run.closing,
+ ...(relayModelAccess ? { relayModelAccess } : {}),
+ }),
+ );
if (!binding) {
if (!run.closing) failProviderNotAllowed();
return;
@@ -1321,41 +1358,45 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
&& deps.providerAccess!.isAllowed(providerId, run.controller, model)
: undefined);
}
- const handle = await deps.startHosted({
- ...(run.groupProviderId ? { groupProviderId: run.groupProviderId } : {}),
- kind: run.kind,
- hostSessionId,
- shadowDir,
- mirrorRoot,
- extraDirs,
- writableDirs,
- virtualWorkspace: payload.virtualWorkspace === true,
- ...(payload.personal.instructions ? { personalInstructions: projectText(payload.personal.instructions) } : {}),
- // 恢复标识属于提供方;Pi 的标识即使是文件路径,也不能按控制端路径投影。
- options: Object.fromEntries(Object.entries(payload.options).map(([key, value]) => [
- key,
- typeof value === 'string' && key !== 'resumeSessionId' ? projectText(value) : value,
- ])) as unknown as RemoteAgentWireStartOptions,
- workspace: payload.workspace,
- tunnel: { url: tunnel.url, token: tunnel.token, linkActivity: () => tunnel.linkActivity() },
- mcpServers: payload.mcpServers,
- ...(run.trust === 'guest' ? { guest: true, ...(guestHome ? { guestHome } : {}), ...(guestProvider ? { guestProvider } : {}) } : {}),
- ...(payload.options.invalidResumeCallback
- ? {
- onInvalidResumeSession: async (expected: string) => {
- const reply = await reverse(run, { type: 'callback', name: 'onInvalidResumeSession', args: [expected] });
- return reply.type === 'callback' && reply.value === true;
- },
- }
- : {}),
- });
+ const handle = await timing.measure('agent-session', () =>
+ deps.startHosted({
+ ...(run.groupProviderId ? { groupProviderId: run.groupProviderId } : {}),
+ kind: run.kind,
+ hostSessionId,
+ shadowDir,
+ mirrorRoot,
+ extraDirs,
+ writableDirs,
+ virtualWorkspace: payload.virtualWorkspace === true,
+ ...(payload.personal.instructions ? { personalInstructions: projectText(payload.personal.instructions) } : {}),
+ // 恢复标识属于提供方;Pi 的标识即使是文件路径,也不能按控制端路径投影。
+ options: Object.fromEntries(Object.entries(payload.options).map(([key, value]) => [
+ key,
+ typeof value === 'string' && key !== 'resumeSessionId' ? projectText(value) : value,
+ ])) as unknown as RemoteAgentWireStartOptions,
+ workspace: payload.workspace,
+ tunnel: { url: tunnel.url, token: tunnel.token, linkActivity: () => tunnel.linkActivity() },
+ mcpServers: payload.mcpServers,
+ ...(run.trust === 'guest' ? { guest: true, ...(guestHome ? { guestHome } : {}), ...(guestProvider ? { guestProvider } : {}) } : {}),
+ ...(payload.options.invalidResumeCallback
+ ? {
+ onInvalidResumeSession: async (expected: string) => {
+ const reply = await reverse(run, { type: 'callback', name: 'onInvalidResumeSession', args: [expected] });
+ return reply.type === 'callback' && reply.value === true;
+ },
+ }
+ : {}),
+ }),
+ );
if (run.closing) {
await handle.close({ reason: 'navigation' }).catch(() => undefined);
return;
}
run.handle = handle;
if (run.trust === 'guest' || run.forkWorkspaceIds.length) {
- await recordGuestSession(run.controller, run.relayKey, hostSessionId, [handle.id, handle.requestSessionId], undefined, run.forkWorkspaceIds);
+ await timing.measure('session-registration', () =>
+ recordGuestSession(run.controller, run.relayKey, hostSessionId, [handle.id, handle.requestSessionId], undefined, run.forkWorkspaceIds),
+ );
}
handle.setInteractionResolver(async (request: InteractionRequest) => {
const reply = await reverse(run, { type: 'interaction', request });
@@ -1367,6 +1408,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
run.stateTimer = setInterval(() => emitState(run), STATE_INTERVAL_MS);
(run.stateTimer as { unref?: () => void }).unref?.();
void pumpEvents(run, handle);
+ status = 'ok';
} catch (error) {
if (await relayAfterLocalStartFailure(run, payload, error)) return;
if (run.groupResumed && run.providerId) {
@@ -1374,6 +1416,9 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
}
append(run, { t: 'start-failed', error: remoteAgentErrorInfo(error) });
await finishRun(run, 'start-failed', 'navigation', false);
+ } finally {
+ startupComplete = true;
+ timing.finish(status, execServerStats);
}
}
diff --git a/apps/desktop/src/main/remote-agent/startupTiming.ts b/apps/desktop/src/main/remote-agent/startupTiming.ts
new file mode 100644
index 0000000000..29d41eb797
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/startupTiming.ts
@@ -0,0 +1,69 @@
+import { performance } from 'node:perf_hooks';
+
+export interface StartupTimingLogger {
+ debug?(message: string, fields: Record<string, unknown>): void;
+}
+
+/** 固定字段的启动诊断;不接受 RPC 内容、路径或配置正文。 */
+export interface StartupExecServerStats {
+ shortcutEnabled: boolean;
+ ancestorLevels: number;
+ connections: number;
+ answered: number;
+ forwarded: number;
+}
+
+/** 本机单调时钟计时;只接收关联 ID 和固定阶段名,不接收路径、配置、凭证或错误正文。 */
+export function remoteAgentStartupTiming(
+ log: StartupTimingLogger | undefined,
+ context: {
+ side: 'controller' | 'transport' | 'host';
+ kind: string;
+ sessionId?: string;
+ runId?: string;
+ reconnect?: boolean;
+ },
+) {
+ const started = performance.now();
+ const stagesMs: Record<string, number> = {};
+ const refs = {
+ side: context.side,
+ kind: context.kind,
+ ...(context.sessionId ? { sessionRef: context.sessionId.slice(0, 8) } : {}),
+ ...(context.runId ? { runRef: context.runId.slice(0, 8) } : {}),
+ ...(context.reconnect !== undefined ? { reconnect: context.reconnect } : {}),
+ };
+ const emit = (fields: Record<string, unknown>) => {
+ // 诊断输出失败不能改变创建结果或覆盖原始异常。
+ try {
+ log?.debug?.('remote agent startup timing', { ...refs, ...fields });
+ } catch {
+ /* diagnostic only */
+ }
+ };
+ return {
+ async measure<T>(stage: string, operation: () => Promise<T>): Promise<T> {
+ const begin = performance.now();
+ emit({ stage, status: 'started', elapsedMs: Math.round(begin - started) });
+ let status = 'failed';
+ try {
+ const result = await operation();
+ status = 'ok';
+ return result;
+ } finally {
+ const durationMs = Math.max(0, Math.round(performance.now() - begin));
+ stagesMs[stage] = (stagesMs[stage] ?? 0) + durationMs;
+ emit({ stage, status, durationMs, elapsedMs: Math.round(performance.now() - started) });
+ }
+ },
+ finish(status: 'ok' | 'failed', execServer?: StartupExecServerStats) {
+ emit({
+ stage: 'total',
+ status,
+ durationMs: Math.round(performance.now() - started),
+ stagesMs: { ...stagesMs },
+ ...(execServer ? { execServer: { ...execServer } } : {}),
+ });
+ },
+ };
+}
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index c81fbfff0b..b2bba5064d 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -633,6 +633,74 @@ Debug 日志区分两层耗时:
这些日志不改变 wire、ACK、重试或授权语义。
+远程 Agent 创建慢时,开启 `LOG_LEVEL=debug`,在 main 日志里查
+`remote agent startup timing`(发起端 scope `remote-agent:startup`,运行端
+`remote-agent:host`;独立于 Agent 日志的突发限流)。
+Dev 默认已包含 debug,日志在启动 checkout 的 `apps/desktop/logs/`;安装版在本机
+userData 的 `logs/`。按 `sessionRef`(任务 ID 前 8 位)与 `runRef`(run ID 前 8 位)
+关联两端;同一任务重连会创建新的 run,控制端另标 `reconnect: true`。
+
+- `side=controller`:`mcp-prepare`、`capability-handshake`、`connection-slot`,以及
+ `project-files` / `ancestor-files` / `ancestor-markers` / `personal-config` /
+ `instruction-imports` / `git-probe` / `image-epoch`,最后是 `remote-open`。
+- `side=transport`:`payload-upload`(序列化、压缩与必要的分段上传)、`open-request`
+ (打开请求往返)、`session-ready`(请求收下到收到 started 事件)。旧版运行端也能从
+ 控制端记录这些阶段;打开请求返回不代表 Agent 已经就绪。
+- `side=host`:`resume-workspaces`、`guest-registration`、`shadow-workspace`、
+ `tunnel-prepare`、`provider-route`、`agent-session`(原生 Agent 启动与会话建立)、
+ `session-registration`。仅实际经过的阶段输出。
+
+每阶段先输出 `status=started`,结束输出 `ok` / `failed`、`durationMs` 和 `elapsedMs`;
+`stage=total` 汇总本端总耗时与 `stagesMs`。使用各端自己的单调时钟,不相减不同电脑的
+墙钟;`remote-open` 包含 transport 与 host 的等待,不能把三侧耗时相加。配置收集仍为
+best-effort,因此某项失败而总启动成功是合法结果。只记录固定阶段名、关联标识、结果和
+耗时,不记录配置正文、路径、消息、凭证或错误正文,不改变日志上报白名单。
+运行端 `stage=total` 另带 `execServer`:`shortcutEnabled`、`ancestorLevels`(收到的祖先快照层数)、
+`connections`(识别到的执行环境连接数)、`answered`(本地回答数)、`forwarded`(转发消息数)。
+计数仅覆盖创建至 started/失败,不含首轮消息及后续工具调用;只含布尔值和计数,无路径与 RPC 内容。
+没有此字段不能推断优化已启用;`shortcutEnabled=false` 需核对虚拟工作区或更早的启动失败,
+`ancestorLevels=0` 需核对快照传递,`connections=0` 需核对执行环境接线。已启用且连接存在却
+`answered=0`、转发很多时,再核对查询是否属于已确认不存在的路径;不能仅凭零命中扩大短路范围。
+Codex 的 `session-ready` 还包括原生会话启动时经执行环境读取项目说明与 Skill 的多轮往返,
+不能直接称为模型推理耗时;同一供应商的项目任务与空任务对照可帮助区分项目初始化开销。
+若带 Skill 的项目显著更慢,可在同一临时项目里用「无 Skill → 一个最小 Skill → 撤回 Skill」
+对照。2026-10-26 实测为 5.3s → 37.4s → 6.0s;一个 Skill 就触发沿 36 层目录逐个检查
+三种插件清单的 108 次查询,全部不存在,扫描阶段占 32.3s。原项目同类扫描占 59.4s / 73.6s。
+Git 元数据查询可以成批并发,不能仅按总查询数推断耗时;应区分串行目录探测与本机处理时间。
+`host/execServerShortcut.ts` 在实际运行 Agent 的电脑上减少已确认不存在的目录查询;供应商组
+中转时还需核对最终运行端。控制端更新不能证明该短路已经生效,仍收到虚拟垫层的查询时应先
+核对运行端版本和路径。镜像外未知路径必须保留转发,不能为省往返一律回答不存在。
+
+2026-10-26 本机隔离对照(Windows,真实 Codex/exec-server 与生产 Controller/Host,模型回复和
+插件业务为 loopback mock,不调用分享供应商):同一 Skill 项目,只替换短路返回值,分别不加延迟与
+在每次 poll/push 返回前增加 100ms。创建到 handle 返回的单次样本为:
+
+| 模拟链路 | 关闭短路 | 开启短路 | 启动阶段本地回答 |
+| --- | ---: | ---: | ---: |
+| 无附加延迟 | 615ms | 399ms | 128 次 |
+| poll/push 各附加 100ms | 14,649ms | 4,150ms | 128 次 |
+
+有延迟组创建耗时下降 71.7%;启动阶段元数据转发 157 → 29,总执行环境转发 164 → 36。
+这是模拟链路的样本,不是线上 SLA,也不等同于普通本地供应商的直接启动路径。
+四组均验证 Skill 描述进入模型、真实命令读回 Skill 正文,以及通过真实 Cindy MCP 网关完成
+`ghost_list` / `ghost_info` / `ghost_call` 并收到 mock 插件业务结果。运行端原生插件按 guest 隔离关闭,
+不包含第三方插件安装、原生插件运行时或 UI 验收。`mirror.test.ts` 另验证三种真实存在的插件清单
+在映射路径和原始绝对路径下仍转发,不会被判为不存在。
+
+当前源码本机能够命中;尚未证明原分享运行端未命中的具体原因,不应把控制端加日志或本机通过
+写成线上已修复。现场查询格式、方法和消息长度符合短路入口,最终运行端版本及接线路径仍待核验。
+本次补齐命中统计与可重复对照;测试还修正了 mock 调用方式,并阻止测试引擎后台同步原生插件目录,
+避免 Windows 遗留 Git 子进程影响收尾。
+
+复跑:`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 跳过。
+
+实现:`remote-agent/startupTiming.ts`、`controller/startRemote.ts`、
+`controller/runClient.ts` 与 `host/runHost.ts`;回归:`__tests__/roundtrip.test.ts`
+以及 `__tests__/startupProbe.e2e.test.ts`、`__tests__/mirror.test.ts`
+(上述路径均相对 Desktop main 的 `remote-agent/`,首项相对 Desktop main)。
+
`device-link request slow/failed/timeout` 另记录 `firstWriteWaitMs`(请求建立到首次
WebSocket 写入成功)与 `afterFirstWriteMs`(首次写入到结束);从未写出时记录
`firstWrite=none`。写入成功不是送达回执,后半段仍包含 socket/relay/网络、对端处理和
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 481a7d8e15..7f5f345cea 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -266,6 +266,7 @@ test("real agent integration tests are explicit tiers outside unit", () => {
assert.deepEqual(desktop.tiers.e2e.include, [
"src/main/maker-host/__tests__/*.e2e.test.ts",
"src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts",
+ "src/main/remote-agent/__tests__/startupProbe.e2e.test.ts",
]);
});
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 5919387829..7c3520d129 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -99,6 +99,7 @@ const desktopE2eInclude = [
'src/main/maker-host/__tests__/*.e2e.test.ts',
// Guest fork through a provider group with a real Claude Code; skipped without apps/claude-code-bin.
'src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts',
+ 'src/main/remote-agent/__tests__/startupProbe.e2e.test.ts',
];
const mobileGuardInclude = [
// Swift/delegate authorization, recording lifecycle, and native clipping are cross-runtime contracts.