Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(runtime): accept redundant delegation job selectors

vastsa275748889e78
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index c2a4a48bb..373f3be4d 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1997,11 +1997,16 @@ remain available. TaskList preserves `delegations` and `resumable` and adds
`backgroundJobs: {supported, tasks}`. Delegation summaries also include job
references. Bash summaries contain no logs and bound command text to 1 KiB.
-TaskWait and TaskStop accept one explicit `job`. Combining it with
-`delegationIds`, `mode` or `minCompleted` is an error. Omitting it preserves
-the existing delegation defaults, including stop-all-delegates. A Bash job
-never joins those implicit target sets. A legacy backgroundTaskId can be
-addressed as `{kind: "bash", id: backgroundTaskId}`.
+TaskWait and TaskStop accept one explicit `job`. For a delegation job,
+`delegationIds` may be omitted, empty, or contain only that job's id (duplicates
+are harmless); conflicting or malformed selectors fail before dispatch with
+instructions to omit `job` for multi-subagent selection. `mode` and
+`minCompleted` are ignored for this single-target form; TaskWait still honors
+`timeoutSeconds`. For a Bash job, combining it with `delegationIds`, `mode` or
+`minCompleted` remains an error with corrective usage instructions. Omitting
+`job` preserves the existing delegation defaults, including stop-all-delegates.
+A Bash job never joins those implicit target sets. A legacy backgroundTaskId
+can be addressed as `{kind: "bash", id: backgroundTaskId}`.
For Bash, TaskWait returns a snapshot with state, nullable exitCode,
stopRequested, separate stdout/stderr tails and truncated. Each stream is
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 56e01f62e..12473a3dc 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20358,8 +20358,9 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)
explicit stop reaches terminal state, repeated reads and desktop output agree.
Plan-mode access is rejected.
- Runtime tests cover new input/parent abort during a pending Host wait, late
- Host rejection, old Host/remote capability behavior, mixed selector rejection,
- existing delegation controls and registration without a subagent catalog.
+ Host rejection, old Host/remote capability behavior, conflicting/malformed
+ delegation selectors and mixed Bash selector rejection, existing delegation
+ controls and registration without a subagent catalog.
- Host tests cover pre-settled observation, repeatable output, Unicode clipping,
ownership lookup, idempotent stop and stop acknowledgement before termination.
Existing Windows child/grandchild cleanup tests remain required; record native
@@ -20381,3 +20382,20 @@ Bounded tail pages include compactions appended after the last message. Middle p
#### E2E-ISSUE-2164
While a checkpoint estimate supplies context occupancy, use its recorded provider/model capacity, or the current exact session binding for legacy checkpoints. Keep historical request usage unchanged. Unknown capacity is marked approximate. Verify 20,619 / 1,000,000 = 2%, unknown routes, legacy records and usage after a newer request with `compaction-context-usage.test.mjs`.
+
+#### E2E-ISSUE-2173: Redundant delegation job selectors
+
+- Entry: build shared/agent-runtime/host-runtime and Host, then run
+ `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-task-job-selectors.mjs`.
+- Preconditions: isolated Host data/workspace and a deterministic localhost
+ provider; production parent and delegate loops, with no external model account.
+- Steps: start a delegate; wait with both its job reference and matching
+ delegationIds; re-read with empty delegationIds and single-job mode/minCompleted;
+ start another delegate, hold its provider response, stop it with both selectors,
+ and confirm its stopped state through TaskWait.
+- Expected: reports remain readable, redundant selectors do not cause errors,
+ single-job mode/minCompleted are ignored, and cancellation settles the target.
+ Unit tests also reject conflicting/malformed IDs and mixed Bash selectors.
+- Specs: `03-runtime/02-agent-runtime.md`, Session job controls.
+- Acceptance: wait, report re-read and running-delegate cancellation complete
+ through the real tool loop. Milestone: maintenance. Status: automated.
diff --git a/packages/agent-runtime/src/background-job-tools.test.ts b/packages/agent-runtime/src/background-job-tools.test.ts
index f23d530f3..989f18348 100644
--- a/packages/agent-runtime/src/background-job-tools.test.ts
+++ b/packages/agent-runtime/src/background-job-tools.test.ts
@@ -43,11 +43,47 @@ describe("session job controls", () => {
await stop.execute("stop", {});
expect(dispatch).not.toHaveBeenCalled();
await wait.execute("one", { job: { kind: "delegation", id: "delegate" }, timeoutSeconds: 12 });
- expect(delegates.wait.execute).toHaveBeenLastCalledWith("one", { job: undefined, delegationIds: ["delegate"], timeoutSeconds: 12 }, undefined, undefined);
+ expect(delegates.wait.execute).toHaveBeenLastCalledWith("one", { delegationIds: ["delegate"], timeoutSeconds: 12 }, undefined, undefined);
await stop.execute("one", { job: { kind: "delegation", id: "delegate" } });
expect(delegates.stop.execute).toHaveBeenLastCalledWith("one", { delegationIds: ["delegate"] }, undefined, undefined);
});
+ it.each([undefined, [], ["delegate"], ["delegate", "delegate"]].map(delegationIds => ({ delegationIds })))(
+ "accepts redundant delegation selectors (%j) and ignores single-job wait options",
+ async ({ delegationIds }) => {
+ const { wait, stop, dispatch, delegates } = fixture();
+ const params = {
+ job: { kind: "delegation", id: "delegate" }, delegationIds,
+ mode: "any", minCompleted: 2, timeoutSeconds: 180,
+ };
+ const signal = new AbortController().signal;
+ const update = vi.fn();
+ const waitResult = await wait.execute("wait", params, signal, update);
+ expect(waitResult.content).toEqual([{ type: "text", text: "delegate report" }]);
+ expect(delegates.wait.execute).toHaveBeenCalledWith("wait", {
+ delegationIds: ["delegate"], timeoutSeconds: 180,
+ }, signal, update);
+ await stop.execute("stop", params, signal, update);
+ expect(delegates.stop.execute).toHaveBeenCalledWith("stop", {
+ delegationIds: ["delegate"],
+ }, signal, update);
+ expect(dispatch).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([["other"], ["delegate", "other"], "delegate", null].map(delegationIds => ({ delegationIds })))(
+ "rejects conflicting or malformed delegation selectors (%j) before dispatch",
+ async ({ delegationIds }) => {
+ const { wait, stop, dispatch, delegates } = fixture();
+ const params = { job: { kind: "delegation", id: "delegate" }, delegationIds };
+ await expect(wait.execute("wait", params)).rejects.toThrow("omit delegationIds or pass only job.id");
+ await expect(stop.execute("stop", params)).rejects.toThrow("omit delegationIds or pass only job.id");
+ expect(delegates.wait.execute).not.toHaveBeenCalled();
+ expect(delegates.stop.execute).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ },
+ );
+
it.each(["delegationIds", "mode", "minCompleted"])("rejects mixed selectors before dispatch (%s)", async key => {
const { wait, stop, dispatch } = fixture();
const args = { job: { kind: "bash", id: "process" }, [key]: [] };
diff --git a/packages/agent-runtime/src/background-job-tools.ts b/packages/agent-runtime/src/background-job-tools.ts
index 5b26b5aa0..c8ff83eef 100644
--- a/packages/agent-runtime/src/background-job-tools.ts
+++ b/packages/agent-runtime/src/background-job-tools.ts
@@ -13,7 +13,7 @@ import type { RuntimeHost } from "./host-client.js";
const jobSchema = Type.Object({
kind: Type.Union([Type.Literal("bash"), Type.Literal("delegation")]),
id: Type.String({ minLength: 1 }),
-}, { additionalProperties: false, description: "An explicit job returned by Bash, Task or TaskList." });
+}, { additionalProperties: false, description: "An explicit job returned by Bash, Task or TaskList. For delegation jobs, omit delegationIds or pass an empty array or only this job's id; mode and minCompleted are ignored. For Bash jobs, omit delegationIds, mode and minCompleted." });
function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -26,8 +26,13 @@ function target(params: unknown): JobReference | undefined {
typeof job.id !== "string" || !job.id.trim() || Object.keys(job).some(key => key !== "id" && key !== "kind")) {
throw new Error("job must contain a kind (bash or delegation) and a nonempty id");
}
- if (["delegationIds", "mode", "minCompleted"].some(key => params[key] !== undefined)) {
- throw new Error("job cannot be combined with delegationIds, mode or minCompleted");
+ if (job.kind === "delegation") {
+ if (params.delegationIds !== undefined && (!Array.isArray(params.delegationIds) ||
+ params.delegationIds.some(id => id !== job.id))) {
+ throw new Error("A delegation job targets one subagent: omit delegationIds or pass only job.id. To select multiple subagents, omit job and use delegationIds.");
+ }
+ } else if (["delegationIds", "mode", "minCompleted"].some(key => params[key] !== undefined)) {
+ throw new Error("A Bash job cannot be combined with delegationIds, mode or minCompleted. Pass only job and optional timeoutSeconds; for subagents, omit job and use delegationIds.");
}
return { kind: job.kind, id: job.id };
}
@@ -96,7 +101,7 @@ export function buildJobTools(
const job = target(params);
if (!job) return delegates.wait.execute(id, params, signal, update);
if (job.kind === "delegation") {
- return delegates.wait.execute(id, { ...params, job: undefined, delegationIds: [job.id] }, signal, update);
+ return delegates.wait.execute(id, { delegationIds: [job.id], timeoutSeconds: params.timeoutSeconds }, signal, update);
}
const seconds = params.timeoutSeconds ?? options.defaultTimeoutSeconds;
if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds < 1 || seconds > options.maxTimeoutSeconds) {
diff --git a/scripts/e2e-task-job-selectors.mjs b/scripts/e2e-task-job-selectors.mjs
new file mode 100644
index 000000000..a5396aa38
--- /dev/null
+++ b/scripts/e2e-task-job-selectors.mjs
@@ -0,0 +1,146 @@
+// Issue #2173: real provider transport -> Task -> redundant TaskWait/TaskStop selectors.
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp } from "node:fs/promises";
+import { createServer } from "node:http";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { createSession, configureSession, beginTurn, endTurn } from "./e2e/session.mjs";
+
+const artifacts = fileURLToPath(new URL("../.cache/task-job-selectors/", import.meta.url));
+await mkdir(artifacts, { recursive: true });
+const scratch = await mkdtemp(join(artifacts, "run-"));
+const workspace = join(scratch, "workspace");
+await mkdir(workspace);
+const host = new Host(resolveHostBinary(), join(scratch, "data"), { quiet: true });
+const delegateStarted = Promise.withResolvers();
+let runtime, turnId, fixtureFailure, job;
+let round = 0;
+const events = [];
+const toolResult = (body, id) => {
+ const message = body.messages.find(message => message.role === "tool" && message.tool_call_id === id);
+ assert(message, `missing tool result ${id}`);
+ return message.content;
+};
+const jobReference = (body, id) => {
+ const match = toolResult(body, id).match(/Job reference: (\{.*?\})/);
+ assert(match, `missing job reference in ${id}`);
+ return JSON.parse(match[1]);
+};
+const server = createServer(async (req, res) => {
+ try {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ const body = JSON.parse(raw);
+ const isDelegate = body.messages.some(message => message.role === "system" &&
+ typeof message.content === "string" && message.content.includes("selector-delegate-fixture"));
+ let name, args;
+ if (isDelegate) {
+ if (JSON.stringify(body.messages).includes("selector-stop")) {
+ delegateStarted.resolve();
+ // Keep the real delegate request pending until TaskStop cancels it.
+ await new Promise(resolve => res.once("close", resolve));
+ return;
+ }
+ } else switch (round++) {
+ case 0:
+ name = "Task"; args = { agent: "selector-fixture", task: "Return a selector report." };
+ break;
+ case 1:
+ job = jobReference(body, "call-1");
+ assert.equal(job.kind, "delegation");
+ name = "TaskWait"; args = {
+ job, delegationIds: [job.id], mode: "all", minCompleted: 1, timeoutSeconds: 180,
+ };
+ break;
+ case 2:
+ assert(toolResult(body, "call-2").includes("Selector delegate report."));
+ name = "TaskWait"; args = {
+ job, delegationIds: [], mode: "any", minCompleted: 2, timeoutSeconds: 600,
+ };
+ break;
+ case 3:
+ assert(toolResult(body, "call-3").includes("Selector delegate report."));
+ name = "Task"; args = { agent: "selector-fixture", task: "selector-stop: wait for cancellation." };
+ break;
+ case 4:
+ job = jobReference(body, "call-4");
+ await delegateStarted.promise;
+ name = "TaskStop"; args = { job, delegationIds: [job.id] };
+ break;
+ case 5:
+ assert.match(toolResult(body, "call-5"), /stopped 1 subagent/i);
+ name = "TaskWait"; args = {
+ job, delegationIds: [], mode: "all", minCompleted: 1, timeoutSeconds: 180,
+ };
+ break;
+ case 6:
+ assert(toolResult(body, "call-6").includes("stopped"));
+ break;
+ default: throw new Error("Unexpected provider round");
+ }
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({
+ id: `fixture-${round}`, object: "chat.completion.chunk", created: 1,
+ model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }],
+ })}\n\n`);
+ if (name) {
+ delta({ role: "assistant", tool_calls: [{ index: 0, id: `call-${round}`, type: "function", function: { name, arguments: JSON.stringify(args) } }] });
+ delta({}, "tool_calls");
+ } else {
+ delta({ role: "assistant", content: isDelegate ? "Selector delegate report." : "Verified delegation selectors." });
+ delta({}, "stop");
+ }
+ res.end("data: [DONE]\n\n");
+ } catch (error) {
+ fixtureFailure = error;
+ res.writeHead(400);
+ res.end(String(error));
+ }
+});
+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+const deadline = setTimeout(() => {
+ fixtureFailure ??= new Error("Delegation selector fixture exceeded 30 seconds");
+ void runtime?.abort();
+ server.closeAllConnections();
+}, 30_000);
+try {
+ await host.start();
+ const owner = await createSession(host, workspace, "Delegation selector owner");
+ await configureSession(host, owner, "agent", "auto");
+ const { effective: commandShell } = await host.call("commandShells.list");
+ turnId = await beginTurn(host, owner.id);
+ runtime = new DesktopAgentRuntime({
+ host, sessionId: owner.id, turnId, mode: "agent", projectPath: workspace,
+ provider: {
+ id: "fixture", name: "Local fixture", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,
+ modelId: "fixture", apiKey: "", authKind: "none", apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ },
+ commandShell, thinkingLevel: "off",
+ subagents: [{
+ name: "selector-fixture", description: "Exercise explicit delegation job controls.",
+ prompt: "selector-delegate-fixture", tools: ["Read"], source: "builtin",
+ }],
+ onEvent: envelope => events.push(envelope.event),
+ });
+ await runtime.prompt("Start, wait for and stop the selector fixtures.", "selector-user", turnId);
+ if (fixtureFailure) throw fixtureFailure;
+ assert.equal(round, 7);
+ assert.equal(events.some(event => event.type === "error"), false);
+ await endTurn(host, turnId);
+ turnId = undefined;
+ console.log(JSON.stringify({ ok: true, rounds: round, checks: [
+ "real Task and delegate provider loop", "matching delegation selectors",
+ "empty delegation selectors", "single-job wait options ignored",
+ "report re-read", "running delegate stopped", "stopped status re-read",
+ ] }, null, 2));
+} finally {
+ clearTimeout(deadline);
+ await runtime?.dispose();
+ if (turnId) await endTurn(host, turnId, "aborted");
+ await host.stop();
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+}