Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(orca): 支持创建 Worker 时可选绑定工作目录 (#4332)

Dashd07b8382a7fd
diff --git a/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts b/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
index 93d263dd7b..f5f6514420 100644
--- a/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
@@ -71,6 +71,19 @@ afterEach(async () => {
});
describe('projectGitBootstrap', () => {
+ // Windows strips trailing spaces in ordinary directory names; this identity fixture is POSIX-only.
+ it.skipIf(process.platform === 'win32')('initializes only the exact whitespace-suffixed project', async () => {
+ const parent = await makeTempDir();
+ const plain = path.join(parent, 'project');
+ const exact = path.join(parent, 'project ');
+ await fs.mkdir(plain);
+ await fs.mkdir(exact);
+ const request = { workingDir: exact, workspaceKind: 'project', autoSnapshotEnabled: true };
+ expect(await ensureProjectGitInitialized(request)).toMatchObject({ status: 'initialized', repoRoot: exact });
+ expect(await isGitRepo(plain)).toBe(false);
+ expect(await isGitRepo(exact)).toBe(true);
+ expect(await ensureProjectGitInitialized(request)).toMatchObject({ status: 'already-git', repoRoot: exact });
+ });
it('only considers local project workspaces bootstrap candidates', () => {
const workingDir = path.resolve('project');
expect(
diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts
index 74c20518e8..859b870cb3 100644
--- a/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts
@@ -69,6 +69,13 @@ it('preserves real Git snapshots for attached, detached, unborn, missing and nes
});
if (process.platform !== 'win32') {
+ const spaced = path.join(fixture, 'repo ');
+ await fs.mkdir(spaced);
+ await git('-C', spaced, 'init', '--initial-branch=main');
+ expect((await detectCwd(spaced)).repoRoot).toBe(await fs.realpath(spaced));
+ await git('-C', spaced, '-c', 'user.name=Test', '-c', '[email protected]',
+ 'commit', '--allow-empty', '-m', 'fixture');
+ expect((await detectCwd(spaced)).repoRoot).toBe(await fs.realpath(spaced));
const newlinePath = path.join(fixture, 'line\nbreak');
await git('worktree', 'add', '--detach', newlinePath);
const newlineSnapshot = await detectCwd(newlinePath);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
index cfe28ff6e1..07c586f2e3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
@@ -32,6 +32,11 @@ describe('normalizeWorkdirKey(纯字符串归一化,不碰 fs)', () => {
});
describe('normalize(坏形态清洗)', () => {
+ it('preserves existing literal keys and keeps whitespace-distinct project policies separate', () => {
+ const prefs = { disabledByWorkdir: { '/repo': ['old-plugin'], '/repo ': ['other-plugin'] } };
+ expect(__testing.normalize(prefs)).toEqual(prefs);
+ expect(__testing.normalizeWorkdirKey('/repo ')).toBe('/repo ');
+ });
it('合法条目保留(id 去重排序);空数组、非数组、空目录键全部清掉', () => {
expect(
__testing.normalize({
diff --git a/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts b/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
index 76ea1292c2..654b28f7c4 100644
--- a/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
@@ -39,16 +39,15 @@ const DEFAULTS: GhostWorkdirPrefs = { disabledByWorkdir: {} };
/** 目录键归一化(导出供测试;两端形态判定见文件头注释)。 */
export function normalizeWorkdirKey(dir: string): string {
- const trimmed = dir.trim();
- if (trimmed.length === 0) return '';
- const looksWindows = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.includes('\\');
+ if (dir.trim().length === 0) return '';
+ const looksWindows = /^[A-Za-z]:[\\/]/.test(dir) || dir.includes('\\');
if (looksWindows) {
// win32.normalize 统一分隔符并折叠 '..';根目录(C:\)保留尾分隔符。
- let n = path.win32.normalize(trimmed);
+ let n = path.win32.normalize(dir);
if (n.length > 3 && (n.endsWith('\\') || n.endsWith('/'))) n = n.slice(0, -1);
return n.toLowerCase();
}
- let n = path.posix.normalize(trimmed);
+ let n = path.posix.normalize(dir);
if (n.length > 1 && n.endsWith('/')) n = n.slice(0, -1);
return n;
}
diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
index 2b3336bf49..f668a12be1 100644
--- a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
@@ -12,6 +12,7 @@ import path from 'node:path';
import { createLogger } from '../logger';
import { gitExec, GitExecError } from '../worktree/gitExec';
+import { gitPathOutput } from '../worktree/gitPathOutput';
import {
buildSnapshotFilePlan,
resolveSnapshotGitPath,
@@ -950,7 +951,7 @@ async function detectBlockedGitState(repoPath: string): Promise<SnapshotBlockedG
async function resolveGitInternalPath(repoPath: string, marker: string): Promise<string | null> {
const { stdout } = await gitExec(['rev-parse', '--git-path', marker], repoPath);
- const gitPath = stdout.trim();
+ const gitPath = gitPathOutput(stdout);
if (!gitPath) return null;
return path.isAbsolute(gitPath) ? gitPath : path.resolve(repoPath, gitPath);
}
diff --git a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
index b3f9f25aba..e36e629f08 100644
--- a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
+++ b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
@@ -64,7 +64,7 @@ export async function ensureProjectGitInitialized(
return { status: 'skipped', reason: skipReason };
}
- const workingDir = path.resolve(request.workingDir!.trim());
+ const workingDir = path.resolve(request.workingDir!);
return withProjectBootstrapQueue(workingDir, () =>
ensureProjectGitInitializedInner({ ...request, workingDir }),
);
diff --git a/apps/desktop/src/main/git-snapshot/savepointCleanup.ts b/apps/desktop/src/main/git-snapshot/savepointCleanup.ts
index 7e2f3c7167..4752c81a10 100644
--- a/apps/desktop/src/main/git-snapshot/savepointCleanup.ts
+++ b/apps/desktop/src/main/git-snapshot/savepointCleanup.ts
@@ -20,6 +20,7 @@ import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
import { createLogger } from '../logger';
import { gitExec } from '../worktree/gitExec';
+import { gitPathOutput } from '../worktree/gitPathOutput';
import { deleteSavepointRef, listSavepointRefs } from './savepointRefs';
const log = createLogger('git-snapshot');
@@ -35,7 +36,7 @@ const RECONCILE_MAX_WORKDIRS = 200;
*/
async function resolveSavepointRepoRoot(workingDir: string): Promise<string | null> {
try {
- const repoRoot = (await gitExec(['rev-parse', '--show-toplevel'], workingDir)).stdout.trim();
+ const repoRoot = gitPathOutput((await gitExec(['rev-parse', '--show-toplevel'], workingDir)).stdout);
if (!repoRoot) return null;
const [gitDir, commonDir] = await Promise.all([
gitExec(['rev-parse', '--git-dir'], workingDir),
@@ -45,8 +46,8 @@ async function resolveSavepointRepoRoot(workingDir: string): Promise<string | nu
// WorktreeManager.detectCwd 同口径;用 repoRoot 作基准会在子目录场景
// 下解析错。
const isInsideWorktree =
- path.resolve(workingDir, gitDir.stdout.trim()) !==
- path.resolve(workingDir, commonDir.stdout.trim());
+ path.resolve(workingDir, gitPathOutput(gitDir.stdout)) !==
+ path.resolve(workingDir, gitPathOutput(commonDir.stdout));
if (isInsideWorktree) return null;
return repoRoot;
} catch {
diff --git a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
index 1d83f3a08d..3ed96d4c60 100644
--- a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
@@ -138,6 +138,13 @@ describe('normalizeHistoryWorkingDir', () => {
});
describe('resolveStoredWorkingDirCandidates', () => {
+ it('keeps whitespace-distinct project identities separate', async () => {
+ const db = useDb();
+ insertSession(db, 'plain', '/repo/project', 1_000);
+ insertSession(db, 'space', '/repo/project ', 2_000);
+ expect(await resolveStoredWorkingDirCandidates('/repo/project ')).toEqual(['/repo/project ']);
+ expect(await resolveStoredWorkingDirCandidates('/repo/project')).toEqual(['/repo/project']);
+ });
it('returns every stored spelling of the same physical directory, including trailing slashes', async () => {
const db = useDb();
insertSession(db, 's1', 'D:/Project-001', 1_000);
diff --git a/apps/desktop/src/main/localDb/workingDirHistoryFilter.ts b/apps/desktop/src/main/localDb/workingDirHistoryFilter.ts
index 18f2fa1f82..d64c9d29eb 100644
--- a/apps/desktop/src/main/localDb/workingDirHistoryFilter.ts
+++ b/apps/desktop/src/main/localDb/workingDirHistoryFilter.ts
@@ -61,12 +61,12 @@ function isUnderManagedDialogueRoot(normalizedDir: string): boolean {
export async function resolveStoredWorkingDirCandidates(
raw: string | null | undefined,
): Promise<string[]> {
- const trimmed = typeof raw === 'string' ? raw.trim() : '';
- const target = normalizeWorkingDirForStorage(trimmed);
+ const original = typeof raw === 'string' ? raw : '';
+ const target = normalizeWorkingDirForStorage(original);
if (!target) return [];
if (isUnderManagedDialogueRoot(target)) {
- const probes = [...new Set([trimmed, target])];
+ const probes = [...new Set([original, target])];
const rows = await getDbClient().query<{ workingDir: string | null }>(
`SELECT DISTINCT working_dir AS workingDir FROM sessions
WHERE working_dir IN (${probes.map(() => '?').join(',')})`,
diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
index 2cb7dd0545..13a342e429 100644
--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
@@ -153,7 +153,6 @@ describe('desktop MCP approval policy', () => {
'cindy_scheduler',
'cindy_memory',
'cindy_helper',
- 'cindy_orca',
// worker → lead 回报通道:执行边界在工具内部 fail-closed, 逐次弹窗
// 会让远端 daemon 等审批超时断链。
'orca_worker_bridge',
@@ -436,3 +435,41 @@ describe('Cindy market action authorization', () => {
expect(getDesktopClaudeReadOnlyAllowedTools()).not.toContain('mcp__cindy__ghost_market_install');
});
});
+
+describe('Orca Worker directory authorization', () => {
+ const policy = (toolName: string | undefined, toolParams?: unknown) =>
+ getDesktopMcpToolApprovalPolicy({ serverName: 'cindy_orca', toolName, toolParams });
+
+ it('reviews every explicit root, including batch entries and JSON payloads', () => {
+ for (const working_dir of ['/private/project', '/remote/project ', '', null]) {
+ for (const [name, params] of [
+ ['create_worker', { working_dir }],
+ ['create_workers', { workers: [{ label: 'inherits' }, { working_dir }] }],
+ ] as const) {
+ expect(policy(name, params)).toBe('prompt-each-time');
+ expect(policy(name, JSON.stringify(params))).toBe('prompt-each-time');
+ }
+ }
+ expect(getDesktopClaudeReadOnlyAllowedTools()).not.toContain('mcp__cindy_orca__create_worker');
+ expect(getDesktopClaudeReadOnlyAllowedTools()).not.toContain('mcp__cindy_orca__create_workers');
+ });
+
+ it('preserves inherited-directory creation and other Orca operations', () => {
+ expect(policy('create_worker', { label: 'inherits' })).toBe('auto-approve');
+ expect(policy('create_workers', { workers: [{ label: 'a' }, { label: 'b' }] })).toBe('auto-approve');
+ expect(policy('send_to_worker', { worker_id: 'a', message: 'continue' })).toBe('auto-approve');
+ expect(policy('list_workers')).toBe('auto-approve');
+ });
+
+ it('does not infer directory inheritance from missing approval evidence', () => {
+ expect(policy(undefined)).toBe('prompt-each-time');
+ expect(policy(undefined, { working_dir: '/other' })).toBe('prompt-each-time');
+ for (const name of ['create_worker', 'create_workers']) {
+ for (const params of [undefined, 'invalid JSON', [], null]) {
+ expect(policy(name, params)).toBe('prompt-each-time');
+ }
+ }
+ expect(policy('create_workers', {})).toBe('prompt-each-time');
+ expect(policy('create_workers', { workers: [null] })).toBe('prompt-each-time');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts b/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts
index 28e1a8f30a..1337eaaf37 100644
--- a/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts
@@ -217,6 +217,16 @@ describe('DesktopSessionStorage.create workingDir 规范化', () => {
h.rows.clear();
});
+ it.each([undefined, 'ssh-host'])('stores the exact Worker directory identity (remote=%s)', async (remoteHostId) => {
+ const storage = new DesktopSessionStorage();
+ const created = await storage.create({
+ id: 'worker-space', title: 'Worker', workDir: '/repo ',
+ model: 'gpt-5.4', agentKind: 'codex', remoteHostId,
+ });
+ expect(h.captured?.workingDir).toBe('/repo ');
+ expect(created.workDir).toBe('/repo ');
+ });
+
it('Windows 反斜杠路径入库前归一为 storage spelling', async () => {
const storage = new DesktopSessionStorage();
const created = await storage.create({
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 5255f1c873..515d3a08f0 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -908,7 +908,7 @@ export function getMaker(): Maker {
const pluginRegistry = createPluginRegistry();
const resolveIOSSimulatorAccess = (context?: IOSSimulatorMcpCallContext) => {
- const workingDir = context?.workingDir?.trim() || null;
+ const workingDir = context?.workingDir?.trim() ? context.workingDir : null;
// Product access is the installed plugin (enable + workdir disable).
// Leftover Tools-page `builtinTools['ios-simulator']` must not gate runtime.
return getIOSSimulatorPluginAccessDecision(workingDir);
diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
index 02190c5fe2..946a515618 100644
--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
@@ -237,6 +237,22 @@ export function getDesktopMcpToolApprovalPolicy(
if (canAutoApproveCindyArtGhostCall(context)) {
return 'auto-approve';
}
+ // Choosing a new Worker root delegates filesystem access. Do not let the
+ // trusted-server shortcut or a cached server grant authorize another root.
+ // Full Access / Auto / Ask still use their existing permission flow.
+ if (serverName === 'cindy_orca') {
+ if (!toolName) return 'prompt-each-time';
+ if (toolName === 'create_worker' || toolName === 'create_workers') {
+ const params = readJsonObject(toolParams);
+ if (!params) return 'prompt-each-time';
+ const workers = toolName === 'create_worker' ? [params] : params.workers;
+ if (!Array.isArray(workers)) return 'prompt-each-time';
+ if (workers.some((worker) => {
+ const spec = readJsonObject(worker);
+ return !spec || Object.hasOwn(spec, 'working_dir');
+ })) return 'prompt-each-time';
+ }
+ }
const iosSimulatorCall = readIOSSimulatorInnerCall(context);
if (iosSimulatorCall) {
const innerName = iosSimulatorCall.name;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
index cb4aa2b59b..0d1bb691ce 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/collabProjectPolicy.test.ts
@@ -12,21 +12,21 @@ describe('resolveLocalCollabPolicyWorkingDir', () => {
it('drops app-managed dialogue cwd so policy queries use only the user/global level', () => {
expect(
resolveLocalCollabPolicyWorkingDir(
- ' /app-managed/dialogues/2026-08-02/session-1 ',
+ '/app-managed/dialogues/2026-08-02/session-1',
'dialogue',
isManagedDialogueWorkspace,
),
).toBeUndefined();
});
- it('keeps and normalizes an explicitly bound real directory', () => {
+ it('preserves whitespace in an explicitly bound real directory', () => {
expect(
resolveLocalCollabPolicyWorkingDir(
- ' /projects/cindy ',
+ '/projects/cindy ',
'dialogue',
isManagedDialogueWorkspace,
),
- ).toBe('/projects/cindy');
+ ).toBe('/projects/cindy ');
});
it('keeps a project path even when it has the same shape as a managed dialogue cwd', () => {
@@ -54,25 +54,43 @@ describe('assertCollabProjectEnabled', () => {
).not.toThrow();
});
+ it.each(['.cindy-worktrees', '.xdt-worktrees'])('enforces the base policy for %s without changing runtime cwd', (folder) => {
+ const context = { ...project, workingDir: `/projects/repo /${folder}/worker/src` };
+ const calls: Array<string | undefined> = [];
+ expect(() => assertCollabProjectEnabled(context, (_plugin, path) => {
+ calls.push(path);
+ return path !== '/projects/repo ';
+ }, neverManagedDialogue)).toThrow('[PRECONDITION_FAILED] collaboration is disabled for this session');
+ expect(calls).toEqual(['/projects/repo ']);
+ expect(context.workingDir).toBe(`/projects/repo /${folder}/worker/src`);
+ expect(resolveLocalCollabPolicyWorkingDir(context.workingDir, 'project', neverManagedDialogue))
+ .toBe('/projects/repo ');
+ });
+
+ it('keeps imported worktree project overrides independent', () => {
+ const path = '/projects/repo/.worktrees/imported';
+ expect(resolveLocalCollabPolicyWorkingDir(path, 'project', neverManagedDialogue)).toBe(path);
+ });
+
it('rejects a project with collab disabled', () => {
expect(() =>
assertCollabProjectEnabled(project, () => false, neverManagedDialogue),
).toThrow('[PRECONDITION_FAILED] collaboration is disabled for this session');
});
- it('trims the working directory before checking the project policy', () => {
+ it('checks the exact directory rather than its whitespace-stripped sibling', () => {
let checkedPath: string | undefined;
expect(() =>
assertCollabProjectEnabled(
- { ...project, workingDir: ' C:\\projects\\cindy ' },
+ { ...project, workingDir: '/projects/cindy ' },
(_pluginId, workingDir) => {
checkedPath = workingDir;
- return true;
+ return workingDir !== '/projects/cindy ';
},
neverManagedDialogue,
),
- ).not.toThrow();
- expect(checkedPath).toBe('C:\\projects\\cindy');
+ ).toThrow('[PRECONDITION_FAILED] collaboration is disabled for this session');
+ expect(checkedPath).toBe('/projects/cindy ');
});
it('allows dialogue sessions using only the user/global policy', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
index 5275b77b7b..65abab13d9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -211,7 +211,7 @@ describe('iOS Simulator IPC handlers', () => {
const getStatus = vi.fn();
registerTrusted(harness, {
getPluginAccess,
- getSessionContext: async () => ({ workingDir: '/repo/disabled' }),
+ getSessionContext: async () => ({ workingDir: '/repo/disabled ' }),
getStatus,
});
@@ -220,7 +220,7 @@ describe('iOS Simulator IPC handlers', () => {
sessionId: 'session-a',
}),
).rejects.toMatchObject({ code: 'IOS_SIMULATOR_DISABLED' });
- expect(getPluginAccess).toHaveBeenCalledWith('/repo/disabled');
+ expect(getPluginAccess).toHaveBeenCalledWith('/repo/disabled ');
expect(getStatus).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
index 5b4268f06e..c62587a77a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
@@ -284,6 +284,7 @@ describe('OrcaLifecycleService', () => {
agent: 'codex' as AgentKind,
label: 'reviewer',
initialTask: 'review PR',
+ workingDir: '/remote/explicit-project',
}),
).resolves.toMatchObject({
ok: true,
@@ -293,6 +294,7 @@ describe('OrcaLifecycleService', () => {
});
expect(deps.createActiveTeam).not.toHaveBeenCalled();
+ expect(deps.createWorkerInTeam).toHaveBeenCalledWith(expect.objectContaining({ workingDir: '/remote/explicit-project' }));
expect(calls).toEqual([
'createWorkerInTeam:team-existing:reviewer',
'dispatchWorkerTask:create_worker/worker-session-1/initial_task',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 0f11ea03a2..1bd4463f58 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -1,3 +1,4 @@
+import path from 'node:path';
import { resolveAgentCredentialMode, type AgentKind } from '@cindy/maker-core';
import { describe, expect, it, vi } from 'vitest';
@@ -95,6 +96,7 @@ function createDeps(overrides: Partial<OrcaWorkerCreationDeps> = {}) {
})),
getWorkerDefaults: vi.fn(() => ({})),
getWorkerPermissionMode: vi.fn(() => 'auto' as const),
+ resolveWorkerWorkingDir: vi.fn(async (dir) => dir),
getAvailableModels: vi.fn((agent: AgentKind) => (
agent === 'codex'
? [
@@ -186,6 +188,74 @@ function createDeps(overrides: Partial<OrcaWorkerCreationDeps> = {}) {
};
}
+describe('Orca worker working directory', () => {
+ const params: OrcaWorkerCreateParams = {
+ leadSessionId: 'lead-1', role: 'developer', agent: 'codex', label: 'worker',
+ initialTask: 'Run in the assigned project',
+ };
+
+ it('binds the resolved directory before bootstrap (dispatch belongs to lifecycle)', async () => {
+ const requested = path.resolve('candidate link ');
+ const resolved = path.resolve('candidate real ');
+ const { deps, service } = createDeps({
+ resolveWorkerWorkingDir: vi.fn(async () => resolved),
+ });
+ const result = await service.createWorker({ ...params, workingDir: requested });
+ expect(result.ok).toBe(true);
+ expect(deps.resolveWorkerWorkingDir).toHaveBeenCalledWith(requested, expect.objectContaining({ id: 'lead-1' }));
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({
+ workingDir: resolved, workspaceKind: 'project',
+ }));
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ expect(vi.mocked(deps.resolveWorkerWorkingDir).mock.invocationCallOrder[0])
+ .toBeLessThan(vi.mocked(deps.bootstrapSession).mock.invocationCallOrder[0]!);
+ });
+
+ it('preserves Lead directory inheritance when the override is omitted', async () => {
+ const { deps, service } = createDeps();
+ await service.createWorker(params);
+ expect(deps.resolveWorkerWorkingDir).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir: 'C:\\repo' }));
+ });
+
+ it.each(['', ' ', 'relative/project', './project', 'a\0b'])('rejects invalid directory %j before creating anything', async (workingDir) => {
+ const { deps, service } = createDeps();
+ expect(await service.createWorker({ ...params, workingDir })).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });
+ expect(deps.resolveWorkerWorkingDir).not.toHaveBeenCalled();
+ expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ });
+
+ it.each(['missing directory', 'not a directory', 'collaboration disabled'])('does not fall back when resolution fails: %s', async (reason) => {
+ const { deps, service } = createDeps({ resolveWorkerWorkingDir: vi.fn(async () => { throw new Error(reason); }) });
+ expect(await service.createWorker({ ...params, workingDir: path.resolve('candidate') }))
+ .toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });
+ expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ });
+
+ it('uses project context when a dialogue Lead explicitly selects a directory', async () => {
+ const { deps, service } = createDeps();
+ const lead = await deps.getLeadSessionRow('lead-1');
+ vi.mocked(deps.getLeadSessionRow).mockResolvedValue({ ...lead!, workspaceKind: 'dialogue' });
+ const workingDir = path.resolve('explicit project');
+ expect(await service.createWorker({ ...params, workingDir })).toMatchObject({ ok: true });
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir, workspaceKind: 'project' }));
+ });
+
+ it('resolves SSH paths on the inherited host and binds the result', async () => {
+ const { deps, service } = createDeps();
+ const lead = await deps.getLeadSessionRow('lead-1');
+ vi.mocked(deps.getLeadSessionRow).mockResolvedValue({ ...lead!, remoteHostId: 'host-1' });
+ vi.mocked(deps.resolveWorkerWorkingDir).mockResolvedValue('/remote/real');
+ expect(await service.createWorker({ ...params, workingDir: '/remote/project' })).toMatchObject({ ok: true });
+ expect(deps.resolveWorkerWorkingDir).toHaveBeenCalledWith('/remote/project', expect.objectContaining({ remoteHostId: 'host-1' }));
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir: '/remote/real', remoteHostId: 'host-1' }));
+ });
+});
+
describe('OrcaWorkerCreationService', () => {
const workerStatus = (status: OrcaWorkerStatus): OrcaWorkerStatus => status;
diff --git a/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts b/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
index 4c95bf70a0..5ed737e9be 100644
--- a/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
+++ b/apps/desktop/src/main/maker-ipc/collabProjectPolicy.ts
@@ -1,4 +1,5 @@
import { throwIpcError } from '../utils/ipcValidate.js';
+import { normalizeWorkingDirForProjectSettings } from '../../shared/workingDir.js';
export interface CollabProjectPolicyContext {
workingDir?: string | null;
@@ -21,14 +22,13 @@ export function resolveLocalCollabPolicyWorkingDir(
workspaceKind: string | null | undefined,
isManagedDialogueWorkspace: (workingDir: string) => boolean,
): string | undefined {
- const normalizedWorkingDir = workingDir.trim();
if (
- normalizedWorkingDir === '' ||
- (workspaceKind === 'dialogue' && isManagedDialogueWorkspace(normalizedWorkingDir))
+ workingDir.trim() === '' ||
+ (workspaceKind === 'dialogue' && isManagedDialogueWorkspace(workingDir))
) {
return undefined;
}
- return normalizedWorkingDir;
+ return normalizeWorkingDirForProjectSettings(workingDir) ?? workingDir;
}
/**
@@ -52,7 +52,7 @@ export function assertCollabProjectEnabled(
isPluginEnabled: (pluginId: 'collab', workingDir?: string) => boolean,
isManagedDialogueWorkspace: (workingDir: string) => boolean,
): void {
- const workingDir = typeof context.workingDir === 'string' ? context.workingDir.trim() : null;
+ const workingDir = typeof context.workingDir === 'string' ? context.workingDir : null;
if (context.workspaceKind !== 'project' && context.workspaceKind !== 'dialogue') {
throwIpcError(
'PRECONDITION_FAILED',
@@ -61,7 +61,7 @@ export function assertCollabProjectEnabled(
}
// 正常 dialogue 在 createSession 时已经拿到 app 托管的运行目录。这里仍要求非空,
// 防止损坏/legacy 行把空 cwd 带进 Worker bootstrap;区别只在它不参与项目级策略查询。
- if (workingDir === null || workingDir === '') {
+ if (workingDir === null || workingDir.trim() === '') {
throwIpcError('PRECONDITION_FAILED', 'collaboration requires a session working directory');
}
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index 11e4c240dd..ff3edf8201 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -280,7 +280,7 @@ async function callIOSSimulatorHost<T>(
if (!sessionContext) {
throwIpcError('PERMISSION_DENIED', 'iOS Simulator access is limited to the current task');
}
- const workingDir = sessionContext.workingDir?.trim() || null;
+ const workingDir = sessionContext.workingDir?.trim() ? sessionContext.workingDir : null;
const ownerScopeKey = deps.getOwnerScopeKey();
const assertOwnerScopeCurrent = (): void => {
if (deps.isOwnerBoundaryPending() || deps.getOwnerScopeKey() !== ownerScopeKey) {
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index 64a94a5d72..d5a8e47cf9 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -1,5 +1,6 @@
import type { AgentKind } from '@cindy/maker-core';
import type { AuthStrategy } from '@cindy/model-providers';
+import path from 'node:path';
import { isCredentialModeSwitchBusyError } from '../maker-host/codex-credential-switch.js';
import { isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
@@ -188,6 +189,8 @@ export interface OrcaWorkerCreateParams {
*/
providerId?: string | null;
initialTask?: string;
+ /** Existing absolute directory on the Worker's host; omission inherits Lead. */
+ workingDir?: string;
/** 显式值用于本次创建;缺省读取全局 Worker 创建偏好。 */
workerPermissionMode?: OrcaWorkerPermissionMode;
}
@@ -207,6 +210,8 @@ export interface OrcaWorkerCreationDeps {
getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;
getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;
getWorkerPermissionMode(): OrcaWorkerPermissionMode;
+ /** Validate existence and target project policy before reserving or bootstrapping. */
+ resolveWorkerWorkingDir(dir: string, lead: OrcaLeadSessionSnapshot): Promise<string>;
getAvailableModels(agent: AgentKind): OrcaWorkerModelCapabilities[];
/**
* 从同一次 provider registry 读取构造 Worker 路由上下文。
@@ -680,6 +685,20 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
return { ok: false, errorCode: 'NOT_FOUND', message: `lead session ${params.leadSessionId} not found` };
}
+ let workingDir = lead.workingDir ?? '';
+ if (params.workingDir !== undefined) {
+ const requested = typeof params.workingDir === 'string' ? params.workingDir : '';
+ const paths = lead.remoteHostId ? path.posix : path;
+ if (!requested || requested.length > 4096 || requested.includes('\0') || !paths.isAbsolute(requested)) {
+ return { ok: false, errorCode: 'INVALID_PARAMS', message: 'working_dir must be an existing absolute directory on the Worker host' };
+ }
+ try {
+ workingDir = await deps.resolveWorkerWorkingDir(requested, lead);
+ } catch {
+ return { ok: false, errorCode: 'INVALID_PARAMS', message: 'working_dir is unavailable or collaboration is disabled for that directory; no Worker was started' };
+ }
+ }
+
// 轮 42:解除「SSH remote lead 禁 Pi worker」闸 —— 该闸写于 Pi SSH remote 能力
// 落地之前(前提「PiAgent.startSession 对 remoteHostId 一律 NotSupportedError」
// 已不成立, 现 remote pi 会话全链路可用)。worker 创建走通用 remote 路径:
@@ -1010,12 +1029,12 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
const workerOpts = deps.buildCreateOptsWithStderr({
id: workerSessionId,
agentKind: params.agent,
- // Worker 与 Lead 共享同一种 workspace 语义。dialogue Lead 虽然已有 main 自动分配
- // 的运行目录,也不能把 Worker 落成 project,否则侧栏分组和项目能力都会误判。
- workspaceKind: lead.workspaceKind,
- workingDir: lead.workingDir ?? '',
+ // 未指定目录时保留 Lead 的 workspace 语义(包括 dialogue 托管目录)。
+ // 显式选择目录才使用 project,并在 bootstrap 前完成校验。
+ workspaceKind: params.workingDir === undefined ? lead.workspaceKind : 'project',
+ workingDir,
// remote lead 的 worker 继承 remoteHostId:在同一台远端主机上 spawn,
- // 与 lead 共享远端 workingDir;本地 lead 不带此字段 (本地 worker)。
+ // workingDir 在该远端校验;本地 lead 不带此字段(本地 worker)。
...(lead.remoteHostId ? { remoteHostId: lead.remoteHostId } : {}),
model: resolved.model,
providerId: resolved.providerId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 952ed90e9d..2c11784fb3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -542,6 +542,7 @@ import {
ensureRemoteHostReady,
getRemoteSshPool,
broadcastSilentInstallStatus,
+ probeRemoteWorkingDirectory,
} from '../remote-ssh/index.js';
import { recordSessionContextSnapshot } from '../sessionSpendBroadcaster.js';
@@ -1881,6 +1882,7 @@ interface OrcaCollabService {
fast?: boolean;
workerPermissionMode?: OrcaWorkerPermissionMode;
label: string;
+ workingDir?: string;
initialTask?: string;
}) => Promise<
| {
@@ -10655,6 +10657,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
getWorkerDefaults: getWorkerDefaultsFromNewMaker,
getWorkerPermissionMode: getWorkerPermissionModeFromCreationPrefs,
+ resolveWorkerWorkingDir: async (dir, lead) => {
+ let resolved: string;
+ if (lead.remoteHostId) {
+ resolved = await probeRemoteWorkingDirectory(lead.remoteHostId, dir);
+ } else {
+ resolved = await realpathWorkingDirectory(dir);
+ if (!(await statWorkingDirectory(resolved)).isDirectory()) throw new Error('Not a directory');
+ }
+ assertCollabProjectEnabled(
+ { ...lead, workingDir: resolved, workspaceKind: 'project' },
+ (pluginId, workingDir) => getPluginRegistry().isEnabled(pluginId, workingDir),
+ () => false,
+ );
+ return resolved;
+ },
getAvailableModels: (agent) => maker.getCapabilities(agent).availableModels,
getProviderRoutingContext,
readClaudeApiKey,
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index 198d48a32b..8f20bc71ec 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -302,7 +302,7 @@ function makeDeps(
function clearAllPrefs(): void {
// 把测试涉及的目录 × id 全部清一遍(幂等;清空后 store 自动删文件)。
- for (const dir of [WORKDIR, '/proj/beta', 'E:/Repo']) {
+ for (const dir of [WORKDIR, `${WORKDIR} `, '/proj/beta', 'E:/Repo']) {
for (const id of ['art', 'other', 'missing', 'sleeping', 'account']) {
setGhostDisabledForWorkdir(dir, id, false);
}
@@ -732,6 +732,13 @@ afterAll(() => {
});
describe('写路径 roundtrip(真实存储,tmp userData)', () => {
+ it('keeps adjacent whitespace-distinct project overrides independent', () => {
+ setGhostDisabledForWorkdir(WORKDIR, 'art', true);
+ expect(isGhostDisabledForWorkdir('art', `${WORKDIR} `)).toBe(false);
+ setGhostDisabledForWorkdir(`${WORKDIR} `, 'other', true);
+ expect(listDisabledGhostIdsForWorkdir(`${WORKDIR} `)).toEqual(['other']);
+ expect(listDisabledGhostIdsForWorkdir(WORKDIR)).toEqual(['art']);
+ });
it('set → 生效;清最后一条 → 键与文件一并删除(reset 语义)', () => {
expect(setGhostDisabledForWorkdir(WORKDIR, 'art', true)).toEqual(['art']);
expect(fs.existsSync(prefsFile())).toBe(true);
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts
index 1abdfb6e30..21cef5ddb3 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts
@@ -1,4 +1,8 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { execSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, symlinkSync, rmSync, realpathSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import type {
HostConfig,
@@ -130,6 +134,7 @@ vi.mock('../../maker-host/index.js', () => ({
import {
getRemoteSshPool,
+ probeRemoteWorkingDirectory,
registerRemoteSshIpc,
REMOTE_SSH_INVOKE,
} from '../index.js';
@@ -206,6 +211,103 @@ beforeEach(async () => {
});
describe('remote SSH mutation runtime semantics', () => {
+ it.each(['\n', '\r', '\r\n'])('rejects injected protocol lines before remote execution (%j)', async (separator) => {
+ await getRemoteSshPool().hydrate([host('worker-dir')]);
+ const remote = getRemoteSshPool().get('worker-dir')!;
+ const status = vi.spyOn(remote, 'getStatus').mockReturnValue('ready');
+ const exec = vi.spyOn(remote, 'exec');
+ try {
+ await expect(probeRemoteWorkingDirectory('worker-dir', `/missing${separator}dir /other`))
+ .rejects.toThrow('unsupported control characters');
+ expect(exec).not.toHaveBeenCalled();
+ } finally {
+ exec.mockRestore();
+ status.mockRestore();
+ }
+ });
+
+ // symlink-platform-skip: Windows cannot represent CR/LF in directory names used as link targets.
+ it.skipIf(process.platform === 'win32')('validates physical paths before emitting the line protocol', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'cindy-stat-framing-'));
+ await getRemoteSshPool().hydrate([host('worker-dir')]);
+ const remote = getRemoteSshPool().get('worker-dir')!;
+ const status = vi.spyOn(remote, 'getStatus').mockReturnValue('ready');
+ const exec = vi.spyOn(remote, 'exec').mockImplementation(async (command) => {
+ try {
+ return { exitCode: 0, signal: null, stdout: `banner\n${execSync(command, { encoding: 'utf8' })}`, stderr: '' };
+ } catch {
+ return { exitCode: 64, signal: null, stdout: '', stderr: 'unsupported physical path' };
+ }
+ });
+ try {
+ const normal = join(root, 'project ');
+ mkdirSync(normal);
+ await expect(probeRemoteWorkingDirectory('worker-dir', normal)).resolves.toBe(realpathSync(normal));
+ for (const [i, suffix] of ['\n', '\r', '\ndir other'].entries()) {
+ const target = join(root, `target${suffix}`);
+ const alias = join(root, `alias-${i}`);
+ mkdirSync(target);
+ symlinkSync(target, alias);
+ await expect(probeRemoteWorkingDirectory('worker-dir', alias)).rejects.toThrow('bash exit=64');
+ await expect(probeRemoteWorkingDirectory('worker-dir', join(alias, 'missing'))).rejects.toThrow('bash exit=64');
+ }
+ } finally {
+ exec.mockRestore();
+ status.mockRestore();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it.each(['dir /remote/project \n', 'Welcome\nnotice\ndir /remote/project \n', 'Welcome\r\ndir /remote/project \r\n'])('preserves trailing whitespace after shell startup output: %j', async (stdout) => {
+ await getRemoteSshPool().hydrate([host('worker-dir')]);
+ const remote = getRemoteSshPool().get('worker-dir')!;
+ const status = vi.spyOn(remote, 'getStatus').mockReturnValue('ready');
+ const exec = vi.spyOn(remote, 'exec').mockResolvedValue({
+ exitCode: 0, signal: null, stdout, stderr: '',
+ });
+ try {
+ await expect(probeRemoteWorkingDirectory('worker-dir', '/remote/project '))
+ .resolves.toBe('/remote/project ');
+ await expect(handler(REMOTE_SSH_INVOKE.STAT_REMOTE_PATH)({}, { id: 'worker-dir', path: '/remote/project ' }))
+ .resolves.toEqual({ kind: 'dir', resolvedPath: '/remote/project ' });
+ expect(exec).toHaveBeenCalledWith(expect.stringContaining("'/remote/project '"),
+ expect.objectContaining({ timeoutMs: 10_000 }));
+ } finally {
+ exec.mockRestore();
+ status.mockRestore();
+ }
+ });
+
+ it.each([true, false])('reconnects only the selected Worker host before probing (success=%s)', async (succeeds) => {
+ const pool = getRemoteSshPool();
+ await pool.hydrate([host('worker-dir'), host('unrelated')]);
+ const remote = pool.get('worker-dir')!;
+ let ready = false;
+ const status = vi.spyOn(remote, 'getStatus').mockImplementation(() => ready ? 'ready' : 'disconnected');
+ const connect = vi.spyOn(pool, 'connect').mockImplementation(async () => {
+ if (!succeeds) throw new Error('fixture connection failed');
+ ready = true;
+ });
+ const exec = vi.spyOn(remote, 'exec').mockResolvedValue({
+ exitCode: 0, signal: null, stdout: 'banner\ndir /remote/project \n', stderr: '',
+ });
+ try {
+ const result = probeRemoteWorkingDirectory('worker-dir', '/remote/project ');
+ if (succeeds) {
+ await expect(result).resolves.toBe('/remote/project ');
+ expect(connect.mock.invocationCallOrder[0]).toBeLessThan(exec.mock.invocationCallOrder[0]!);
+ } else {
+ await expect(result).rejects.toThrow('fixture connection failed');
+ expect(exec).not.toHaveBeenCalled();
+ }
+ expect(connect).toHaveBeenCalledExactlyOnceWith('worker-dir');
+ } finally {
+ exec.mockRestore();
+ connect.mockRestore();
+ status.mockRestore();
+ }
+ });
+
it('returns a cold-start diagnostic instead of making the host list look valid and empty', () => {
expect(initialListResult).toMatchObject({
hosts: [],
diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.ts
index 80d21b6cdd..bb4fd56c02 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -2039,6 +2039,14 @@ export function registerRemoteSshIpc(): void {
log.info('remote-ssh IPC registered', { home: os.homedir() });
}
+/** Validate an existing Worker directory using the host filesystem, not local fs. */
+export async function probeRemoteWorkingDirectory(hostId: string, inputPath: string): Promise<string> {
+ await ensureRemoteHostReady(hostId);
+ const result = await statRemotePath(requireConnectedHost(hostId), inputPath);
+ if (result.kind !== 'dir') throw new Error('Remote working directory is unavailable');
+ return result.resolvedPath;
+}
+
/**
* stat-remote-path — POSIX-bash-driven stat that also expands a leading `~`
* or `~/...` to `$HOME` safely (no `eval`, no command injection).
@@ -2059,6 +2067,7 @@ async function statRemotePath(
host: RemoteHost,
inputPath: string,
): Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }> {
+ if (/[\r\n\0]/.test(inputPath)) throw new Error('Remote path contains unsupported control characters');
// 归一化为绝对路径:
// - 存在的目录 → cd && pwd -P (展开 symlink 与相对路径,与 daemon cwd 契约一致)
// - 存在的文件 → parent cd && pwd -P + basename
@@ -2071,28 +2080,38 @@ case "$1" in
'~'|'~/'*) p="$HOME${'$'}{1:1}" ;;
*) p="$1" ;;
esac
+case "$p" in
+ *$'\\r'*|*$'\\n'*) exit 64 ;;
+esac
abs_for() {
local target="$1"
if [ -d "$target" ]; then
- (cd "$target" && pwd -P)
+ (cd -P -- "$target" && printf '%s' "$PWD")
else
local parent base
parent="$(dirname -- "$target")"
base="$(basename -- "$target")"
if [ -d "$parent" ]; then
- printf '%s/%s' "$(cd "$parent" && pwd -P)" "$base"
+ (cd -P -- "$parent" && printf '%s/%s' "$PWD" "$base")
else
printf '%s' "$target"
fi
fi
}
if [ -d "$p" ]; then
- printf 'dir %s\\n' "$(abs_for "$p")"
+ kind=dir
elif [ -e "$p" ]; then
- printf 'file %s\\n' "$(abs_for "$p")"
+ kind=file
else
- printf 'missing %s\\n' "$(abs_for "$p")"
+ kind=missing
fi
+# Preserve trailing newlines until validation, including symlink targets.
+resolved="$(abs_for "$p" && printf '.')" || exit 64
+resolved="${'$'}{resolved%.}"
+case "$resolved" in
+ *$'\\r'*|*$'\\n'*) exit 64 ;;
+esac
+printf '%s %s\\n' "$kind" "$resolved"
`;
const result = await host.exec(
`bash -c ${shellQuoteSh(script)} _ ${shellQuoteSh(inputPath)}`,
@@ -2101,7 +2120,9 @@ fi
if (result.exitCode !== 0) {
throw new Error(`bash exit=${result.exitCode}: ${result.stderr.trim().slice(0, 200) || '(no stderr)'}`);
}
- const line = result.stdout.trim().split(/\r?\n/).pop() ?? '';
+ // Shell startup can print banners before the final protocol line. Remove
+ // only its terminator: trailing spaces belong to the path, not the framing.
+ const line = result.stdout.replace(/\r?\n$/, '').split(/\r?\n/).pop() ?? '';
// Allow spaces in the resolved path — only split on the first space.
const spaceIdx = line.indexOf(' ');
if (spaceIdx < 0) {
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index 6729b52c93..8cac09b540 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -33,6 +33,7 @@ import {
globalSafeDirectoryLockPath,
safeDirectorySpellings,
} from './gitExec';
+import { gitPathOutput } from './gitPathOutput';
import { withCrossProcessLock } from '../device-link/crossProcessLock';
import { applyWorktreeIncludeFile, listChangedWorktreeIncludeFiles } from './includePatternsEngine';
import { hasKeepSentinel, isManagedWorktreePath } from './safety';
@@ -413,15 +414,15 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
cwd,
CWD_PROBE_GIT_OPTS,
);
- const lines = stdout.trim().split(/\r?\n/);
+ const lines = gitPathOutput(stdout).split(process.platform === 'win32' ? /\r?\n/ : /\n/);
if (lines.length === 4 && lines.every((line) => line.trim().length > 0)) {
const [root, branch, gitDir, commonDir] = lines;
return {
isGitRepo: true,
- isInsideWorktree: path.resolve(cwd, gitDir.trim()) !== path.resolve(cwd, commonDir.trim()),
+ isInsideWorktree: path.resolve(cwd, gitDir) !== path.resolve(cwd, commonDir),
gitInstalled: true,
supportsRecoveryKeyDiscard: true,
- repoRoot: path.resolve(root.trim()),
+ repoRoot: path.resolve(root),
...(branch !== 'HEAD' ? { currentBranch: branch.trim() } : {}),
};
}
@@ -452,7 +453,7 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
// 2. rev-parse --show-toplevel: 拿 repo 根
try {
const { stdout } = await gitExec(['rev-parse', '--show-toplevel'], cwd, CWD_PROBE_GIT_OPTS);
- const toplevel = stdout.trim();
+ const toplevel = gitPathOutput(stdout);
if (toplevel) {
out.isGitRepo = true;
out.repoRoot = path.resolve(toplevel);
@@ -495,8 +496,8 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
if (commonDirResult.status === 'rejected') throw commonDirResult.reason;
const gitDirRaw = gitDirResult.value.stdout;
const gitCommonDirRaw = commonDirResult.value.stdout;
- const gitDir = path.resolve(cwd, gitDirRaw.trim());
- const gitCommonDir = path.resolve(cwd, gitCommonDirRaw.trim());
+ const gitDir = path.resolve(cwd, gitPathOutput(gitDirRaw));
+ const gitCommonDir = path.resolve(cwd, gitPathOutput(gitCommonDirRaw));
if (gitDir && gitCommonDir && gitDir !== gitCommonDir) {
out.isInsideWorktree = true;
}
diff --git a/apps/desktop/src/main/worktree/gitPathOutput.ts b/apps/desktop/src/main/worktree/gitPathOutput.ts
new file mode 100644
index 0000000000..52a812091c
--- /dev/null
+++ b/apps/desktop/src/main/worktree/gitPathOutput.ts
@@ -0,0 +1,4 @@
+/** Remove Git's record terminator, never whitespace belonging to a path. */
+export function gitPathOutput(stdout: string): string {
+ return stdout.replace(process.platform === 'win32' ? /\r?\n$/ : /\n$/, '');
+}
diff --git a/apps/desktop/src/shared/__tests__/workingDir.test.ts b/apps/desktop/src/shared/__tests__/workingDir.test.ts
index bb9f9c64b9..2688c19e17 100644
--- a/apps/desktop/src/shared/__tests__/workingDir.test.ts
+++ b/apps/desktop/src/shared/__tests__/workingDir.test.ts
@@ -7,6 +7,16 @@ import {
} from '../workingDir';
describe('workingDir normalization', () => {
+ it('preserves significant whitespace through repeated storage normalization', () => {
+ for (const path of ['/repo ', '/repo /', '/repo\t']) {
+ const expected = path.endsWith('/') ? path.slice(0, -1) : path;
+ expect(normalizeWorkingDirForStorage(path)).toBe(expected);
+ expect(normalizeWorkingDirForStorage(normalizeWorkingDirForStorage(path))).toBe(expected);
+ expect(normalizeWorkingDirForProjectSettings(path)).toBe(expected);
+ }
+ expect(normalizeWorkingDirForStorage(' \t ')).toBeNull();
+ });
+
it('normalizes Windows-looking paths for storage', () => {
expect(normalizeWorkingDirForStorage('D:\\repo\\project\\')).toBe('D:/repo/project');
expect(normalizeWorkingDirForStorage('\\\\?\\D:\\repo\\project\\')).toBe('D:/repo/project');
diff --git a/apps/desktop/src/shared/workingDir.ts b/apps/desktop/src/shared/workingDir.ts
index 65b41bbcb1..a227a97020 100644
--- a/apps/desktop/src/shared/workingDir.ts
+++ b/apps/desktop/src/shared/workingDir.ts
@@ -20,12 +20,12 @@ import { getManagedWorktreeBasePath } from './managedWorktreePaths';
*/
export function normalizeWorkingDirForStorage(raw: string | null | undefined): string | null {
if (raw == null) return null;
- const trimmed = String(raw).trim();
- if (trimmed === '') return null;
+ const path = String(raw);
+ if (path.trim() === '') return null;
- const withoutLongPathPrefix = stripWindowsLongPathPrefix(trimmed);
+ const withoutLongPathPrefix = stripWindowsLongPathPrefix(path);
const outNeedsWindowsSeparatorRewrite =
- isWindowsPathLike(trimmed) || isWindowsPathLike(withoutLongPathPrefix);
+ isWindowsPathLike(path) || isWindowsPathLike(withoutLongPathPrefix);
let out = outNeedsWindowsSeparatorRewrite
? withoutLongPathPrefix.replace(/\\/g, '/')
: withoutLongPathPrefix;
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 856e0b2567..ab51619a48 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -208,6 +208,23 @@ Worker 不出现在普通 sidebar。renderer 用 `isOrcaWorkerSession(session) =
Worktree 现状:Orca 与普通 session 对齐,worktree 是可选项,不强制;toggle off 时 Lead/Worker 使用用户选的 workingDir,toggle on 时 Lead/Worker 共用同一个 worktree。
+`create_worker` / `create_workers` 的每个 Worker 可显式指定 `working_dir`(Worker
+所在主机上已存在的绝对目录)。省略时仍继承 Lead;显式指定时,在 reservation、session
+bootstrap 和首条任务派发之前校验并绑定,项目上下文与 agent 进程使用同一目录。
+本机目录解析真实路径并检查目录及协同开关;SSH 目录通过继承的 remoteHostId 在远端校验,
+探测前复用该主机的就绪/重连入口,不触碰其他主机;解析保留 shell 前置输出兼容与路径空格,
+SSH 行协议不接受含 CR/LF 的输入或物理路径(含 symlink 目标),拒绝后不绑定其他目录。
+不拿本机文件系统判断远端路径。无效目录或目标项目禁用协同时返回错误,不回退到 Lead
+目录,也不创建 Worker。路径解析与会话落库均保留目录名中的空格。
+运行期消费者同样保留目录身份:Git 初始化、仓库根探测与保存点清理只去掉 Git 输出的行结束符,
+文档工具、历史筛选和 iOS 工具项目权限检查不得 trim 路径;trim 仅用于判空。
+策略查询统一将 Cindy 托管 worktree 映射到 base repo,但运行目录与落库目录仍为实际 worktree;用户自建 worktree
+保留独立项目设置。该参数不创建目录或
+Git worktree,不改变供应商、模型与 Worker 创建权限偏好。
+显式 `working_dir` 的单个或批量 MCP 调用走现有会话审批:Full Access 直接执行,Auto
+审阅用户授权,Ask 使用现有确认;不得被可信 server 或缓存的 server 授权直接放行。
+省略时保持原有静默继承;审批缺少工具名或参数证据时不静默放行。无需新增 UI。
+
### 协同运行时行为契约
本节记录当前系统必须持续满足的运行时不变量。它们不是远期规划,而是 Lead / Worker 协同时已经依赖的行为契约。
diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
index 1d1fe28122..cb0a51d099 100644
--- a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
@@ -42,7 +42,7 @@ import {
resolvePptxGenConstructor,
validateDecodablePptxImage,
} from '../cindy-docs/make_pptx.js';
-import { DocsPathError, readInputFileWithinLimit } from '../cindy-docs/_paths.js';
+import { DocsPathError, readInputFileWithinLimit, resolveSessionRoot, prepareOutputPath } from '../cindy-docs/_paths.js';
import { RENDER_PDF_MAX_HTML_BYTES } from '../cindy-docs/render_pdf.js';
import { MAX_XLSX_ZIP_ENTRIES } from '../cindy-docs/read_sheet.js';
import type {
@@ -57,6 +57,19 @@ import type {
let workdir: string;
const created: string[] = [];
+it('preserves the authoritative root including trailing whitespace', async () => {
+ const root = `${workdir}/project `;
+ expect(resolveSessionRoot(sessionCtx({ workingDir: root }))).toBe(root);
+ // Windows aliases ordinary trailing-space directory names; lexical identity is tested above.
+ if (process.platform === 'win32') return;
+ await fs.mkdir(root);
+ await fs.mkdir(root.trim());
+ const output = await prepareOutputPath(resolveSessionRoot(sessionCtx({ workingDir: root })), 'result.txt', false);
+ await fs.writeFile(output, 'exact');
+ expect(await fs.readFile(path.join(root, 'result.txt'), 'utf8')).toBe('exact');
+ await expect(fs.stat(path.join(root.trim(), 'result.txt'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
beforeEach(async () => {
workdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-test-'));
created.push(workdir);
diff --git a/packages/lizi-mcps/src/__tests__/createWorkerTool.test.ts b/packages/lizi-mcps/src/__tests__/createWorkerTool.test.ts
index 11b964b0ae..3fb981e401 100644
--- a/packages/lizi-mcps/src/__tests__/createWorkerTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/createWorkerTool.test.ts
@@ -50,6 +50,24 @@ function setupWorkerSession() {
}
describe('create_worker tool', () => {
+ it('forwards the explicit working_dir to the host', async () => {
+ const { registry, createWorker } = setup();
+ const result = await registry.call('create_worker', {
+ role: 'developer', agent: 'codex', label: 'worker', working_dir: '/tmp/candidate with spaces ',
+ });
+ expect(result.isError).toBeUndefined();
+ expect(createWorker).toHaveBeenCalledWith(expect.objectContaining({ workingDir: '/tmp/candidate with spaces ' }));
+ });
+
+ it('rejects an empty explicit directory instead of silently inheriting', async () => {
+ const { registry, createWorker } = setup();
+ const result = await registry.call('create_worker', {
+ role: 'developer', agent: 'codex', label: 'worker', working_dir: ' ',
+ });
+ expect(result.isError).toBe(true);
+ expect(createWorker).not.toHaveBeenCalled();
+ });
+
it('describes the subagent distinction before creating a worker', () => {
const { registry } = setup();
diff --git a/packages/lizi-mcps/src/__tests__/createWorkersTool.test.ts b/packages/lizi-mcps/src/__tests__/createWorkersTool.test.ts
index 9144311af8..2b91590d5b 100644
--- a/packages/lizi-mcps/src/__tests__/createWorkersTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/createWorkersTool.test.ts
@@ -55,6 +55,18 @@ function hardLimitFailure(hardLimit: number) {
}
describe('create_workers tool', () => {
+ it('preserves each worker directory independently in a batch', async () => {
+ const createWorker = vi.fn<CreateWorkerDeps['createWorker']>()
+ .mockResolvedValueOnce(created(1, 5)).mockResolvedValueOnce(created(2, 5));
+ const registry = setup(createWorker);
+ await registry.call('create_workers', { workers: [
+ { ...worker(1), working_dir: '/tmp/first' },
+ { ...worker(2), working_dir: '/tmp/second with spaces ' },
+ ] });
+ expect(createWorker).toHaveBeenNthCalledWith(1, expect.objectContaining({ workingDir: '/tmp/first' }));
+ expect(createWorker).toHaveBeenNthCalledWith(2, expect.objectContaining({ workingDir: '/tmp/second with spaces ' }));
+ });
+
it('routes multi-worker requests to one deterministic batch tool', () => {
const createWorker = vi.fn<CreateWorkerDeps['createWorker']>();
const registry = setup(createWorker);
diff --git a/packages/lizi-mcps/src/cindy-docs/_paths.ts b/packages/lizi-mcps/src/cindy-docs/_paths.ts
index d7ff7fe724..76fe5fa81b 100644
--- a/packages/lizi-mcps/src/cindy-docs/_paths.ts
+++ b/packages/lizi-mcps/src/cindy-docs/_paths.ts
@@ -55,8 +55,8 @@ export function resolveSessionRoot(sessionCtx: DocsMcpSessionCtx): string {
'文档工具只能在本机会话里生成文件。请在本地会话中重试,或让用户把内容带回本机后再生成。',
);
}
- const root = typeof ctx.workingDir === 'string' ? ctx.workingDir.trim() : '';
- if (root.length === 0) {
+ const root = typeof ctx.workingDir === 'string' ? ctx.workingDir : '';
+ if (root.trim().length === 0) {
throw new DocsPathError(
'NO_SESSION_CONTEXT',
'当前调用无法确认所属会话的工作目录',
diff --git a/packages/lizi-mcps/src/orca/server.ts b/packages/lizi-mcps/src/orca/server.ts
index 5b8376a310..5e68f94b5d 100644
--- a/packages/lizi-mcps/src/orca/server.ts
+++ b/packages/lizi-mcps/src/orca/server.ts
@@ -98,6 +98,7 @@ export interface OrcaMcpDeps {
effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
fast?: boolean;
label: string;
+ workingDir?: string;
initialTask?: string;
}) => Promise<
ControlResult<
diff --git a/packages/lizi-mcps/src/xdt-helper/create_worker.ts b/packages/lizi-mcps/src/xdt-helper/create_worker.ts
index 43d88a385d..5d44695789 100644
--- a/packages/lizi-mcps/src/xdt-helper/create_worker.ts
+++ b/packages/lizi-mcps/src/xdt-helper/create_worker.ts
@@ -57,6 +57,7 @@ export interface CreateWorkerDeps {
effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
fast?: boolean;
label: string;
+ workingDir?: string;
initialTask?: string;
}) => Promise<CreateWorkerControlResult>;
}
@@ -102,6 +103,8 @@ export const createWorkerSpecSchema = z.object({
.min(1)
.optional()
.describe('可选, 创建后立即派给 worker 的第一条消息'),
+ working_dir: z.string().min(1).max(4096).refine((value) => value.trim().length > 0).optional()
+ .describe('可选,Worker 所在主机上已存在的绝对工作目录;省略则继承 Lead。创建前校验并绑定,失败不回退;不创建目录或 Git worktree。'),
}).strict();
export type CreateWorkerSpec = z.infer<typeof createWorkerSpecSchema>;
@@ -130,6 +133,7 @@ const DESCRIPTION = [
'- effort: 可选, reasoning/thinking 强度 (low / medium / high / xhigh / max / ultra)。Codex: 映射 OpenAI reasoning effort(max/ultra 仅部分模型如 GPT-5.6 Sol 支持); Claude Code: 映射 extended thinking token 预算(无 ultra,自动降级为 max)。显式传入时必须匹配所选 model 能力;当前 worker 模型都不把 minimal 作为可选思考档。',
'- fast: 可选 boolean, 是否给 worker 开启 Fast 模式 (更快输出)。用户明确说「fast / 快速 / 开/关 fast」时显式传。对 codex 与 pi worker 生效 (且需所选模型声明 supportsFastMode; 否则自动降级为关); claude-code worker 忽略此参数 (其 fast mode 在 agent 层为 no-op)。不传则继承默认 (New Maker 面板默认或 lead session 的 fastMode)。',
'- label: worker 短标识, 1-32 chars, 只能含字母、数字、-、_, 同 workflow 内唯一, 用于 switch_focus 定位',
+ '- working_dir: 可选,Worker 所在主机上已存在的绝对目录;创建前校验并绑定,省略继承 Lead,失败不回退。不创建目录或 Git worktree。',
"- initial_task: 可选, 创建后立即派给 worker 的第一条消息;dispatch_outcome.wakeKind=queued 表示首条任务已成功入队(此时回传 queued_message_id, 被消费前可用 get_worker_queue_status / update_queued_message / cancel_queued_message / merge_queued_messages 管理);dispatch_outcome.kind='session-dispatch' 且 dispatched=false,或 kind='host-send' 且 accepted=false,表示 worker 已创建但首条任务未送达 / 派发失败",
'',
'【硬边界】',
@@ -153,7 +157,7 @@ export function registerCreateWorkerTool(
category: 'control',
description: DESCRIPTION,
inputShape: createWorkerSpecSchema.shape,
- handler: async ({ role, agent, model, provider_id, effort, fast, label, initial_task }) => {
+ handler: async ({ role, agent, model, provider_id, effort, fast, label, initial_task, working_dir }) => {
const ctx = deps.getSessionContext?.() ?? deps;
if (!ctx.sessionId) {
return errorPayload('LEAD_NOT_SUPPORTED', '当前 session 类型不支持作为 Lead。');
@@ -173,6 +177,7 @@ export function registerCreateWorkerTool(
effort,
fast,
label,
+ ...(working_dir !== undefined ? { workingDir: working_dir } : {}),
initialTask: initial_task,
});
if (!result.ok) {
diff --git a/packages/lizi-mcps/src/xdt-helper/create_workers.ts b/packages/lizi-mcps/src/xdt-helper/create_workers.ts
index 211c2722cf..1025800191 100644
--- a/packages/lizi-mcps/src/xdt-helper/create_workers.ts
+++ b/packages/lizi-mcps/src/xdt-helper/create_workers.ts
@@ -152,6 +152,7 @@ export function registerCreateWorkersTool(
effort: worker.effort,
fast: worker.fast,
label: worker.label,
+ ...(worker.working_dir !== undefined ? { workingDir: worker.working_dir } : {}),
initialTask: worker.initial_task,
});
limit = result.limit ?? limit;