Skip to content

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

fix(runtime): bound the completion-notice silence to its own reply

vastsadf4a2ec80620
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 6d542cd9c..90189d6fa 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -2880,6 +2880,16 @@ describe("DesktopAgentRuntime thinking configuration", () => {
});
describe("DesktopAgentRuntime session collaboration provenance", () => {
+ const completionOrigin: SessionMessageOrigin = {
+ messageId: "completion-1", sourceSessionId: "sender", sourceTitle: "Worker",
+ targetSessionId: "session-1", kind: "completion", replyToMessageId: "task-1",
+ };
+ const eventsOf = (onEvent: ReturnType<typeof vi.fn>) =>
+ onEvent.mock.calls.map(([envelope]) => (envelope as AgentEventEnvelope).event);
+ const emptyModelResponse = expect.objectContaining({
+ type: "error", error: expect.objectContaining({ code: "EMPTY_MODEL_RESPONSE" }),
+ });
+
it.each([
{ content: [] },
{ content: [{ type: "text", text: " \n " }] },
@@ -2892,6 +2902,8 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {
const handle = (runtime as any).handleAgentEvent.bind(runtime);
const silent = assistantMessage({ content });
const respond = async () => {
+ // pi appends the reply to its transcript before notifying listeners.
+ agent.state.messages = [...agent.state.messages, silent];
await handle({ type: "agent_start" });
await handle({ type: "message_start", message: silent });
await handle({ type: "message_end", message: silent });
@@ -2902,23 +2914,23 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {
agent.continue = vi.fn(respond);
agent.waitForIdle = vi.fn(async () => undefined);
try {
- await runtime.prompt({ text: "Task completed", sessionMessage: {
- messageId: "completion-1", sourceSessionId: "sender", sourceTitle: "Worker",
- targetSessionId: "session-1", kind: "completion", replyToMessageId: "task-1",
- } }, "notice-user", "notice-turn");
+ await runtime.prompt({ text: "Task completed", sessionMessage: completionOrigin }, "notice-user", "notice-turn");
expect(agent.continue).not.toHaveBeenCalled();
- const notices = onEvent.mock.calls.map(([envelope]) => (envelope as AgentEventEnvelope).event);
+ const notices = eventsOf(onEvent);
expect(notices.filter((event) => event.type === "agent_end")).toHaveLength(1);
expect(notices.some((event) => event.type === "error")).toBe(false);
expect(notices).toContainEqual(expect.objectContaining({
type: "message_end", message: expect.objectContaining({ status: "complete" }),
}));
+ // Accepted silence is not resent: neither the runtime entries nor pi's
+ // transcript carry an empty assistant into the next request.
+ expect((runtime as any).fullEntries).toHaveLength(0);
+ expect(agent.state.messages.some((message: { role: string }) => message.role === "assistant")).toBe(false);
+ expect(buildSessionContext((runtime as any).fullEntries).messages).toEqual([]);
onEvent.mockClear();
await runtime.prompt("Please answer", "human-user", "human-turn");
expect(agent.continue).toHaveBeenCalledOnce();
- expect(onEvent.mock.calls.map(([envelope]) => (envelope as AgentEventEnvelope).event)).toContainEqual(
- expect.objectContaining({ type: "error", error: expect.objectContaining({ code: "EMPTY_MODEL_RESPONSE" }) }),
- );
+ expect(eventsOf(onEvent)).toContainEqual(emptyModelResponse);
} finally {
await runtime.dispose();
}
@@ -2940,34 +2952,156 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {
};
agent.prompt = vi.fn(async () => {
if (kind === "steered") {
+ // Steering that pi injects before the first reply: the reply answers
+ // the user, so the notice exception no longer applies to it.
agent.state.isStreaming = true;
runtime.steer({ text: "Please answer now" }, "notice-turn", {
id: "steering", role: "user", content: "Please answer now",
status: "complete", createdAt: new Date().toISOString(),
});
agent.state.isStreaming = false;
+ const [queued] = [...(runtime as any).pendingSteering.keys()];
+ await handle({ type: "message_start", message: queued });
+ await handle({ type: "message_end", message: queued });
}
await respond();
});
agent.continue = vi.fn(respond);
agent.waitForIdle = vi.fn(async () => undefined);
const origin: SessionMessageOrigin = {
- messageId: "completion-1", sourceSessionId: "sender", sourceTitle: "Worker",
+ ...completionOrigin,
targetSessionId: kind === "wrong-session" ? "other-session" : "session-1",
kind: kind === "task" || kind === "message" ? kind : "completion",
- ...(kind !== "unlinked" ? { replyToMessageId: "task-1" } : {}),
};
+ if (kind === "unlinked") delete origin.replyToMessageId;
try {
await runtime.prompt(kind === "text-only" ? formatSessionMessage("Task completed", origin)
: { text: "Task completed", sessionMessage: origin }, "user", "notice-turn");
expect(agent.continue).toHaveBeenCalledOnce();
- expect(onEvent.mock.calls.map(([envelope]) => (envelope as AgentEventEnvelope).event)).toContainEqual(
- expect.objectContaining({ type: "error", error: expect.objectContaining({ code: "EMPTY_MODEL_RESPONSE" }) }),
- );
+ expect(eventsOf(onEvent)).toContainEqual(emptyModelResponse);
} finally { await runtime.dispose(); }
},
);
+ it("spends the notice exception on a tool batch so the post-tool reply keeps recovery", async () => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const agent = (runtime as any).agent;
+ const handle = (runtime as any).handleAgentEvent.bind(runtime);
+ const toolBatch = assistantMessage({
+ content: [{ type: "toolCall", id: "call-1", name: "Read", arguments: {} }],
+ stopReason: "toolUse",
+ });
+ const silent = assistantMessage({ content: [] });
+ agent.prompt = vi.fn(async () => {
+ await handle({ type: "agent_start" });
+ await handle({ type: "message_start", message: toolBatch });
+ await handle({ type: "message_end", message: toolBatch });
+ await handle({ type: "message_start", message: silent });
+ await handle({ type: "message_end", message: silent });
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.continue = vi.fn(async () => {
+ await handle({ type: "agent_start" });
+ await handle({ type: "message_start", message: silent });
+ await handle({ type: "message_end", message: silent });
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.waitForIdle = vi.fn(async () => undefined);
+ try {
+ await runtime.prompt({ text: "Task completed", sessionMessage: completionOrigin }, "notice-user", "notice-turn");
+ // The model did work and then said nothing about it: D193 applies.
+ expect(agent.continue).toHaveBeenCalledOnce();
+ expect(eventsOf(onEvent)).toContainEqual(emptyModelResponse);
+ } finally { await runtime.dispose(); }
+ });
+
+ it("keeps the notice exception for the retried attempt after a transient stream failure", async () => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const agent = (runtime as any).agent;
+ const handle = (runtime as any).handleAgentEvent.bind(runtime);
+ const failed = assistantMessage({ content: [], stopReason: "error" });
+ (failed as { errorMessage?: string }).errorMessage = "terminated";
+ const silent = assistantMessage({ content: [] });
+ agent.prompt = vi.fn(async () => {
+ agent.state.messages = [{ role: "user", content: "Task completed", timestamp: 1 }, failed];
+ await handle({ type: "message_start", message: failed });
+ await handle({ type: "message_end", message: failed });
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.continue = vi.fn(async () => {
+ agent.state.messages = [...agent.state.messages, silent];
+ await handle({ type: "agent_start" });
+ await handle({ type: "message_start", message: silent });
+ await handle({ type: "message_end", message: silent });
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.waitForIdle = vi.fn(async () => undefined);
+ try {
+ await runtime.prompt({ text: "Task completed", sessionMessage: completionOrigin }, "notice-user", "notice-turn");
+ // One provider retry, then the silent notice reply is accepted as-is.
+ expect(agent.continue).toHaveBeenCalledOnce();
+ const events = eventsOf(onEvent);
+ expect(events.some((event) => event.type === "error")).toBe(false);
+ expect(events.filter((event) => event.type === "agent_end")).toHaveLength(1);
+ expect(events).toContainEqual(expect.objectContaining({
+ type: "message_end", message: expect.objectContaining({ status: "complete" }),
+ }));
+ expect(agent.state.messages.some((message: { role: string }) => message.role === "assistant")).toBe(false);
+ } finally { await runtime.dispose(); }
+ });
+
+ it("answers user steering after a silent notice reply with full recovery", async () => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const agent = (runtime as any).agent;
+ const handle = (runtime as any).handleAgentEvent.bind(runtime);
+ const silent = assistantMessage({ content: [] });
+ agent.prompt = vi.fn(async () => {
+ agent.state.messages = [...agent.state.messages, silent];
+ await handle({ type: "agent_start" });
+ await handle({ type: "message_start", message: silent });
+ // The user types while the notice reply streams; pi injects the
+ // steering message after this reply and streams another one.
+ agent.state.isStreaming = true;
+ runtime.steer({ text: "Please answer now" }, "notice-turn", {
+ id: "steering", role: "user", content: "Please answer now",
+ status: "complete", createdAt: new Date().toISOString(),
+ });
+ await handle({ type: "message_end", message: silent });
+ const [queued] = [...(runtime as any).pendingSteering.keys()];
+ agent.state.messages = [...agent.state.messages, queued];
+ await handle({ type: "message_start", message: queued });
+ await handle({ type: "message_end", message: queued });
+ agent.state.messages = [...agent.state.messages, silent];
+ await handle({ type: "message_start", message: silent });
+ await handle({ type: "message_end", message: silent });
+ agent.state.isStreaming = false;
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.continue = vi.fn(async () => {
+ await handle({ type: "agent_start" });
+ await handle({ type: "message_start", message: silent });
+ await handle({ type: "message_end", message: silent });
+ await handle({ type: "turn_end" });
+ await handle({ type: "agent_end", messages: [] });
+ });
+ agent.waitForIdle = vi.fn(async () => undefined);
+ try {
+ await runtime.prompt({ text: "Task completed", sessionMessage: completionOrigin }, "notice-user", "notice-turn");
+ // The notice reply spent the exception silently; the reply to the user
+ // still gets its one re-run and then the visible error.
+ expect(agent.continue).toHaveBeenCalledOnce();
+ expect(eventsOf(onEvent)).toContainEqual(emptyModelResponse);
+ } finally { await runtime.dispose(); }
+ });
+
it("frames live input and restored history identically without changing human input", async () => {
const origin: SessionMessageOrigin = {
messageId: "delivery-1", sourceSessionId: "sender", sourceTitle: "Coordinator",
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 535aa33d0..76c78cd3e 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1573,7 +1573,11 @@ export class DesktopAgentRuntime {
* One automatic re-run per prompt, then the failure becomes visible. */
private pendingSilentTurnRerun = false;
private silentTurnRerunAttempted = false;
- /** Only a current Host-ledger completion notice may need no acknowledgement. */
+ /**
+ * The first settled reply to a current Host-ledger completion notice may
+ * need no acknowledgement (D446). Spent by that reply, and revoked as soon
+ * as accepted user steering enters the model context.
+ */
private allowSilentCompletion = false;
private silentTurnRerunInProgress = false;
private suppressSilentTurnRunEnd = false;
@@ -6682,8 +6686,15 @@ Delegation rules:
if (event.message.role === "user") {
const steeringId = this.pendingSteering.get(event.message);
const id = steeringId ?? this.pendingUserMessageId ?? randomUUID();
- if (steeringId) this.pendingSteering.delete(event.message);
- else this.pendingUserMessageId = undefined;
+ if (steeringId) {
+ this.pendingSteering.delete(event.message);
+ // User input is now part of the model context: whatever the model
+ // says next answers the user, not a completion notice, so the
+ // ordinary response contract applies again.
+ this.allowSilentCompletion = false;
+ } else {
+ this.pendingUserMessageId = undefined;
+ }
this.appendLiveEntry(id, event.message);
break;
}
@@ -6768,12 +6779,20 @@ Delegation rules:
// leaving the user with nothing: the reasoning that may hold the
// answer is never rendered. Re-run once with a nudge before letting
// that surface as a finished turn.
- const silentTurn =
- !this.allowSilentCompletion &&
+ const silence =
!failed &&
!aborted &&
responseText.trim().length === 0 &&
!messageRequestsTools(event.message);
+ // A completion notice needs no acknowledgement, so its own reply may
+ // stay silent (D446). The exception covers exactly that reply: the
+ // first settled response spends it, whether silent, textual, or a
+ // tool batch, so later replies in the same run answer tool results
+ // or user input under the ordinary contract. A provider failure
+ // keeps it for the retried attempt.
+ const exemptSilence = silence && this.allowSilentCompletion;
+ if (!failed && !aborted) this.allowSilentCompletion = false;
+ const silentTurn = silence && !exemptSilence;
if (silentTurn && !this.silentTurnRerunAttempted) {
this.silentTurnRerunAttempted = true;
this.pendingSilentTurnRerun = true;
@@ -6918,7 +6937,18 @@ Delegation rules:
this.compactionEnabled &&
overflow &&
!this.overflowRecoveryAttempted;
- if (!failed && !aborted && !emptyResponse) {
+ if (exemptSilence) {
+ // Accepted silence is still nothing worth resending: keep it out
+ // of the runtime entries, exactly as a restored transcript would,
+ // and out of pi's transcript state so the next request carries no
+ // empty assistant message. pi appends the message before it
+ // notifies listeners; the identity check keeps this from touching
+ // anything else should that order ever change.
+ const messages = this.agent.state.messages;
+ if (messages.at(-1) === event.message) {
+ this.agent.state.messages = messages.slice(0, -1);
+ }
+ } else if (!failed && !aborted && !emptyResponse) {
this.appendLiveEntry(assistantId, event.message);
} else {
this.turnHadError = true;
@@ -7455,8 +7485,6 @@ Delegation rules:
steer(input: RuntimePrompt, expectedTurnId: string, message: UiMessage): { accepted: boolean; turnId: string } {
this.steeringContext(expectedTurnId);
- // User input accepted during a notice requires the ordinary response contract.
- this.allowSilentCompletion = false;
const queued: AgentMessage = { role: "user", content: promptContent(input), timestamp: Date.now() };
this.pendingSteering.set(queued, message.id);
this.agent.steer(queued);
diff --git a/packages/agent-runtime/src/session-context.test.ts b/packages/agent-runtime/src/session-context.test.ts
index 9c1cad248..3fd3522f2 100644
--- a/packages/agent-runtime/src/session-context.test.ts
+++ b/packages/agent-runtime/src/session-context.test.ts
@@ -82,6 +82,20 @@ describe("buildSessionContext", () => {
).toBe("ok");
});
+ it("drops assistants that have no content blocks", () => {
+ // D446: an accepted silent completion reply, or any other empty
+ // assistant, is not worth resending and would be rejected by providers.
+ const empty = assistant("a1", "", 1);
+ (empty.message as { content: unknown[] }).content = [];
+ const messages = buildSessionContext([
+ user("u1", "notice", 0),
+ empty,
+ user("u2", "next", 2),
+ assistant("a2", "answer", 3),
+ ]).messages;
+ expect(messages.map((message) => message.role)).toEqual(["user", "user", "assistant"]);
+ });
+
it("slices from the newest compaction and puts the summary before the tail", () => {
const keptUser = user("u2", "keep me", 3).message;
const messages = buildSessionContext([
diff --git a/packages/agent-runtime/src/session-context.ts b/packages/agent-runtime/src/session-context.ts
index 176bce50a..5aae7c8de 100644
--- a/packages/agent-runtime/src/session-context.ts
+++ b/packages/agent-runtime/src/session-context.ts
@@ -24,12 +24,19 @@ import {
type ReasoningReplayIdentity,
} from "./reasoning-replay.js";
+/**
+ * Failed, aborted, and deferred assistants are transcript rows, not context.
+ * An assistant with no content blocks is not worth resending either: the
+ * runtime never appends one live, a restored transcript drops them, and a
+ * provider would reject or silently skip it (D446).
+ */
function isContextMessage(message: AgentMessage): boolean {
return (
message.role !== "assistant" ||
(message.stopReason !== "error" &&
message.stopReason !== "aborted" &&
- message.stopReason !== "deferred")
+ message.stopReason !== "deferred" &&
+ message.content.length > 0)
);
}
diff --git a/scripts/e2e-session-completion.mjs b/scripts/e2e-session-completion.mjs
index 942568d67..26da188cd 100644
--- a/scripts/e2e-session-completion.mjs
+++ b/scripts/e2e-session-completion.mjs
@@ -88,6 +88,11 @@ async function runTurn(sessionId, content, delivery, expectedError = false) {
assert.equal(errors.length, expectedError ? 1 : 0, JSON.stringify(errors));
if (expectedError) assert.equal(errors[0].error.code, "EMPTY_MODEL_RESPONSE");
assert.equal(requests.length - before, expectedError ? 2 : 1, "empty recovery is bounded and completion does not retry");
+ for (const payload of requests.slice(before)) {
+ const emptyAssistant = payload.messages.filter((message) =>
+ message.role === "assistant" && !message.tool_calls && !(typeof message.content === "string" ? message.content : "").trim());
+ assert.deepEqual(emptyAssistant, [], "no request carries an empty assistant message");
+ }
assert.equal(turnEvents.filter((event) => event.type === "agent_end").length, 1);
for (const event of turnEvents) {
if (event.type === "message_end" && event.message.role === "assistant") {