fix(pi): keep the turn open when an extension sends context before Pi answers the prompt (#11533)

Pi answers the prompt RPC only after extension preflight. A custom message an
extension sends from before_agent_start therefore reaches Paseo before the
response and before agent_start. The adapter treated that message as an
extension command's output and completed the turn. The run then continued
without a turn, and Pi's echo of the prompt arrived without the client message
ID, so the chat showed the user's message twice.

A custom message no longer completes a turn whose prompt is unanswered. Once Pi
answers, the adapter asks Pi for its state, as it already does for slash
commands, and completes the turn only if no run is starting.

Co-authored-by: Stelath <25530613+Stelath@users.noreply.github.com>
This commit is contained in:
paseo-bot[bot]
2026-12-01 03:13:28 +00:00
committed by GitHub
co-authored by Stelath
parent b9bd2a2b05
commit 66b57ed3b3
3 changed files with 121 additions and 9 deletions
@@ -1465,6 +1465,87 @@ describe("PiRpcAgentSession", () => {
]);
});
test("keeps the turn open when an extension sends context before Pi answers the prompt", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
// Pi answers `prompt` after before_agent_start, where extensions inject hidden context.
fakeSession.holdNextPrompt();
const { turnId } = await session.startTurn("hello", { clientMessageId: "client-hello" });
fakeSession.emit({
type: "message_end",
message: {
role: "custom",
customType: "project-context",
content: [{ type: "text", text: "Hidden context" }],
display: false,
},
});
// Pi writes its answer and agent_start back to back.
const answered = fakeSession.answerHeldPrompt();
fakeSession.emit({ type: "agent_start" });
fakeSession.emit({ type: "turn_start" });
await answered;
fakeSession.finishSubmittedUserMessage({ id: "entry-hello", parentId: null, text: "hello" });
expect(events.turnCompletedEvents()).toHaveLength(0);
expect(events.timelineItems()).toEqual([
{
type: "user_message",
text: "hello",
messageId: "entry-hello",
clientMessageId: "client-hello",
},
]);
fakeSession.finishTurn();
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
expect(events.turnCompletedEvents()).toHaveLength(1);
await session.close();
});
test("keeps the turn open when Pi has answered the prompt and is still starting the run", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
fakeSession.holdNextPrompt();
const { turnId } = await session.startTurn("hello");
fakeSession.emit({
type: "message_end",
message: {
role: "custom",
content: [{ type: "text", text: "Hidden context" }],
display: false,
},
});
fakeSession.state = { ...fakeSession.state, isStreaming: true };
await fakeSession.answerHeldPrompt();
await flushTurnScheduling();
expect(events.turnCompletedEvents()).toHaveLength(0);
fakeSession.emit({ type: "agent_start" });
fakeSession.finishTurn();
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
await session.close();
});
test("completes a prompt an extension handled with a custom message once Pi answers it", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
fakeSession.holdNextPrompt();
const { turnId } = await session.startTurn("show status");
fakeSession.emit({
type: "message_end",
message: { role: "custom", content: [{ type: "text", text: "Extension output" }] },
});
expect(events.turnCompletedEvents()).toHaveLength(0);
await fakeSession.answerHeldPrompt();
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
await session.close();
});
test("settles an autonomous turn triggered by a Pi extension custom message", async () => {
const { pi, events } = await createSession();
const fakeSession = pi.latestSession();
@@ -1219,6 +1219,9 @@ export class PiRpcAgentSession implements AgentSession {
private activeNoTurnPromptText: string | null = null;
private readonly pendingNoTurnOutputs: Array<{ turnId: string; message: string }> = [];
private activePromptRequestId: string | null = null;
// Pi answers `prompt` only after extension preflight (input handlers, the compaction check and
// before_agent_start), so events can arrive for a turn whose prompt is still unanswered.
private promptPreflight: { turnId: string; sawCustomMessage: boolean } | null = null;
private readonly pendingPromptResults = new Map<string, boolean>();
private readonly pendingSteerSubmissions: PiPendingSteerSubmission[] = [];
currentLeafOverrideId: string | null | undefined;
@@ -1368,7 +1371,11 @@ export class PiRpcAgentSession implements AgentSession {
return;
}
}
const ack = await this.runtimeSession.prompt(payload.text, payload.images);
const preflight = { turnId, sawCustomMessage: false };
this.promptPreflight = preflight;
const ack = await this.runtimeSession.prompt(payload.text, payload.images).finally(() => {
if (this.promptPreflight === preflight) this.promptPreflight = null;
});
this.activePromptRequestId = ack.requestId ?? null;
const correlatedResult = ack.requestId
? this.pendingPromptResults.get(ack.requestId)
@@ -1381,10 +1388,12 @@ export class PiRpcAgentSession implements AgentSession {
await this.completeNoTurnPrompt(turnId);
return;
}
// Pi can acknowledge a prompt as handled even when the extension starts a run.
// A custom message or a handled acknowledgment can precede a run started by the extension.
if (
agentInvoked === undefined &&
(ack.handledByExtension || this.parseSlashCommandInput(payload.text) !== null)
(preflight.sawCustomMessage ||
ack.handledByExtension ||
this.parseSlashCommandInput(payload.text) !== null)
) {
await this.completePromptIfHandledWithoutTurn(turnId);
}
@@ -2649,7 +2658,12 @@ export class PiRpcAgentSession implements AgentSession {
),
});
}
if (!this.activeTurnStarted) {
// An extension can send context from preflight, before Pi answers the prompt. Whether a run
// follows is known once Pi answers; startTurn checks then.
const preflight = this.promptPreflight;
if (preflight && preflight.turnId === turnId) {
preflight.sawCustomMessage = true;
} else if (!this.activeTurnStarted) {
this.completeTurn(turnId, []);
}
return;
@@ -53,6 +53,12 @@ interface FakePiUserEntry {
text: string;
}
interface HeldPrompt {
promise: Promise<void>;
resolve: () => void;
reject: (error: Error) => void;
}
export class FakePi implements PiRuntime {
readonly recordedLaunches: PiRuntimeLaunch[] = [];
private readonly sessions: FakePiSession[] = [];
@@ -183,9 +189,8 @@ export class FakePiSession implements PiRuntimeSession {
private readonly subscribers = new Set<(event: PiRuntimeEvent) => void>();
private readonly subagentMessageResults = new Map<string, FakePiSubagentMessagesResult[]>();
private nextHeldPrompt: { promise: Promise<void>; reject: (error: Error) => void } | null = null;
private activeHeldPrompt: { promise: Promise<void>; reject: (error: Error) => void } | null =
null;
private nextHeldPrompt: HeldPrompt | null = null;
private activeHeldPrompt: HeldPrompt | null = null;
constructor(
launch: PiRuntimeLaunch,
@@ -238,11 +243,23 @@ export class FakePiSession implements PiRuntimeSession {
if (this.nextHeldPrompt || this.activeHeldPrompt) {
throw new Error("FakePi already has a held prompt");
}
let resolve!: () => void;
let reject!: (error: Error) => void;
const promise = new Promise<void>((_resolve, rejectPromise) => {
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
this.nextHeldPrompt = { promise, reject };
this.nextHeldPrompt = { promise, resolve, reject };
}
/** Pi answers a prompt only after extension preflight; this ends that wait. */
async answerHeldPrompt(): Promise<void> {
const heldPrompt = this.activeHeldPrompt ?? this.nextHeldPrompt;
if (!heldPrompt) {
throw new Error("FakePi has no held prompt");
}
heldPrompt.resolve();
await new Promise<void>((resolve) => setImmediate(resolve));
}
async failHeldPrompt(error: Error): Promise<void> {