mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(agents): preserve autonomous run ownership during prompt admission
Keep Stop available when a follow-up is rejected, honor explicit interrupt delivery, and record pending tool IDs covered by a session Stop.
This commit is contained in:
@@ -1414,7 +1414,7 @@ class AcpRuntime {
|
||||
): void {
|
||||
for (const [id, record] of this.toolCalls) {
|
||||
const { snapshot, turnId, settlement } = record;
|
||||
if (settlement) continue;
|
||||
if (settlement === "canceled" || (settlement && state !== "canceled")) continue;
|
||||
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
|
||||
if (options?.preserveBackgroundTools && this.backgroundToolCalls.has(id)) continue;
|
||||
if (options?.preserveInProgressTools && snapshot.status === "in_progress") continue;
|
||||
|
||||
@@ -2831,6 +2831,13 @@ describe("ACP out-of-turn background activity", () => {
|
||||
promptUpdates: (text) =>
|
||||
text === "Start"
|
||||
? [
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "pending-before-stop",
|
||||
kind: "execute",
|
||||
title: "Pending command",
|
||||
status: "pending",
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "cmd-1",
|
||||
@@ -2961,6 +2968,14 @@ describe("ACP out-of-turn background activity", () => {
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "cmd-2", status: "failed" },
|
||||
});
|
||||
agent.notify("session/update", output);
|
||||
agent.notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "pending-before-stop",
|
||||
status: "failed",
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(events.filter((event) => event.type === "session.turn")).toHaveLength(
|
||||
turnCountAfterCancel,
|
||||
|
||||
@@ -3180,7 +3180,9 @@ export class AgentManager {
|
||||
}): Promise<string | null> {
|
||||
const { agent, agentId, pendingRun, prompt, options, promptStart } = params;
|
||||
if (promptStart?.admit?.() === false) {
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
if (!(await this.restoreAutonomousRun(agentId, pendingRun))) {
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
@@ -3217,8 +3219,10 @@ export class AgentManager {
|
||||
stale: true,
|
||||
});
|
||||
agent.pendingReplacement = false;
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
if (!(await this.restoreAutonomousRun(agentId, pendingRun))) {
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3231,12 +3235,17 @@ export class AgentManager {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
if (await this.restoreAutonomousRun(agentId, pendingRun)) {
|
||||
await this.appendSystemErrorTimelineMessage(agent, agent.provider, errorMsg);
|
||||
this.emitState(agent);
|
||||
} else {
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
}
|
||||
} finally {
|
||||
// A steer waiting on this start is released only once the run is cleared.
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
@@ -3245,6 +3254,16 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async restoreAutonomousRun(
|
||||
agentId: string,
|
||||
pending: PendingForegroundRun,
|
||||
): Promise<boolean> {
|
||||
if (!this.runs.restoreAutonomousRun(agentId, pending)) return false;
|
||||
for (const event of pending.stagedEvents.splice(0)) this.enqueueSessionEvent(agentId, event);
|
||||
await this.drainSessionEvents(agentId);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async ensureInteractiveSession(agentId: string): Promise<ActiveManagedAgent> {
|
||||
const agent = this.requireSessionAgent(agentId);
|
||||
if (this.historySessions.has(agent.session)) {
|
||||
@@ -3337,8 +3356,6 @@ export class AgentManager {
|
||||
const isReplacement = agent.pendingReplacement;
|
||||
agent.lastError = undefined;
|
||||
|
||||
// The provider settles this autonomous turn when it admits the new prompt.
|
||||
if (acceptsFollowUp) this.runs.clearAgentRun(agentId);
|
||||
const pendingRun = this.runs.createPendingRun(agentId);
|
||||
promptStart?.bind(pendingRun);
|
||||
|
||||
@@ -3517,9 +3534,10 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
admission?: { allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.requireSessionAgent(agentId);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart, admission);
|
||||
}
|
||||
|
||||
async steerAgentRun(
|
||||
@@ -3677,9 +3695,9 @@ export class AgentManager {
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
|
||||
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, {
|
||||
assert: (live) => this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3691,12 +3709,12 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
admission?: { assert?: (agent: ActiveManagedAgent) => void; allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
// Replacements queue in arrival order; each one holds the foreground lane only while
|
||||
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
|
||||
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, admission),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3705,7 +3723,7 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
delivery?: { assert?: (agent: ActiveManagedAgent) => void; allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
let stalledStart: PendingForegroundRun | null = null;
|
||||
for (;;) {
|
||||
@@ -3719,8 +3737,9 @@ export class AgentManager {
|
||||
if (starting && starting.start.status !== "started" && starting !== stalledStart) {
|
||||
return { status: "starting" as const, run: starting };
|
||||
}
|
||||
assertAdmission?.(agent);
|
||||
if (!this.hasInFlightRun(agent.id) || this.runs.acceptsFollowUp(agent.id)) {
|
||||
delivery?.assert?.(agent);
|
||||
const canHandOff = delivery?.allowAutonomousHandoff && this.runs.acceptsFollowUp(agent.id);
|
||||
if (!this.hasInFlightRun(agent.id) || canHandOff) {
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
|
||||
@@ -92,7 +92,9 @@ async function startOrReplaceRun(
|
||||
}> {
|
||||
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
|
||||
const iterator = replaced
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart, {
|
||||
allowAutonomousHandoff: options?.activeTurnBehavior !== "interrupt",
|
||||
})
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
|
||||
return { iterator, replaced };
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface PendingForegroundRun {
|
||||
token: string;
|
||||
kind: "foreground";
|
||||
stagedEvents: AgentStreamEvent[];
|
||||
handoffFrom?: AutonomousAgentRun;
|
||||
start: ForegroundRunStart;
|
||||
turnStartedPromise: Promise<void>;
|
||||
resolveTurnStarted: () => void;
|
||||
@@ -50,6 +51,10 @@ export class AgentRunState {
|
||||
|
||||
createPendingRun(agentId: string): PendingForegroundRun {
|
||||
const pendingRun = createPendingForegroundRun();
|
||||
const current = this.runs.get(agentId);
|
||||
if (current?.kind === "autonomous" && current.acceptsFollowUp) {
|
||||
pendingRun.handoffFrom = current;
|
||||
}
|
||||
this.runs.set(agentId, pendingRun);
|
||||
return pendingRun;
|
||||
}
|
||||
@@ -65,6 +70,7 @@ export class AgentRunState {
|
||||
): void {
|
||||
run.start = start;
|
||||
if (start.status === "started") {
|
||||
this.settleHandoff(run);
|
||||
run.resolveTurnStarted();
|
||||
}
|
||||
}
|
||||
@@ -131,6 +137,14 @@ export class AgentRunState {
|
||||
if (!run) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.kind === "foreground" &&
|
||||
run.handoffFrom &&
|
||||
(turnId === undefined || turnId === run.handoffFrom.turnId)
|
||||
) {
|
||||
this.settleHandoff(run);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.kind === "foreground" &&
|
||||
(run.start.status !== "started" || run.start.turnId !== turnId)
|
||||
@@ -165,6 +179,14 @@ export class AgentRunState {
|
||||
}
|
||||
}
|
||||
|
||||
restoreAutonomousRun(agentId: string, pending: PendingForegroundRun): boolean {
|
||||
if (this.runs.get(agentId) !== pending || !pending.handoffFrom) return false;
|
||||
this.runs.set(agentId, pending.handoffFrom);
|
||||
pending.handoffFrom = undefined;
|
||||
settleTrackedRun(pending);
|
||||
return true;
|
||||
}
|
||||
|
||||
createTurnStream(turnId: string): ForegroundTurnStream {
|
||||
return new ForegroundTurnStream(turnId);
|
||||
}
|
||||
@@ -250,8 +272,15 @@ export class AgentRunState {
|
||||
|
||||
private clearRun(agentId: string, run: TrackedAgentRun): void {
|
||||
this.runs.delete(agentId);
|
||||
if (run.kind === "foreground") this.settleHandoff(run);
|
||||
settleTrackedRun(run);
|
||||
}
|
||||
|
||||
private settleHandoff(run: PendingForegroundRun): void {
|
||||
if (!run.handoffFrom) return;
|
||||
settleTrackedRun(run.handoffFrom);
|
||||
run.handoffFrom = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class ForegroundTurnStream {
|
||||
|
||||
@@ -20,7 +20,7 @@ import { cancelAgentRunCommand } from "./lifecycle-command.js";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import type { AgentClient, AgentStreamEvent } from "./agent-sdk-types.js";
|
||||
import type { AgentClient, AgentPromptInput, AgentStreamEvent } from "./agent-sdk-types.js";
|
||||
import { toStoredAgentRecord } from "./agent-projections.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { buildProviderRegistry } from "./provider-registry.js";
|
||||
@@ -2819,7 +2819,7 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["steer", "stop"] as const)(
|
||||
test.each(["steer", "stop", "interrupt", "refused follow-up"] as const)(
|
||||
"Antigravity ACP background work through the daemon's %s command",
|
||||
async (action) => {
|
||||
const home = await mkdtemp(join(tmpdir(), "plugin-bg-work-"));
|
||||
@@ -2854,15 +2854,19 @@ test.each(["steer", "stop"] as const)(
|
||||
},
|
||||
});
|
||||
}
|
||||
wake = () =>
|
||||
acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "cmd-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
wake = async () => {
|
||||
const finished = action === "refused follow-up" ? ["cmd-1", "cmd-2"] : ["cmd-1"];
|
||||
for (const toolCallId of finished) {
|
||||
await acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
return { stopReason: "end_turn" };
|
||||
},
|
||||
@@ -2882,8 +2886,8 @@ test.each(["steer", "stop"] as const)(
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const send = async (prompt: string, activeTurnBehavior?: "steer") => {
|
||||
const result = await sendPromptToAgent({
|
||||
const dispatch = (prompt: AgentPromptInput, activeTurnBehavior?: "steer" | "interrupt") =>
|
||||
sendPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
@@ -2891,6 +2895,8 @@ test.each(["steer", "stop"] as const)(
|
||||
prompt,
|
||||
activeTurnBehavior,
|
||||
});
|
||||
const send = async (prompt: string, activeTurnBehavior?: "steer" | "interrupt") => {
|
||||
const result = await dispatch(prompt, activeTurnBehavior);
|
||||
if (result.disposition !== "turn_started")
|
||||
throw new Error(`Unexpected dispatch: ${result.disposition}`);
|
||||
await result.started;
|
||||
@@ -2908,15 +2914,38 @@ test.each(["steer", "stop"] as const)(
|
||||
{ id: "cmd-2", kind: "shell" },
|
||||
]);
|
||||
|
||||
if (action === "steer") {
|
||||
if (action !== "stop") {
|
||||
await wake();
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
}
|
||||
if (action === "steer") {
|
||||
await send("Follow up", "steer");
|
||||
expect(calls).toEqual(["Start two commands", "Follow up"]);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([
|
||||
{ id: "cmd-2", kind: "shell", description: "cmd-2", startedAt: expect.any(String) },
|
||||
]);
|
||||
expect(toolStatuses("cmd-1")).toEqual(["completed"]);
|
||||
} else if (action === "interrupt") {
|
||||
await send("Follow up", "interrupt");
|
||||
expect(calls).toEqual(["Start two commands", "session/cancel", "Follow up"]);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
|
||||
} else if (action === "refused follow-up") {
|
||||
await expect.poll(() => manager.listAgentBackgroundWork(agent.id)).toEqual([]);
|
||||
const result = await dispatch(
|
||||
[{ type: "image", data: "AA==", mimeType: "image/png" }],
|
||||
"steer",
|
||||
);
|
||||
if (result.disposition !== "turn_started")
|
||||
throw new Error(`Unexpected dispatch: ${result.disposition}`);
|
||||
await expect(result.started).rejects.toThrow(/image/i);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
const { cancelled } = await cancelAgentRunCommand(
|
||||
{ agentManager: manager, logger },
|
||||
agent.id,
|
||||
);
|
||||
expect(cancelled).toBe(true);
|
||||
await expect.poll(() => calls).toEqual(["Start two commands", "session/cancel"]);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
} else {
|
||||
const { cancelled } = await cancelAgentRunCommand(
|
||||
{ agentManager: manager, logger },
|
||||
|
||||
Reference in New Issue
Block a user