Skip to content
Merged
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
3 changes: 3 additions & 0 deletions packages/app/src/electro-bridge/ipc/agent-host-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const AGENT_HOST_CHANNELS = {
LIST_TASKS: "agent-host:list-tasks",
CONTROL_TASK: "agent-host:control-task",
REDIRECT_TASK: "agent-host:redirect-task",
RECORD_OUTPUT: "agent-host:record-output",
CANCEL: "agent-host:cancel",
RESPOND: "agent-host:respond",
REQUEST: "agent-host:request",
Expand All @@ -35,6 +36,8 @@ export function createAgentHostAPI(
invoke(AGENT_HOST_CHANNELS.CONTROL_TASK, taskId, action),
redirectTask: (taskId, instruction) =>
invoke(AGENT_HOST_CHANNELS.REDIRECT_TASK, taskId, instruction),
recordOutput: (jobId, messageId) =>
invoke(AGENT_HOST_CHANNELS.RECORD_OUTPUT, jobId, messageId),
cancel: (jobId) => invoke(AGENT_HOST_CHANNELS.CANCEL, jobId),
respond: (response) => invoke(AGENT_HOST_CHANNELS.RESPOND, response),
onRequest: (callback) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ describe("Agent Host IPC", () => {
resumeTask: vi.fn(async () => true),
cancelTask: vi.fn(async () => true),
redirectTask: vi.fn(async () => ({ id: "job-2" })),
recordOutput: vi.fn(async () => true),
} as unknown as AgentHost;
const { handlers, ipc } = mainIPC();
setupAgentHostIPC(
Expand Down Expand Up @@ -166,11 +167,19 @@ describe("Agent Host IPC", () => {
"Show the diff first" as never,
),
).toEqual({ success: true, job: { id: "job-2" } });
expect(
await handlers.get(AGENT_HOST_CHANNELS.RECORD_OUTPUT)?.(
event(sender),
"job-2" as never,
"message-2" as never,
),
).toEqual({ success: true, recorded: true });
expect(host.listTasks).toHaveBeenCalledWith("agent:fizz");
expect(host.pauseTask).toHaveBeenCalledWith("task-1");
expect(host.redirectTask).toHaveBeenCalledWith(
"task-1",
"Show the diff first",
);
expect(host.recordOutput).toHaveBeenCalledWith("job-2", "message-2");
});
});
30 changes: 30 additions & 0 deletions packages/app/src/electro-bridge/ipc/agent-host-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export function setupAgentHostIPC(
AGENT_HOST_CHANNELS.LIST_TASKS,
AGENT_HOST_CHANNELS.CONTROL_TASK,
AGENT_HOST_CHANNELS.REDIRECT_TASK,
AGENT_HOST_CHANNELS.RECORD_OUTPUT,
AGENT_HOST_CHANNELS.CANCEL,
AGENT_HOST_CHANNELS.RESPOND,
]) {
Expand Down Expand Up @@ -183,6 +184,35 @@ export function setupAgentHostIPC(
},
);

mainIPC.handle(
AGENT_HOST_CHANNELS.RECORD_OUTPUT,
async (event, jobId: unknown, messageId: unknown) => {
if (!allowed(event, options)) {
return {
success: false,
error: "Agent Host IPC sender is not allowed.",
};
}
if (!options.host) {
return { success: false, error: "Agent Host is unavailable." };
}
if (typeof jobId !== "string" || !jobId) {
return { success: false, error: "A job id is required." };
}
if (typeof messageId !== "string" || !messageId) {
return { success: false, error: "A message id is required." };
}
try {
return {
success: true,
recorded: await options.host.recordOutput(jobId, messageId),
};
} catch (error) {
return { success: false, error: errorMessage(error) };
}
},
);

mainIPC.handle(AGENT_HOST_CHANNELS.CANCEL, async (event, jobId: unknown) => {
if (!allowed(event, options)) {
return { success: false, error: "Agent Host IPC sender is not allowed." };
Expand Down
11 changes: 11 additions & 0 deletions packages/app/src/electro-bridge/ipc/local-ai-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,17 @@ describe("local AI IPC", () => {
...baseRequest,
agent: { id: "../fizz", memberId: "agent:../fizz" },
},
{
...baseRequest,
agentHost: {
jobId: "job-1",
taskId: "task-1",
channelKind: "channel",
collaborationTargets: [
{ agentId: "reviewer", memberId: "agent:someone-else" },
],
},
},
{ ...baseRequest, options: { temperature: Number.NaN } },
{ ...baseRequest, options: { maxOutputTokens: 0 } },
{
Expand Down
28 changes: 28 additions & 0 deletions packages/app/src/electro-bridge/ipc/local-ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,34 @@ function validateRequest(request: unknown): request is LocalAIChatRequest {
}
}

if (request.agentHost !== undefined) {
if (!isRecord(request.agentHost)) return false;
if (
!isValidIdentifier(request.agentHost.jobId) ||
!isValidIdentifier(request.agentHost.taskId) ||
(request.agentHost.channelKind !== "channel" &&
request.agentHost.channelKind !== "dm") ||
!isOptionalString(request.agentHost.roomContext, MAX_MESSAGE_CHARS)
) {
return false;
}
const targets = request.agentHost.collaborationTargets;
if (
targets !== undefined &&
(!Array.isArray(targets) ||
targets.length > 16 ||
!targets.every(
(target) =>
isRecord(target) &&
isValidIdentifier(target.agentId) &&
isValidIdentifier(target.memberId) &&
target.memberId === `agent:${target.agentId}`,
))
) {
return false;
}
}

if (request.options !== undefined) {
if (!isRecord(request.options)) return false;
if (!isOptionalString(request.options.cwd, MAX_CWD_CHARS)) return false;
Expand Down
137 changes: 137 additions & 0 deletions packages/app/src/electron/agent-host/host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,4 +353,141 @@ describe("AgentHost", () => {
host.redirectTask(job.taskId, "Change direction", "agent:b"),
).rejects.toThrow("not found for this agent");
});

it("delegates bounded child tasks, waits for Dexie result receipts, and replays idempotently", async () => {
const gates = new Map<string, ReturnType<typeof deferred<void>>>();
const execute = vi.fn((job: AgentHostJob) => {
const gate = deferred<void>();
gates.set(job.id, gate);
return gate.promise;
});
let nextId = 0;
const host = new AgentHost({
repository: new InMemoryAgentHostJobRepository(),
executor: { execute },
maxConcurrency: 3,
createId: () => `structured-${++nextId}`,
});
const [source] = await host.enqueue(dispatch("c1", ["agent:a"]));
await vi.waitFor(async () =>
expect((await host.listJobs())[0].status).toBe("running"),
);

const request = {
sourceJobId: source.id,
sourceTaskId: source.taskId,
callerMemberId: "agent:a",
idempotencyKey: "delegate-1",
inputHash: "same-input",
ttlSeconds: 60,
delegates: ["b", "c"].map((id) => ({
target: { agentId: id, memberId: `agent:${id}` },
brief: {
objective: `Research ${id}`,
acceptanceCriteria: ["Post evidence"],
contextMessageIds: [source.triggerMessageId],
outputContract: { format: "text" as const, description: "Findings" },
},
})),
};
const created = await host.delegateTask(request);
const replay = await host.delegateTask(request);
expect(replay.operationId).toBe(created.operationId);
expect(replay.jobs.map((job) => job.id)).toEqual(
created.jobs.map((job) => job.id),
);
await expect(
host.delegateTask({ ...request, inputHash: "changed-input" }),
).rejects.toThrow("different input");
await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(3));

const outcomePromise = host.waitForDelegation(created.operationId, {
strategy: "all",
cancelRemainingOnSatisfied: true,
timeoutMs: 5_000,
});
for (const child of created.jobs) {
expect(
await host.recordOutput(child.id, `message:${child.agentId}`),
).toBe(true);
gates.get(child.id)?.resolve();
}
const outcome = await outcomePromise;

expect(outcome.joinStatus).toBe("satisfied");
expect(outcome.jobs).toEqual([
expect.objectContaining({
parentTaskId: source.taskId,
status: "completed",
outputMessageIds: ["message:b"],
}),
expect.objectContaining({
parentTaskId: source.taskId,
status: "completed",
outputMessageIds: ["message:c"],
}),
]);
expect((await host.listTasks("agent:a"))[0].id).toBe(source.taskId);
gates.get(source.id)?.resolve();
});

it("hands off the stable task identity and removes control from the former owner", async () => {
const gates = new Map<string, ReturnType<typeof deferred<void>>>();
const execute = vi.fn((job: AgentHostJob) => {
const gate = deferred<void>();
gates.set(job.id, gate);
return gate.promise;
});
let nextId = 0;
const host = new AgentHost({
repository: new InMemoryAgentHostJobRepository(),
executor: { execute },
maxConcurrency: 2,
createId: () => `handoff-${++nextId}`,
});
const [source] = await host.enqueue(dispatch("c1", ["agent:a"]));
await vi.waitFor(() => expect(execute).toHaveBeenCalledOnce());
const request = {
sourceJobId: source.id,
sourceTaskId: source.taskId,
callerMemberId: "agent:a",
idempotencyKey: "handoff-1",
inputHash: "same-input",
target: { agentId: "b", memberId: "agent:b" },
brief: {
objective: "Own the rest of the task",
acceptanceCriteria: ["Finish it"],
contextMessageIds: [],
outputContract: { format: "text" as const, description: "Result" },
},
};
const committed = await host.handoffTask(request);
await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(2));

expect(committed.job).toMatchObject({
taskId: source.taskId,
parentJobId: source.id,
agentMemberId: "agent:b",
collaboration: { kind: "handoff", fromMemberId: "agent:a" },
});
expect(await host.listTasks("agent:a")).toEqual([]);
expect(await host.listTasks("agent:b")).toEqual([
expect.objectContaining({ id: source.taskId, agentMemberId: "agent:b" }),
]);
expect(await host.pauseTask(source.taskId, "agent:a")).toBe(false);
expect((await host.handoffTask(request)).job.id).toBe(committed.job.id);
await expect(
host.handoffTask({
...request,
sourceJobId: committed.job.id,
callerMemberId: "agent:b",
idempotencyKey: "handoff-back",
inputHash: "handoff-back",
target: { agentId: "a", memberId: "agent:a" },
}),
).rejects.toThrow("repeat an agent");

gates.get(committed.job.id)?.resolve();
gates.get(source.id)?.resolve();
});
});
Loading
Loading