Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): resolve exec-server output paths asynchronously
MagicLizi9970f18ec8eb
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.tsindex d4fd71ffb3..645ac9b958 100644--- a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts@@ -10,7 +10,7 @@ import { PassThrough } from 'node:stream';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const spawned = vi.hoisted(() => ({ lines: [] as string[] }));+const spawned = vi.hoisted(() => ({ lines: [] as string[], outputs: [] as PassThrough[], close: [] as Array<() => void> }));vi.mock('node:child_process', async (importOriginal) => ({...(await importOriginal<typeof import('node:child_process')>()),@@ -24,6 +24,8 @@ vi.mock('node:child_process', async (importOriginal) => ({child.stdin = new PassThrough();child.stdout = new PassThrough();child.stderr = new PassThrough();+ spawned.outputs.push(child.stdout);+ spawned.close.push(() => { child.emit('close', 0, null); });child.kill = () => undefined;child.stdin.on('data', (chunk: Buffer) => {spawned.lines.push(...chunk.toString().split('\n').filter(Boolean));@@ -42,6 +44,8 @@ let root: string;beforeEach(() => {root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-relay-consent-')));spawned.lines = [];+ spawned.outputs = [];+ spawned.close = [];});afterEach(() => {@@ -80,9 +84,106 @@ function setup(authorize?: (action: ExecutorAction) => ExecutorGateDecision) {const send = (message: Record<string, unknown>) =>relay.handle({ t: 'ws', connId: 'c1', kind: 'message', data: JSON.stringify(message) });const sentIds = () => spawned.lines.map((line) => (JSON.parse(line) as { id?: unknown }).id);- return { relay, pending, replies, send, sentIds };+ return { relay, workspace, pending, replies, send, sentIds };}+// 测试价值:异步 realpath 后,真实 stdout 入口必须保序、背压,关闭/重连不能收到旧回复,退出不丢尾部。+// 旧用例只覆盖入站授权;最小输入是两个 JSON-RPC 输出和一次暂停的路径准备。unit,手动释放 Promise。+describe('exec-server asynchronous output projection', () => {+ function holdProjection(workspace: ExecutorWorkspace) {+ let release!: () => void;+ const waiting = new Promise<void>((resolve) => { release = resolve; });+ const prepare = workspace.prepareAgentProjection.bind(workspace);+ const pending: Array<Promise<Awaited<ReturnType<typeof prepare>>>> = [];+ const spy = vi.spyOn(workspace, 'prepareAgentProjection').mockImplementation(() => {+ const result = waiting.then(prepare);+ pending.push(result);+ return result;+ });+ return { release, spy, pending };+ }++ it('holds output in order without blocking other connections while path resolution is waiting', async () => {+ const { relay, workspace, replies } = setup();+ const held = holdProjection(workspace);+ try {+ spawned.outputs[0].write('{"id":1,"result":"first"}\n{"id":2,"result":"second"}\n');+ await vi.waitFor(() => expect(held.pending).toHaveLength(1));+ expect(replies).toEqual([]);+ expect(relay.busy()).toBe(true);+ expect(spawned.outputs[0].isPaused()).toBe(true);+ // 另一条连接有自己的输出队列,不被这条连接的磁盘读取挡住。+ held.spy.mockRestore();+ relay.handle({ t: 'ws', connId: 'c2', kind: 'open', path: '/ws/exec-server' });+ spawned.outputs[1].write('{"id":3,"result":"other"}\n');+ await vi.waitFor(() => expect(replies.map((item) => item.id)).toEqual([3]));+ held.release();+ await vi.waitFor(() => expect(replies.map((item) => item.id)).toEqual([3, 1, 2]));+ await vi.waitFor(() => expect(relay.busy()).toBe(false));+ expect(spawned.outputs[0].isPaused()).toBe(false);+ } finally {+ held.release();+ held.spy.mockRestore();+ relay.close();+ }+ });++ it.each(['close', 'reset'] as const)('discards old output after %s and reusing the connection id', async (action) => {+ const { relay, workspace, replies } = setup();+ const held = holdProjection(workspace);+ try {+ spawned.outputs[0].write('{"id":1,"result":"old"}\n');+ await vi.waitFor(() => expect(held.pending).toHaveLength(1));+ if (action === 'reset') relay.reset();+ else relay.handle({ t: 'ws', connId: 'c1', kind: 'close' });+ held.spy.mockRestore();+ relay.handle({ t: 'ws', connId: 'c1', kind: 'open', path: '/ws/exec-server' });+ spawned.outputs[1].write('{"id":2,"result":"new"}\n');+ held.release();+ await Promise.all(held.pending);+ await vi.waitFor(() => expect(replies).toEqual([{ id: 2, result: 'new' }]));+ } finally {+ held.release();+ held.spy.mockRestore();+ relay.close();+ }+ });++ it('finishes projecting the final reply before closing an exited exec-server connection', async () => {+ const { relay, workspace, replies } = setup();+ const held = holdProjection(workspace);+ try {+ spawned.outputs[0].write('{"id":1,"result":"last"}\n');+ await vi.waitFor(() => expect(held.pending).toHaveLength(1));+ spawned.close[0]();+ expect(relay.busy()).toBe(true);+ held.release();+ await vi.waitFor(() => expect(replies).toEqual([{ id: 1, result: 'last' }]));+ await vi.waitFor(() => expect(relay.busy()).toBe(false));+ } finally {+ held.release();+ held.spy.mockRestore();+ relay.close();+ }+ });++ it('closes only the failed connection without sending an unprojected reply', async () => {+ const { relay, workspace, replies, send, sentIds } = setup();+ const prepare = vi.spyOn(workspace, 'prepareAgentProjection').mockRejectedValueOnce(new Error('path preparation failed'));+ try {+ relay.handle({ t: 'ws', connId: 'c2', kind: 'open', path: '/ws/exec-server' });+ spawned.outputs[0].write('{"id":1,"result":"local path"}\n');+ spawned.outputs[1].write('{"id":2,"result":"other"}\n');+ await vi.waitFor(() => expect(replies).toEqual([{ id: 2, result: 'other' }]));+ send({ id: 3, method: 'fs/exists', params: { path: root } });+ expect(sentIds()).toEqual([]);+ } finally {+ prepare.mockRestore();+ relay.close();+ }+ });+});+describe('exec-server relay with confirmation on this computer', () => {it('uses an explicit session consent for subsequent Codex credential requests', async () => {const workspace = new ExecutorWorkspace({ workingDir: root });diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.tsindex 8bb039b0e7..6235d062b1 100644--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts@@ -25,7 +25,7 @@ import {import { readExistingTextSync } from '../executor/files';import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';import { resolveExecutorShell } from '../executor/shell';-import type { ExecutorWorkspace } from '../executor/workspace';+import type { ExecutorAgentProjection, ExecutorWorkspace } from '../executor/workspace';export const EXEC_SERVER_WS_PATH = '/ws/exec-server';/** exec-server 单行(一条 JSON-RPC 消息)上限:大文件读写的 base64 也在这里面。 */@@ -73,6 +73,8 @@ interface Connection {closed: boolean;/** 有消息在等本机确认时,后面的消息按顺序排在它后面。 */queue?: Promise<void>;+ /** 异步准备输出路径时保持连接内顺序;不占用入站确认队列。 */+ output?: Promise<void>;/*** 还在运行的进程(`process/start` 起的,收到 `process/closed` / `process/exited` 或启动失败前都算)。* Codex 的后台终端就是这些:编号在对方的 Codex 里,进程在这里,连接一断就没了。@@ -292,40 +294,52 @@ function existingTextFor(target: unknown, workspace: ExecutorWorkspace): stringreturn workspace.isSensitive(local) ? null : readExistingTextSync(local);}+/** 一条结果只解析一次目录;磁盘 realpath 走异步文件系统,不阻塞 Electron 主线程。 */+export async function mapExecServerResult(value: unknown, workspace: ExecutorWorkspace, method?: string): Promise<unknown> {+ const directories: string[] = [];+ const collect = (item: unknown): void => {+ if (!item || typeof item !== 'object') return;+ if (Array.isArray(item)) { item.forEach(collect); return; }+ const record = item as Record<string, unknown>;+ if (record.environmentInfo && typeof record.environmentInfo === 'object') {+ const info = record.environmentInfo as Record<string, unknown>;+ for (const dir of [info.userHomeDir, info.tempDir, ...(Array.isArray(info.temporaryDirectories) ? info.temporaryDirectories : [])]) {+ if (typeof dir !== 'string') continue;+ try { directories.push(dir.startsWith('file://') ? fileURLToPath(dir) : dir); } catch { /* 无效 URI 不登记。 */ }+ }+ }+ Object.values(record).forEach(collect);+ };+ collect(value);+ if (directories.length) await workspace.virtualizeDirsAsync(directories);+ return projectExecServerResult(value, await workspace.prepareAgentProjection(), method);+}+/** JSON 层逐字符串投影;文件 base64 数据保持原始字节,进程输出单独解码。 */-export function mapExecServerResult(value: unknown, workspace: ExecutorWorkspace, method?: string): unknown {+function projectExecServerResult(value: unknown, projection: ExecutorAgentProjection, method?: string): unknown {if (typeof value === 'string') {if (value.startsWith('file://')) {try {const uri = new URL(value);const real = fileURLToPath(uri);- const virtual = workspace.toAgentPath(real);+ const virtual = projection.toAgentPath(real);if (virtual === real) return value;uri.host = '';uri.pathname = virtual.replace(/\\/g, '/');return uri.href;} catch { return value; }}- return workspace.mapTextForAgent(value);+ return projection.mapTextForAgent(value);}- if (Array.isArray(value)) return value.map((item) => mapExecServerResult(item, workspace, method));+ if (Array.isArray(value)) return value.map((item) => projectExecServerResult(item, projection, method));if (!value || typeof value !== 'object') return value;const record = value as Record<string, unknown>;- // 初始化里的 HOME / temp 同样只暴露本机虚拟目录;这些别名不增加执行权限。- if (record.environmentInfo && typeof record.environmentInfo === 'object') {- const info = record.environmentInfo as Record<string, unknown>;- const directories = [info.userHomeDir, info.tempDir, ...(Array.isArray(info.temporaryDirectories) ? info.temporaryDirectories : [])];- workspace.virtualizeDirs(directories.flatMap((dir) => {- if (typeof dir !== 'string') return [];- try { return [dir.startsWith('file://') ? fileURLToPath(dir) : dir]; } catch { return []; }- }));- }const currentMethod = typeof record.method === 'string' ? record.method : method;return Object.fromEntries(Object.entries(record).map(([key, item]) => {if (currentMethod === 'process/output' && key === 'chunk' && typeof item === 'string') {- return [key, workspace.mapOutputForAgent(Buffer.from(item, 'base64')).toString('base64')];+ return [key, projection.mapOutputForAgent(Buffer.from(item, 'base64')).toString('base64')];}- return [key, mapExecServerResult(item, workspace, currentMethod)];+ return [key, projectExecServerResult(item, projection, currentMethod)];}));}@@ -363,7 +377,8 @@ export class ExecServerRelay {* 这时断开对方的 Agent 会丢掉它们,连接池不让出名额。*/busy(): boolean {- return this.outbox.length > 0 || Boolean(this.flushing) || this.hasWork();+ return this.outbox.length > 0 || Boolean(this.flushing) || this.hasWork()+ || [...this.connections.values()].some((connection) => Boolean(connection.output));}/** 各条连接上还有没有工作(在跑的进程、启动中的请求、待确认的消息);还没推完的帧不算。 */@@ -413,6 +428,7 @@ export class ExecServerRelay {this.connections.set(connId, connection);child.stdout.setEncoding('utf8');child.stdout.on('data', (chunk: string) => {+ if (connection.closed) return;connection.buffer += chunk;for (;;) {const index = connection.buffer.indexOf('\n');@@ -421,7 +437,7 @@ export class ExecServerRelay {connection.buffer = connection.buffer.slice(index + 1);if (line.trim()) {this.trackOutbound(connection, line);- this.sendMessage(connId, this.projectOutbound(line));+ this.enqueueOutput(connId, connection, line);}}if (connection.buffer.length > MAX_LINE_CHARS) {@@ -430,8 +446,15 @@ export class ExecServerRelay {}});child.stderr.resume();- child.on('error', () => this.dropConnection(connId, true));- child.on('exit', () => this.dropConnection(connId, true));+ child.on('error', () => {+ if (this.connections.get(connId) === connection) this.dropConnection(connId, true);+ });+ // close 在 stdout 完全读完后触发;尾部结果的异步投影完成后才通知对端连接结束。+ child.on('close', () => {+ void (connection.output ?? Promise.resolve()).then(() => {+ if (this.connections.get(connId) === connection) this.dropConnection(connId, true);+ });+ });}private forward(connId: string, data: string): void {@@ -558,12 +581,36 @@ export class ExecServerRelay {}));}- private projectOutbound(line: string): string {+ private enqueueOutput(connId: string, connection: Connection, line: string): void {+ connection.child.stdout.pause();+ const next = (connection.output ?? Promise.resolve()).then(async () => {+ if (connection.closed) return;+ const projected = await this.projectOutbound(line);+ if (!connection.closed) this.sendMessage(connId, projected);+ }).catch(() => {+ // 不发送未投影的本机路径;只结束这条连接,不能影响同一设备上的其它任务。+ if (!connection.closed) {+ this.deps.log?.warn('remote agent: exec-server output projection failed; closing connection', { connId });+ this.dropConnection(connId, true);+ }+ });+ connection.output = next;+ void next.then(() => {+ if (connection.output !== next) return;+ connection.output = undefined;+ if (!connection.closed) connection.child.stdout.resume();+ });+ }++ private async projectOutbound(line: string): Promise<string> {+ let value: unknown;try {- return JSON.stringify(mapExecServerResult(JSON.parse(line), this.deps.workspace));+ value = JSON.parse(line);} catch {- return this.deps.workspace.mapTextForAgent(line);+ const projection = await this.deps.workspace.prepareAgentProjection();+ return projection.mapTextForAgent(line);}+ return JSON.stringify(await mapExecServerResult(value, this.deps.workspace));}private dropConnection(connId: string, notifyRemote: boolean): void {diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.tsindex c58e359135..44fdcfd0d8 100644--- a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts@@ -392,15 +392,79 @@ describe('virtual workspace', () => {const params = mapExecServerParams({ path: 'file:///Users/agent/workspace/a.txt', dataBase64: Buffer.from(project).toString('base64') }, workspace);expect(params).toEqual({ path: pathToFileURL(path.join(project, 'a.txt')).href, dataBase64: Buffer.from(project).toString('base64') });expect(execServerActions('fs/writeFile', params, project)).toEqual([{ kind: 'write', path: path.join(project, 'a.txt') }]);- const result = mapExecServerResult({ result: { cwd: pathToFileURL(project).href } }, workspace);+ const result = await mapExecServerResult({ result: { cwd: pathToFileURL(project).href } }, workspace);expect(JSON.stringify(result)).toContain('file:///Users/agent/workspace');- const output = mapExecServerResult({ method: 'process/output', params: { chunk: Buffer.from(project).toString('base64') } }, workspace) as any;+ const output = await mapExecServerResult({ method: 'process/output', params: { chunk: Buffer.from(project).toString('base64') } }, workspace) as any;expect(Buffer.from(output.params.chunk, 'base64').toString()).toBe('/Users/agent/workspace');const fileData = { result: { dataBase64: Buffer.from(project).toString('base64') } };- expect(Buffer.from((mapExecServerResult(fileData, workspace) as any).result.dataBase64, 'base64').toString()).toBe(project);+ expect(Buffer.from((await mapExecServerResult(fileData, workspace) as any).result.dataBase64, 'base64').toString()).toBe(project);await executor.close();});+ // 测试价值:2026-10-21 实测 exec-server 输出逐字段同步 realpath 拖住主进程;旧路径测试只检查文本。+ // 生产入口 mapExecServerResult:最小多字段结果应异步解析、每条结果复用,下一条刷新;unit,无真实等待。+ it('shares asynchronous canonical paths across one reply and refreshes them for the next reply', async () => {+ vi.stubEnv('PATH', '');+ const project = path.join(root, 'project');+ fs.mkdirSync(project);+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: '/agent/workspace', to: project }] });+ workspace.setVirtualRoot('/agent');+ const native = vi.spyOn(fs.realpathSync, 'native');+ const realpath = vi.spyOn(fs.promises, 'realpath');+ try {+ const first = await mapExecServerResult({ result: { path: project } }, workspace);+ expect(first).toEqual({ result: { path: '/agent/workspace' } });+ expect(native).not.toHaveBeenCalled();+ const reads = realpath.mock.calls.length;+ expect(reads).toBeGreaterThan(0);+ realpath.mockClear();+ const fields = { a: project, b: project, nested: [project, project] };+ expect(await mapExecServerResult({ result: fields }, workspace)).toEqual({+ result: { a: '/agent/workspace', b: '/agent/workspace', nested: ['/agent/workspace', '/agent/workspace'] },+ });+ expect(realpath).toHaveBeenCalledTimes(reads);+ expect(native).not.toHaveBeenCalled();+ } finally {+ native.mockRestore();+ realpath.mockRestore();+ vi.unstubAllEnvs();+ }+ });++ it('refreshes a retargeted directory link and resolves newly announced environment directories asynchronously', async ({ skip }) => {+ vi.stubEnv('PATH', '');+ const first = path.join(root, 'first');+ const second = path.join(root, 'second');+ const link = path.join(root, 'link');+ fs.mkdirSync(first);+ fs.mkdirSync(second);+ try {+ try { fs.symlinkSync(first, link, process.platform === 'win32' ? 'junction' : 'dir'); }+ catch { return skip(); }+ const workspace = new ExecutorWorkspace({ workingDir: root, aliases: [{ from: '/agent/workspace', to: link }] });+ workspace.setVirtualRoot('/agent');+ expect(await mapExecServerResult({ result: first }, workspace)).toEqual({ result: '/agent/workspace' });+ fs.unlinkSync(link);+ fs.symlinkSync(second, link, process.platform === 'win32' ? 'junction' : 'dir');+ const native = vi.spyOn(fs.realpathSync, 'native');+ try {+ expect(await mapExecServerResult({ result: { text: second, path: pathToFileURL(second).href } }, workspace))+ .toEqual({ result: { text: '/agent/workspace', path: 'file:///agent/workspace' } });+ const temp = path.join(root, 'announced temp');+ fs.mkdirSync(temp);+ const value = await mapExecServerResult({ result: { environmentInfo: { tempDir: pathToFileURL(temp).href } } }, workspace) as {+ result: { environmentInfo: { tempDir: string } };+ };+ expect(value.result.environmentInfo.tempDir).toMatch(/^file:\/\/\/agent\/additional\/runtime-/);+ expect(native).not.toHaveBeenCalled();+ } finally {+ native.mockRestore();+ }+ } finally {+ vi.unstubAllEnvs();+ }+ });+it.skipIf(process.platform === 'win32')('maps Codex sandbox permissions from a Windows agent and drops paths that only exist on the agent computer', () => {const project = path.join(root, 'real project');const temp = path.join(root, 'temp');diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.tsindex a7f044cbd4..093b7d41c3 100644--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts@@ -29,6 +29,13 @@ export interface ExecutorWorkspaceRoots {aliases?: readonly ExecutorPathAlias[];}+/** 单条返回结果共用的路径视图;不用于文件访问授权。 */+export interface ExecutorAgentProjection {+ toAgentPath(input: string): string;+ mapTextForAgent(text: string, context?: PathTextContext): string;+ mapOutputForAgent(data: Buffer): Buffer;+}+export class ExecutorPathError extends Error {constructor(message: string) {super(message);@@ -63,6 +70,36 @@ function realPathOrAncestorPortable(target: string): string {return realPathOrAncestorWith(target, fs.realpathSync);}+/** realpath 的磁盘访问交给 Node 文件系统线程池,不能在输出热路径阻塞 Electron。 */+async function realPathOrAncestorAsync(+ target: string, resolveRealpath: (target: string) => Promise<string> = fs.promises.realpath,+): Promise<string> {+ let current = path.resolve(target);+ const rest: string[] = [];+ for (;;) {+ try {+ const real = await resolveRealpath(current);+ return rest.length ? path.join(real, ...rest.reverse()) : real;+ } catch {+ const parent = path.dirname(current);+ if (parent === current) return path.resolve(target);+ rest.push(path.basename(current));+ current = parent;+ }+ }+}++function portableRealpathAsync(target: string): Promise<string> {+ return new Promise((resolve, reject) => fs.realpath(target, (error, real) => error ? reject(error) : resolve(real)));+}++function projectUtf8Output(data: Buffer, project: (text: string) => string): Buffer {+ const text = data.toString('utf8');+ if (data.includes(0) || !Buffer.from(text, 'utf8').equals(data)) return data;+ const projected = project(text);+ return projected === text ? data : Buffer.from(projected, 'utf8');+}+function isInside(child: string, parent: string): boolean {const relative = path.relative(parent, child);return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));@@ -533,6 +570,10 @@ export class ExecutorWorkspace {if (path.resolve(canonical) !== path.resolve(alias.to)) expanded.push({ from: alias.from, to: canonical });}}+ this.installAliases(expanded);+ }++ private installAliases(expanded: readonly ExecutorPathAlias[]): void {const seen = new Set<string>();this.aliases = expanded.filter((alias) => {@@ -588,6 +629,22 @@ export class ExecutorWorkspace {});}+ /** exec-server 初始化返回的目录也异步解析;等待期间新增的别名不能被旧快照覆盖。 */+ async virtualizeDirsAsync(dirs: readonly string[]): Promise<void> {+ if (!this.virtualRoot) return;+ const native = /^[A-Za-z]:|^\\\\/.test(this.virtualRoot) ? path.win32 : path.posix;+ for (const dir of dirs) {+ const real = this.resolve(dir);+ if (this.aliases.some((alias) => path.resolve(alias.to) === real)) continue;+ const canonical = await Promise.all([+ realPathOrAncestorAsync(real), realPathOrAncestorAsync(real, portableRealpathAsync),+ ]);+ if (this.aliases.some((alias) => path.resolve(alias.to) === real)) continue;+ const from = native.join(this.virtualRoot, 'additional', 'runtime-' + this.aliases.length);+ this.installAliases([...this.aliases, ...[real, ...canonical].map((to) => ({ from, to }))]);+ }+ }+/** 任务运行中附加目录变化时更新。 */setExtraDirs(extraDirs: readonly string[]): void {this.extraDirs = extraDirs.filter((dir) => path.isAbsolute(dir)).map((dir) => path.resolve(dir));@@ -605,8 +662,8 @@ export class ExecutorWorkspace {}/** 影子路径对应的本机路径;不是影子路径(Agent 主机自己的路径)时返回 null。 */- localPathFromAgent(input: string): string | null {- for (const alias of this.aliases) {+ localPathFromAgent(input: string, aliases: readonly ExecutorPathAlias[] = this.aliases): string | null {+ for (const alias of aliases) {const rest = stripAliasPrefix(input, alias.from);if (rest !== null) return rest ? path.join(alias.to, ...rest.split('/')) : alias.to;}@@ -635,7 +692,11 @@ export class ExecutorWorkspace {/** 本机真实路径投影到 Agent 主机上的路径;仅匹配完整路径段。 */toAgentPath(input: string): string {if (!this.virtualRoot) return input;- const aliases = [...this.aliases].sort((a, b) => b.to.length - a.to.length);+ return this.pathToAgent(input, this.aliases);+ }++ private pathToAgent(input: string, pathAliases: readonly ExecutorPathAlias[]): string {+ const aliases = [...pathAliases].sort((a, b) => b.to.length - a.to.length);for (const alias of aliases) {const rest = stripAliasPrefix(input, alias.to);if (rest === null) continue;@@ -656,14 +717,33 @@ export class ExecutorWorkspace {{ ...options, continuesName: this.continuesName });}+ /** 每条结果刷新一次 canonical 目录;同一结果的所有字段复用,后续结果仍能看到 junction 的变化。 */+ async prepareAgentProjection(): Promise<ExecutorAgentProjection> {+ if (!this.virtualRoot) return { toAgentPath: (text) => text, mapTextForAgent: (text) => text, mapOutputForAgent: (data) => data };+ const aliases = this.aliases;+ const targets = [...new Set(aliases.map((alias) => alias.to))];+ const canonical = new Map(await Promise.all(targets.map(async (target) =>+ [target, await realPathOrAncestorAsync(target)] as const)));+ const projectedAliases = this.agentAliases(aliases, canonical);+ const pathAliases = aliases.flatMap((alias) => [alias, { from: alias.from, to: canonical.get(alias.to)! }]);+ const project = (text: string, context: PathTextContext = 'text') =>+ projectPathText(text, projectedAliases, context, (mapped) => fs.existsSync(this.localPathFromAgent(mapped, aliases) ?? mapped),+ { continuesName: this.continuesName });+ return {+ toAgentPath: (input) => this.pathToAgent(input, pathAliases),+ mapTextForAgent: project,+ mapOutputForAgent: (data) => projectUtf8Output(data, project),+ };+ }+/** 本机真实路径(含 Git Bash 写法)→ Agent 看到的虚拟路径。 */- private agentAliases(): ExecutorPathAlias[] {+ private agentAliases(aliases: readonly ExecutorPathAlias[] = this.aliases, canonical?: ReadonlyMap<string, string>): ExecutorPathAlias[] {const seen = new Set<string>();- return this.aliases.flatMap((alias) => {+ return aliases.flatMap((alias) => {// A junction/symlink can be resolved differently by the Windows runner and by// the process that created the alias. Include the current canonical target at// projection time so both spellings still map to the same virtual directory.- const targets = [alias.to, realPathOrAncestor(alias.to)];+ const targets = [alias.to, canonical ? canonical.get(alias.to)! : realPathOrAncestor(alias.to)];return targets.flatMap((target) => {const real = target.replace(/\\/g, '/');const entries: ExecutorPathAlias[] = [{ from: real, to: alias.from }];@@ -845,11 +925,8 @@ export class ExecutorWorkspace {}mapOutputForAgent(data: Buffer): Buffer {- const text = data.toString('utf8');// 二进制 stdout 不做 UTF-8 往返,避免 exec.run / process/output 改变原始字节。- if (data.includes(0) || !Buffer.from(text, 'utf8').equals(data)) return data;- const projected = this.mapTextForAgent(text);- return projected === text ? data : Buffer.from(projected, 'utf8');+ return projectUtf8Output(data, (text) => this.mapTextForAgent(text));}/** Agent 写入的文件字节;original 为写入前的文本内容(见 mapContentFromAgent)。 */