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。

test: 远程会话路径投影的工作量不应随别名数×字符串数相乘 (#7710)

PraiseZhub1fc37019330
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.ts
index 3f66537887..67a031dc06 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
@@ -5,9 +5,11 @@ import { pathToFileURL } from 'node:url';
import { createComputerMcpServer, registerGetCurrentSessionIdTool, XdtHelperToolRegistry } from '@cindy/mcps';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import type { AgentEvent } from '@cindy/maker-core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
+import { RemoteEventProjection } from '../../controller/eventProjection';
import { mapExecServerParams, mapExecServerResult, execServerActions } from '../../controller/execServerRelay';
import { RemoteExecutor } from '../executor';
import { ExecutorGate } from '../gate';
@@ -921,3 +923,174 @@ describe('virtual workspace', () => {
}
});
});
+
+/**
+ * #7710:远程会话里每个事件、每段输出都要做路径投影,别名多时按「别名数 × 字符串数」重复排序、重建
+ * 正则、同步 realpath,把主窗口卡住。这里经生产入口(mapTextFromAgent / mapTextForAgent /
+ * RemoteEventProjection.project)断言工作量只随文本增长,并保证投影结果与别名变化的语义不变。
+ * 失败输入:338 条别名 + 1000 个不含路径的短字符串。tier:unit(内存与临时目录,无真实等待)。
+ */
+describe('path projection cost with many aliases', () => {
+ const VIRTUAL = '/Users/agent/Library/Application Support/Cindy/remote-agent/workspaces/0123456789abcdef/run/fs';
+
+ let workspaces = 0;
+ function manyAliasWorkspace(count = 338) {
+ const base = path.join(root, 'many-' + (workspaces += 1));
+ const project = path.join(base, 'work');
+ fs.mkdirSync(project, { recursive: true });
+ const dirs = Array.from({ length: count }, (_, index) => {
+ const dir = path.join(base, 'dirs', 'd' + index);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+ });
+ const aliases = [{ from: VIRTUAL + '/workspace', to: project },
+ ...dirs.map((to, index) => ({ from: VIRTUAL + '/additional/runtime-' + index, to }))];
+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases });
+ workspace.setVirtualRoot(VIRTUAL);
+ return { project, dirs, workspace };
+ }
+
+ /** 统计 run 期间的别名排序次数、RegExp 构造次数与同步 realpath 次数(含 native)。 */
+ function measure<T>(run: () => T) {
+ const counts = { sorts: 0, regexps: 0, realpaths: 0 };
+ const sort = Array.prototype.sort;
+ const realpath = fs.realpathSync;
+ const native = realpath.native;
+ const RegExpOriginal = globalThis.RegExp;
+ Array.prototype.sort = function (this: unknown[], ...args: Parameters<typeof sort>) {
+ if (this.length >= 100 && typeof (this[0] as { from?: unknown } | undefined)?.from === 'string') counts.sorts += 1;
+ return sort.apply(this, args);
+ } as typeof sort;
+ fs.realpathSync = Object.assign(((...args: Parameters<typeof realpath>) => { counts.realpaths += 1; return realpath(...args); }) as typeof realpath,
+ { native: ((...args: Parameters<typeof native>) => { counts.realpaths += 1; return native(...args); }) as typeof native });
+ vi.stubGlobal('RegExp', new Proxy(RegExpOriginal, { construct(target, args) { counts.regexps += 1; return Reflect.construct(target, args); } }));
+ const started = performance.now();
+ try {
+ const value = run();
+ return { value, ...counts, elapsed: performance.now() - started };
+ } finally {
+ vi.unstubAllGlobals();
+ fs.realpathSync = realpath;
+ Array.prototype.sort = sort;
+ }
+ }
+
+ const tick = () => new Promise<void>((resolve) => { setImmediate(resolve); });
+
+ it('sorts aliases and builds prefix patterns once however many short strings are projected', () => {
+ const texts = (count: number) => Array.from({ length: count }, (_, index) => '第 ' + index + ' 条输出:ok');
+ const single = manyAliasWorkspace().workspace;
+ const one = measure(() => single.mapTextFromAgent(texts(1)[0]));
+ const { workspace } = manyAliasWorkspace();
+ const many = measure(() => texts(1000).map((text) => workspace.mapTextFromAgent(text)));
+ expect(many.value).toEqual(texts(1000));
+ expect(many.sorts).toBe(1);
+ expect(many.regexps).toBe(one.regexps);
+ expect(many.elapsed).toBeLessThan(400);
+ });
+
+ it('resolves canonical alias targets once per batch instead of once per string', async () => {
+ const { workspace } = manyAliasWorkspace();
+ const aliases = workspace.agentPathPrefixes().length;
+ const toolOutputs = (count: number) => Array.from({ length: count }, (_, index) => 'line ' + index + ' of tool output');
+ const batch = async (count: number) => {
+ await tick();
+ return measure(() => toolOutputs(count).map((text) => workspace.mapTextForAgent(text)));
+ };
+ const few = await batch(50);
+ const many = await batch(500);
+ expect(many.value).toEqual(toolOutputs(500));
+ expect(many.realpaths).toBe(few.realpaths);
+ expect(many.realpaths).toBeLessThanOrEqual(aliases * 2);
+ expect(many.sorts).toBe(1);
+ });
+
+ it('projects streamed remote events without per-delta alias work', () => {
+ const { workspace } = manyAliasWorkspace();
+ const projection = new RemoteEventProjection(workspace);
+ const deltas = Array.from({ length: 500 }, (_, index) => ({
+ type: 'text', source: 'claude-code', data: { text: '第' + index + '段 ', isFinal: false, agentMessageId: 'm1' },
+ }) as AgentEvent);
+ const work = measure(() => deltas.flatMap((event) => projection.project(event)));
+ expect(work.value.map((event) => (event.data as { text: string }).text).join('') + projection.flush().map((event) => (event.data as { text: string }).text).join(''))
+ .toBe(deltas.map((event) => (event.data as { text: string }).text).join(''));
+ expect(work.sorts).toBeLessThanOrEqual(1);
+ expect(work.realpaths).toBe(0);
+ });
+
+ const SETS = [
+ { name: 'posix', virtual: '/Users/agent/workspace/p' },
+ { name: 'windows', virtual: 'C:\\Agent\\工作 目录' },
+ ];
+ const inputs = (virtual: string) => {
+ const url = 'file://' + (virtual.startsWith('/') ? virtual : '/' + virtual.replace(/\\/g, '/')) + '/src/a.ts';
+ const escaped = virtual.replace(/\\/g, '\\\\') + '\\\\src\\\\a.ts';
+ return {
+ plain: '编辑了 ' + virtual + '/src/a.ts 然后运行 ' + virtual + '/package.json。',
+ chinese: '文件在 ' + virtual + '/中文 目录/报告.md,已保存',
+ json: JSON.stringify({ file: virtual + '/src/a.ts', list: [virtual + '/b', 'plain'] }),
+ fileUri: '打开 ' + url + ' 看看',
+ code: '`' + virtual + '/src/a.ts` 和 <' + virtual + '/src/b.ts> 与 [x](<' + virtual + '/c.md>)',
+ escaped: '"' + escaped + '"',
+ noPath: '/api/v1 与 relative/path 不是影子路径',
+ };
+ };
+
+ it.each(SETS)('projects the same text with a reused or fresh alias array ($name paths)', ({ virtual }) => {
+ const local = path.join(root, 'real 目录');
+ fs.mkdirSync(local);
+ const aliases = [{ from: virtual, to: local }, { from: virtual + '/deep', to: path.join(root, 'deep') }];
+ for (const [kind, text] of Object.entries(inputs(virtual))) {
+ for (const options of [{ escapedSeparators: true, separators: 'source' as const }, {}]) {
+ const fresh = () => projectPathText(text, [...aliases], 'text', undefined, options);
+ const reused = [projectPathText(text, aliases, 'text', undefined, options), projectPathText(text, aliases, 'text', undefined, options)];
+ expect([kind, reused[0]]).toEqual([kind, fresh()]);
+ expect([kind, reused[1]]).toEqual([kind, fresh()]);
+ if (kind !== 'noPath' && kind !== 'escaped' && kind !== 'fileUri') expect([kind, reused[0] === text]).toEqual([kind, false]);
+ }
+ }
+ expect(projectPathText(inputs(virtual).noPath, aliases)).toBe(inputs(virtual).noPath);
+ });
+
+ it('reflects aliases added after a projection on the very next call', () => {
+ const { project, workspace } = manyAliasWorkspace(5);
+ const later = path.join(root, 'later');
+ const runtime = path.join(root, 'runtime-dir');
+ const added = path.join(root, 'added');
+ fs.mkdirSync(later);
+ fs.mkdirSync(runtime);
+ fs.mkdirSync(added);
+ const virtualOf = (dir: string) => workspace.mapTextForAgent(path.join(dir, 'f.txt'));
+ expect(virtualOf(later)).toBe(path.join(later, 'f.txt'));
+ expect(workspace.mapTextFromAgent(VIRTUAL + '/extra/f.txt')).toBe(VIRTUAL + '/extra/f.txt');
+
+ workspace.setAliases([{ from: VIRTUAL + '/workspace', to: project }, { from: VIRTUAL + '/extra', to: later }]);
+ expect(virtualOf(later)).toBe(VIRTUAL + '/extra/f.txt');
+ expect(workspace.mapTextFromAgent(VIRTUAL + '/extra/f.txt')).toBe(path.join(later, 'f.txt'));
+
+ workspace.addAliases([{ from: VIRTUAL + '/added', to: added }]);
+ expect(virtualOf(added)).toBe(VIRTUAL + '/added/f.txt');
+ expect(workspace.mapTextFromAgent(VIRTUAL + '/added/f.txt')).toBe(path.join(added, 'f.txt'));
+
+ const [virtual] = workspace.virtualizeDirs([runtime]);
+ expect(virtualOf(runtime)).toBe(virtual + '/f.txt');
+ expect(workspace.mapTextFromAgent(virtual + '/f.txt')).toBe(path.join(runtime, 'f.txt'));
+ expect(workspace.agentPathPrefixes()).toContain(virtual);
+ });
+
+ it.skipIf(process.platform === 'win32')('follows a symlinked alias target that is retargeted between batches', async () => {
+ const project = path.join(root, 'work');
+ const first = path.join(root, 'first');
+ const second = path.join(root, 'second');
+ const link = path.join(root, 'link');
+ for (const dir of [project, first, second]) fs.mkdirSync(dir);
+ fs.symlinkSync(first, link);
+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: VIRTUAL + '/workspace', to: project }, { from: VIRTUAL + '/link', to: link }] });
+ workspace.setVirtualRoot(VIRTUAL);
+ expect(workspace.mapTextForAgent(path.join(first, 'f.txt'))).toBe(VIRTUAL + '/link/f.txt');
+ fs.unlinkSync(link);
+ fs.symlinkSync(second, link);
+ await tick();
+ expect(workspace.mapTextForAgent(path.join(second, 'f.txt'))).toBe(VIRTUAL + '/link/f.txt');
+ });
+});