Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/design-doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ In V2, **Allow peer access between tasks** defaults off and explicitly enables d

**Allow agents to read tasks in other projects** (Settings > Agents, global, defaults off) adds read-only access across projects: discovery (`list_agent_sessions`), output (`get_agent_output`) and diffs (`get_task_diff`) of top-level worktree tasks in other projects, from top-level worktree tasks only. Children stay limited to their parent; page agents, shells and checkout-mode tasks stay excluded on both sides. `send_agent_prompt` and every other write or prompt path stay within the project and refuse other projects with a read-only error. Discovery needs only the setting. The first output or diff read of another project asks the user to allow or deny it, once per agent session (launch instance) and project, in a native dialog with Deny as the default. Reads fail at once while the dialog is pending or after a denial, and agents never wait on it. A denied project also drops out of that session's discovery. Turning the setting off revokes every approval and ignores answers to dialogs still open. Peer results (sessions, output and diffs) carry `projectId` and `projectName`, and sessions in other projects are marked `readOnly`. The renderer sends the setting with `crossProjectReadSetting`, and project names with each project policy, before restoring task authority.

**Allow agents to create tasks in other projects** (Settings > Agents, global, defaults off) is the one cross-project write. `create_task` with relation `independent` takes an optional `project`, an id or a name matched without case (an unknown or ambiguous name answers with the list of projects), from any session that may create independent tasks. Naming the creator's own project is an ordinary independent task. Any other project asks the user before each task, in a native dialog naming both projects, the task and its prompt, with Deny as the default; dialogs show one at a time. Unlike reads, the call waits for the answer, since the agent needs the result and the user is approving that exact task. The setting, pause, orchestration and session checks run again before the dialog opens and after the user answers, so switching any of them off meanwhile refuses the task. The created task is an independent task of the target project in every other respect: it starts from that project's main branch, uses the creator's agent, sandbox and permission propagation, counts against the creator's independent-task cap, and the user reviews it. Children (`relation: 'child'`) stay in the creator's project. The renderer sends the setting with `crossProjectTaskSetting`, and lists projects for resolution through the same request the phone uses.

### Exact V1 tool exposure and completion loop

Use these named sets in `selectTools()` and capability-based dispatch. Tool discovery is not the security boundary: HTTP handlers enforce the same scope and current consent/policy, including calls to hidden or legacy handler names.
Expand Down
7 changes: 7 additions & 0 deletions electron/ipc/mcp-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
} from './remote-transport.js';
import { DelegationService } from '../mcp/delegation.js';
import type { CrossProjectReadRequest } from '../mcp/cross-project-reads.js';
import type { CrossProjectTaskRequest, TaskProject } from '../mcp/cross-project-tasks.js';
import type { Coordinator } from '../mcp/coordinator.js';
import { removeCanvasConfig } from '../mcp/canvas-config.js';
import { getMCPRemoteServerUrl } from '../mcp/config.js';
Expand All @@ -39,6 +40,10 @@ export interface McpRuntimeOptions {
) => Promise<{ taskId: string; resumedSessionId: string | null }>;
/** Asks the user whether a session may read another project; true allows. */
confirmCrossProjectRead: (request: CrossProjectReadRequest) => Promise<boolean>;
/** The projects that take tasks, as the renderer lists them. */
listProjects: () => Promise<TaskProject[]>;
/** Asks the user whether an agent may create a task in another project; true allows. */
confirmCrossProjectTask: (request: CrossProjectTaskRequest) => Promise<boolean>;
}

export interface McpRuntime {
Expand Down Expand Up @@ -114,6 +119,8 @@ export function createMcpRuntime(opts: McpRuntimeOptions): McpRuntime {
createIndependent: opts.createIndependentTask,
importWorktree: opts.importWorktree,
confirmCrossProjectRead: opts.confirmCrossProjectRead,
listProjects: opts.listProjects,
confirmCrossProjectTask: opts.confirmCrossProjectTask,
});

async function prepareDelegationParent(task: TaskAuthorityInput): Promise<void> {
Expand Down
21 changes: 21 additions & 0 deletions electron/ipc/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,27 @@ export function registerAllHandlers(win: BrowserWindow): void {
});
return response === 0;
},
listProjects: async () =>
(
await callRenderer<Array<{ id: string; name: string }>>(IPC.Remote_GetProjectsRequest, {})
).map(({ id, name }) => ({ id, name })),
confirmCrossProjectTask: async (request) => {
if (win.isDestroyed()) throw new Error('Desktop app is not available');
const prompt =
request.prompt.length > 600 ? `${request.prompt.slice(0, 600)}…` : request.prompt;
const { response } = await dialog.showMessageBox(win, {
type: 'question',
title: 'Create a task in another project?',
message: `An agent in project "${request.projectName}" wants to create a task in project "${request.targetProjectName}".`,
// Names and prompts come from agents, so they stay out of the headline the user acts on.
detail: `Asking task: ${request.creatorTaskName.slice(0, 80)}\nNew task: ${request.name.slice(0, 80)}\n\nPrompt:\n${prompt}\n\nIf you allow it, the task starts in "${request.targetProjectName}" with the asking agent, its sandbox and its permission settings, and you review it like any other task.`,
buttons: ['Create task', 'Deny'],
// Deny is the default: Enter or Escape on an unexpected dialog must not start work.
defaultId: 1,
cancelId: 1,
});
return response === 0;
},
});
const { transport, delegation, pendingSpawns, canvasOwners, wideBindAgents, needsWideBind } = mcp;
const taskNames = new Map<string, string>();
Expand Down
45 changes: 45 additions & 0 deletions electron/mcp/cross-project-tasks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/** A project that takes tasks, as the renderer lists it. */
export interface TaskProject {
id: string;
name: string;
}

/** What the user is asked before an agent creates a task in another project. */
export interface CrossProjectTaskRequest {
creatorTaskName: string;
projectName: string;
targetProjectName: string;
name: string;
prompt: string;
}

const LISTED_PROJECTS = 30;

function describe(projects: readonly TaskProject[], withIds: boolean): string {
const shown = projects
.slice(0, LISTED_PROJECTS)
.map((p) => (withIds ? `"${p.name}" (id ${p.id})` : `"${p.name}"`));
const more = projects.length - shown.length;
return shown.join(', ') + (more > 0 ? ` and ${more} more` : '');
}

/**
* Finds the project an agent named, by exact id or by name ignoring case. Agents usually
* know a project by name ("phpstan"), so an unknown or ambiguous name returns an error
* message that lists the choices.
*/
export function resolveTaskProject(
projects: readonly TaskProject[],
ref: string,
): TaskProject | string {
const byId = projects.find((p) => p.id === ref);
if (byId) return byId;
const wanted = ref.trim().toLowerCase();
const byName = projects.filter((p) => p.name.trim().toLowerCase() === wanted);
if (byName.length === 1) return byName[0];
if (byName.length > 1)
return `Several projects are named "${ref}"; pass the id of one of them as project: ${describe(byName, true)}`;
return projects.length
? `No project is named "${ref}". Projects: ${describe(projects, false)}`
: `No project is named "${ref}"`;
}
160 changes: 160 additions & 0 deletions electron/mcp/delegation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
import { DEFAULT_INDEPENDENT_TASKS_PER_CREATOR } from '../shared/coordinator-limits.js';
import { setProjectWorktreeSettings } from '../ipc/project-worktree.js';
import type { CrossProjectReadRequest } from './cross-project-reads.js';
import type { CrossProjectTaskRequest, TaskProject } from './cross-project-tasks.js';

const mocks = vi.hoisted(() => ({
git: vi.fn(),
Expand Down Expand Up @@ -99,6 +100,10 @@ let importWorktree: Mock<
let confirmCrossProjectRead: Mock<(request: CrossProjectReadRequest) => Promise<boolean>>;
/** Answers the oldest open cross-project confirmation. */
let answers: Array<(allowed: boolean) => void>;
let listProjects: Mock<() => Promise<TaskProject[]>>;
let confirmCrossProjectTask: Mock<(request: CrossProjectTaskRequest) => Promise<boolean>>;
/** Answers the oldest open cross-project task confirmation. */
let taskAnswers: Array<(allowed: boolean) => void>;

function task(taskId: string, extra: Partial<TaskAuthorityInput> = {}): TaskAuthorityInput {
return {
Expand Down Expand Up @@ -231,6 +236,14 @@ beforeEach(() => {
createIndependent = vi.fn(async () => ({ taskId: 'sibling' }));
importWorktree = vi.fn(async () => ({ taskId: 'imported', resumedSessionId: null }));
answers = [];
taskAnswers = [];
listProjects = vi.fn(async () => [
{ id: 'project', name: 'Project' },
{ id: 'phpstan-id', name: 'phpstan' },
]);
confirmCrossProjectTask = vi.fn(
() => new Promise<boolean>((resolveAnswer) => taskAnswers.push(resolveAnswer)),
);
confirmCrossProjectRead = vi.fn(
() => new Promise<boolean>((resolveAnswer) => answers.push(resolveAnswer)),
);
Expand All @@ -244,6 +257,8 @@ beforeEach(() => {
createIndependent,
importWorktree,
confirmCrossProjectRead,
listProjects,
confirmCrossProjectTask,
});
});
afterEach(() => {
Expand Down Expand Up @@ -2225,3 +2240,148 @@ describe('cross-project reads', () => {
expect(confirmCrossProjectRead).not.toHaveBeenCalled();
});
});

describe('cross-project tasks', () => {
const setting = (enabled: boolean) =>
service.request({ action: 'crossProjectTaskSetting', enabled });
const create = (caller: SessionCaller, project: string, requestId = 'bug') =>
service.callTool(caller, 'create_task', {
requestId,
relation: 'independent',
name: 'Fix generics bug',
prompt: 'Reproduce with this snippet, then fix it',
project,
});
const asked = (count: number) =>
vi.waitFor(() => expect(confirmCrossProjectTask).toHaveBeenCalledTimes(count));
async function parent() {
await register('parent');
policy();
return session('parent');
}

it('refuses another project while the setting is off, without asking', async () => {
const caller = await parent();
await expect(create(caller, 'phpstan')).rejects.toThrow(
'Allow agents to create tasks in other projects',
);
expect(listProjects).not.toHaveBeenCalled();
expect(confirmCrossProjectTask).not.toHaveBeenCalled();
expect(createIndependent).not.toHaveBeenCalled();
});

it('asks the user, waits, and creates the task in the project named', async () => {
const caller = await parent();
await setting(true);
const created = create(caller, 'PHPStan');
await asked(1);
expect(confirmCrossProjectTask).toHaveBeenCalledWith({
creatorTaskName: 'parent',
projectName: 'Project',
targetProjectName: 'phpstan',
name: 'Fix generics bug',
prompt: 'Reproduce with this snippet, then fix it',
});
expect(createIndependent).not.toHaveBeenCalled();
taskAnswers.shift()?.(true);
await expect(created).resolves.toEqual({ taskId: 'sibling', relation: 'independent' });
expect(createIndependent).toHaveBeenCalledWith({
creatorTaskId: 'parent',
name: 'Fix generics bug',
prompt: 'Reproduce with this snippet, then fix it',
launchId: expect.any(String),
projectId: 'phpstan-id',
});
// A retry of the same request answers again without a second dialog or task.
await expect(create(caller, 'PHPStan')).resolves.toMatchObject({ taskId: 'sibling' });
expect(confirmCrossProjectTask).toHaveBeenCalledOnce();
expect(createIndependent).toHaveBeenCalledOnce();
// The same request ID for another project is a different assignment.
await expect(create(caller, 'Project')).rejects.toThrow('Request ID reused');
});

it('creates nothing when the user denies it', async () => {
const caller = await parent();
await setting(true);
const created = create(caller, 'phpstan-id');
await asked(1);
taskAnswers.shift()?.(false);
await expect(created).rejects.toThrow('declined creating this task in project "phpstan"');
expect(createIndependent).not.toHaveBeenCalled();
});

it('treats its own project as an ordinary independent task', async () => {
const caller = await parent();
await setting(true);
await expect(create(caller, 'project')).resolves.toMatchObject({ relation: 'independent' });
expect(confirmCrossProjectTask).not.toHaveBeenCalled();
expect(createIndependent).toHaveBeenCalledWith(
expect.not.objectContaining({ projectId: expect.anything() }),
);
});

it('lists the projects when the name is unknown or ambiguous', async () => {
const caller = await parent();
await setting(true);
await expect(create(caller, 'psalm', 'a')).rejects.toThrow(
'No project is named "psalm". Projects: "Project", "phpstan"',
);
listProjects.mockResolvedValue([
{ id: 'one', name: 'Lib' },
{ id: 'two', name: 'lib' },
]);
await expect(create(caller, 'LIB', 'b')).rejects.toThrow(
'pass the id of one of them as project: "Lib" (id one), "lib" (id two)',
);
expect(confirmCrossProjectTask).not.toHaveBeenCalled();
expect(createIndependent).not.toHaveBeenCalled();
});

it('refuses after approval when the setting or creation was switched off meanwhile', async () => {
const caller = await parent();
await setting(true);
const created = create(caller, 'phpstan');
await asked(1);
await setting(false);
taskAnswers.shift()?.(true);
await expect(created).rejects.toThrow('Allow agents to create tasks in other projects');

await setting(true);
const paused = create(caller, 'phpstan', 'paused');
await asked(2);
await service.request({ action: 'pause', taskId: 'parent', paused: true });
taskAnswers.shift()?.(true);
await expect(paused).rejects.toThrow('Task creation is paused');
expect(createIndependent).not.toHaveBeenCalled();
});

it('shows one dialog at a time', async () => {
const caller = await parent();
await setting(true);
const first = create(caller, 'phpstan', 'first');
const second = create(caller, 'phpstan', 'second');
await asked(1);
await new Promise((resolveTick) => setTimeout(resolveTick, 0));
expect(confirmCrossProjectTask).toHaveBeenCalledOnce();
taskAnswers.shift()?.(false);
await expect(first).rejects.toThrow('declined');
await asked(2);
taskAnswers.shift()?.(true);
await expect(second).resolves.toMatchObject({ relation: 'independent' });
});

it('keeps children in the creator project', async () => {
const caller = await parent();
await setting(true);
await expect(
service.callTool(caller, 'create_task', {
requestId: 'child',
relation: 'child',
name: 'Child',
prompt: 'Do it',
project: 'phpstan',
}),
).rejects.toThrow("use relation 'independent'");
expect(core.createTask).not.toHaveBeenCalled();
});
});
Loading