fix(agents): preserve background work during follow-up prompts

Let providers hand off autonomous turns without a session cancel. Stop cancellable session work explicitly, and keep earlier commands tracked across prompt failures and delayed tool updates.
This commit is contained in:
Mohamed Boudra
2026-11-20 10:16:53 +01:00
parent 66185df4f5
commit c7fbd08215
28 changed files with 383 additions and 161 deletions
@@ -10,6 +10,7 @@ test("retries a failed observation and receives subsequent updates", async () =>
}
const observers: Observer[] = [];
let releases = 0;
const interrupted: string[] = [];
const item = {
id: "shell",
kind: "shell",
@@ -19,6 +20,10 @@ test("retries a failed observation and receives subsequent updates", async () =>
const client = {
getLastServerInfoMessage: () => ({ features: { agentBackgroundWork: true } }),
stopAgentBackgroundWork: async () => {},
cancelAgent: async (agentId: string) => {
interrupted.push(agentId);
if (interrupted.length === 1) throw new Error("Stop failed");
},
listAgentBackgroundWork: async () => [item],
observeAgentBackgroundWork: () => ({
subscribe: (observer: Observer) => {
@@ -54,6 +59,13 @@ test("retries a failed observation and receives subsequent updates", async () =>
payload: { agentId: "agent", items: [] },
});
expect(model.getSnapshot()).toEqual({ status: "ready", items: [] });
const firstStop = model.interruptSession();
expect(model.getSnapshot().sessionStop).toBe("pending");
await firstStop;
expect(model.getSnapshot().sessionStop).toBe("error");
await model.interruptSession();
expect(model.getSnapshot().sessionStop).toBeUndefined();
expect(interrupted).toEqual(["agent", "agent"]);
unsubscribe();
});
@@ -71,6 +83,7 @@ test("starts observing after the same client reconnects", async () => {
getLastServerInfoMessage: () =>
connected ? { features: { agentBackgroundWork: true } } : null,
stopAgentBackgroundWork: async () => {},
cancelAgent: async () => {},
listAgentBackgroundWork: async () => [item],
observeAgentBackgroundWork: () => ({
subscribe: (observer: { snapshot(): void }) => {
+5
View File
@@ -8,6 +8,7 @@ interface BackgroundWorkClient {
features?: { agentBackgroundWork?: boolean; agentBackgroundWorkStop?: boolean } | null;
} | null;
stopAgentBackgroundWork(agentId: string, item: PaseoAgentBackgroundWorkItem): Promise<void>;
cancelAgent(agentId: string): Promise<void>;
listAgentBackgroundWork(agentId: string): Promise<PaseoAgentBackgroundWorkItem[]>;
observeAgentBackgroundWork(): {
subscribe(observer: {
@@ -45,6 +46,10 @@ export function createHostBackgroundWorkModel(
return items.map(({ canStop: _canStop, stopToken: _stopToken, ...item }) => item);
};
return createBackgroundWorkModel({
interruptSession: () => {
if (!client) return Promise.reject(new Error("Host disconnected"));
return client.cancelAgent(agentId);
},
stop: (item) => {
if (!client) return Promise.reject(new Error("Host disconnected"));
return client.stopAgentBackgroundWork(agentId, item);
+22 -1
View File
@@ -18,12 +18,14 @@ function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" {
export function BackgroundWorkTrack({
model,
count,
canInterruptSession,
}: {
model: ReturnType<typeof createHostBackgroundWorkModel>;
count: number;
canInterruptSession: boolean;
}) {
const { t } = useTranslation();
const { items, status, stops } = useSyncExternalStore(
const { items, status, stops, sessionStop } = useSyncExternalStore(
model.subscribe,
model.getSnapshot,
model.getSnapshot,
@@ -77,6 +79,25 @@ export function BackgroundWorkTrack({
stopStatus={stops?.[item.stopToken ?? ""]?.status}
/>
))}
{canInterruptSession && status === "ready" ? (
<ComposerTrackRow>
<View style={styles.row}>
{sessionStop === "error" ? (
<Text style={styles.facts}>{t("message.backgroundWork.stopError")}</Text>
) : null}
<Button
variant="ghost"
size="sm"
disabled={sessionStop === "pending"}
onPress={model.interruptSession}
>
{sessionStop === "pending"
? t("message.backgroundWork.stopping")
: t("message.backgroundWork.stopSession")}
</Button>
</View>
</ComposerTrackRow>
) : null}
</ComposerTrackPill>
);
}
+21 -5
View File
@@ -3,6 +3,7 @@ import type { PaseoAgentBackgroundWorkItem as AgentBackgroundWorkItem } from "@g
interface Port {
list(): Promise<AgentBackgroundWorkItem[]>;
stop?(item: AgentBackgroundWorkItem): Promise<void>;
interruptSession?(): Promise<void>;
observe(callbacks: {
snapshot(): void;
disconnected(): void;
@@ -15,6 +16,7 @@ interface BackgroundWorkState {
status: "loading" | "stale" | "ready" | "error";
items: AgentBackgroundWorkItem[] | null;
stops?: Record<string, { status: "pending" | "error"; item: AgentBackgroundWorkItem }>;
sessionStop?: "pending" | "error";
}
export function createBackgroundWorkModel(port: Port) {
@@ -25,10 +27,7 @@ export function createBackgroundWorkModel(port: Port) {
let observationFailed = false;
const listeners = new Set<() => void>();
const publish = (next: BackgroundWorkState) => {
state =
next.stops === undefined && state.stops === undefined
? next
: { ...next, stops: next.stops ?? state.stops };
state = { ...state, ...next };
for (const listener of listeners) listener();
};
const refresh = async () => {
@@ -58,7 +57,12 @@ export function createBackgroundWorkModel(port: Port) {
{ ...entry, status: "error" as const },
]),
);
publish({ status: state.items === null ? "loading" : "stale", items: state.items, stops });
publish({
status: state.items === null ? "loading" : "stale",
items: state.items,
...(stops ? { stops } : {}),
...(state.sessionStop === "pending" ? { sessionStop: "error" } : {}),
});
},
failed: () => {
observationFailed = true;
@@ -95,6 +99,18 @@ export function createBackgroundWorkModel(port: Port) {
publish({ ...state, stops: { ...state.stops, [token]: { status: "error", item } } });
}
},
interruptSession: async () => {
if (!port.interruptSession || state.status !== "ready" || state.sessionStop === "pending")
return;
const generation = stopGeneration;
publish({ ...state, sessionStop: "pending" });
try {
await port.interruptSession();
if (generation === stopGeneration) publish({ ...state, sessionStop: undefined });
} catch {
if (generation === stopGeneration) publish({ ...state, sessionStop: "error" });
}
},
retry: () => {
if (observationFailed) {
stop?.();
+1
View File
@@ -406,6 +406,7 @@ export const ar: TranslationResources = {
notRunning: "لم يعد قيد التشغيل",
dismiss: "إغلاق",
stop: "إيقاف",
stopSession: "إيقاف الوكيل وعمله في الخلفية",
stopping: "جارٍ الإيقاف…",
stopError: "تعذر تأكيد الإيقاف.",
label: "في الخلفية",
+1
View File
@@ -405,6 +405,7 @@ export const en = {
notRunning: "No longer running",
dismiss: "Dismiss",
stop: "Stop",
stopSession: "Stop agent and its background work",
stopping: "Stopping…",
stopError: "Could not confirm stop.",
label: "Background",
+1
View File
@@ -411,6 +411,7 @@ export const es: TranslationResources = {
notRunning: "Ya no está en ejecución",
dismiss: "Cerrar",
stop: "Detener",
stopSession: "Detener el agente y su trabajo en segundo plano",
stopping: "Deteniendo…",
stopError: "No se pudo confirmar la detención.",
label: "Segundo plano",
+1
View File
@@ -411,6 +411,7 @@ export const fr: TranslationResources = {
notRunning: "N’est plus en cours",
dismiss: "Fermer",
stop: "Arrêter",
stopSession: "Arrêter l’agent et son travail en arrière-plan",
stopping: "Arrêt…",
stopError: "Impossible de confirmer l’arrêt.",
label: "Arrière-plan",
+1
View File
@@ -411,6 +411,7 @@ export const ja: TranslationResources = {
notRunning: "実行は終了しました",
dismiss: "閉じる",
stop: "停止",
stopSession: "エージェントとそのバックグラウンド処理を停止",
stopping: "停止中…",
stopError: "停止を確認できませんでした。",
label: "バックグラウンド",
+1
View File
@@ -407,6 +407,7 @@ export const ko: TranslationResources = {
notRunning: "더 이상 실행 중이 아님",
dismiss: "닫기",
stop: "중지",
stopSession: "에이전트와 백그라운드 작업 중지",
stopping: "중지 중…",
stopError: "중지를 확인하지 못했습니다.",
label: "백그라운드",
+1
View File
@@ -410,6 +410,7 @@ export const ptBR: TranslationResources = {
notRunning: "Não está mais em execução",
dismiss: "Dispensar",
stop: "Parar",
stopSession: "Parar o agente e seu trabalho em segundo plano",
stopping: "Parando…",
stopError: "Não foi possível confirmar a parada.",
label: "Segundo plano",
+1
View File
@@ -410,6 +410,7 @@ export const ru: TranslationResources = {
notRunning: "Больше не выполняется",
dismiss: "Закрыть",
stop: "Остановить",
stopSession: "Остановить агента и его фоновые задачи",
stopping: "Остановка…",
stopError: "Не удалось подтвердить остановку.",
label: "В фоне",
+1
View File
@@ -406,6 +406,7 @@ export const zhCN: TranslationResources = {
notRunning: "已不再运行",
dismiss: "关闭",
stop: "停止",
stopSession: "停止智能体及其后台任务",
stopping: "正在停止…",
stopError: "无法确认已停止。",
label: "后台",
+7 -3
View File
@@ -52,10 +52,10 @@ export const AgentTracks = memo(function AgentTracks({
rows: subagentRows,
});
const { tabId } = usePaneContext();
const backgroundWorkCount = useSessionStore((state) => {
const backgroundWork = useSessionStore((state) => {
const session = state.sessions[serverId];
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
return agent?.backgroundWork?.count ?? 0;
return agent?.backgroundWork;
});
const backgroundModel = useMemo(
() => createHostBackgroundWorkModel(serverId, agentId),
@@ -121,7 +121,11 @@ export const AgentTracks = memo(function AgentTracks({
return (
<ComposerTrackBar>
<BackgroundWorkTrack model={backgroundModel} count={backgroundWorkCount} />
<BackgroundWorkTrack
model={backgroundModel}
count={backgroundWork?.count ?? 0}
canInterruptSession={backgroundWork?.canInterruptSession === true}
/>
{parentAgentId ? <ParentAgentPill serverId={serverId} parentAgentId={parentAgentId} /> : null}
<AgentTaskList tasks={tasks} />
<SubagentsTrack
+4 -3
View File
@@ -23,7 +23,7 @@ export const stopSchema: OutputSchema<StopResult> = {
export function addStopOptions(cmd: Command): Command {
return cmd
.description("Interrupt an agent if it is running (no-op for idle agents)")
.description("Interrupt an active agent or its cancellable session background work")
.argument("[id]", "Agent ID (or prefix) - optional if --all or --cwd specified")
.option("--all", "Stop all agents")
.option("--cwd <path>", "Stop all agents in directory");
@@ -81,10 +81,11 @@ export async function runStopCommand(
agents = [fetchResult.agent];
}
// Interrupt each running agent. Idle agents are a no-op.
const stopResults = await Promise.all(
agents.map(async (agent) => {
if (agent.status !== "running") return { ok: true as const, id: agent.id, stopped: false };
if (agent.status !== "running" && !agent.backgroundWork?.canInterruptSession) {
return { ok: true as const, id: agent.id, stopped: false };
}
try {
await client.cancelAgent(agent.id);
return { ok: true as const, id: agent.id, stopped: true };
@@ -669,7 +669,6 @@ class AcpRuntime {
}
const prompt = toAcpPrompt(input.prompt);
this.replayWindow = null;
this.canceledToolCalls.clear();
const turnId = `acp:${input.prompt.clientMessageId}`;
this.fallbackChunkIds.clear();
this.emit({
@@ -737,8 +736,11 @@ class AcpRuntime {
async (error): Promise<void> => {
await this.drainNotifications();
this.fallbackChunkIds.clear();
this.terminalizeTransientItems("failed");
this.clearBackgroundWork();
const canceled = this.activePrompt?.cancelling === true;
this.terminalizeTransientItems(canceled ? "canceled" : "failed", {
preserveBackgroundTools: !canceled,
});
if (canceled) this.clearBackgroundWork();
this.finishTurnPermissions(turnId);
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
this.emit({
@@ -1384,10 +1386,11 @@ class AcpRuntime {
private terminalizeTransientItems(
state: "completed" | "failed" | "canceled",
options?: { preserveInProgressTools?: boolean },
options?: { preserveInProgressTools?: boolean; preserveBackgroundTools?: boolean },
): void {
for (const [id, snapshot] of this.toolCalls) {
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;
const completed: AcpToolCallSnapshot = {
...snapshot,
@@ -1463,6 +1466,7 @@ class AcpRuntime {
sessionId: this.options.boundarySessionId,
turnId,
state: "started",
acceptsFollowUp: true,
});
}
@@ -1480,15 +1484,6 @@ class AcpRuntime {
this.syncAutonomousTimer();
}
private hasForegroundInProgressTool(): boolean {
for (const [id, snapshot] of this.toolCalls) {
if (snapshot.status === "in_progress" && !this.backgroundToolCalls.has(id)) {
return true;
}
}
return false;
}
private syncAutonomousTimer(): void {
const turn = this.autonomousTurn;
if (!turn || !this.outOfTurnActivity) return;
@@ -1500,10 +1495,6 @@ class AcpRuntime {
this.scheduleAutonomousSettle(this.outOfTurnActivity.settleDelayMs);
return;
}
if (!turn.replyOpen && this.hasForegroundInProgressTool()) {
this.cancelAutonomousSettle();
return;
}
this.scheduleAutonomousSettle(this.outOfTurnActivity.quietLimitMs);
}
@@ -1593,6 +1584,7 @@ class AcpRuntime {
type: "session.background_work",
sessionId: this.options.boundarySessionId,
items,
...(items.length > 0 ? { canInterruptSession: true } : {}),
});
}
@@ -2012,7 +2004,6 @@ function toBackgroundWorkItem(snapshot: AcpToolCallSnapshot): ProviderBackground
kind,
description: summary ?? snapshot.title ?? snapshot.name ?? null,
...(command ? { command } : {}),
canStop: false,
};
}
+67 -25
View File
@@ -2534,13 +2534,13 @@ describe("ACP out-of-turn background activity", () => {
expect(events.findLast((event) => event.type === "session.background_work")).toEqual({
type: "session.background_work",
sessionId: "session-1",
canInterruptSession: true,
items: [
{
id: "cmd-1",
kind: "shell",
description: "Typecheck workspace",
command: "npm run typecheck",
canStop: false,
},
],
});
@@ -2614,13 +2614,13 @@ describe("ACP out-of-turn background activity", () => {
expect(events.findLast((event) => event.type === "session.background_work")).toEqual({
type: "session.background_work",
sessionId: "session-1",
canInterruptSession: true,
items: [
{
id: "cmd-2",
kind: "shell",
description: "npm run lint",
command: "npm run lint",
canStop: false,
},
],
});
@@ -2664,17 +2664,20 @@ describe("ACP out-of-turn background activity", () => {
it("cancels an active out-of-turn wakeup and clears background work on interrupt", async () => {
const { connector, instances } = connectorHarness({
promptUpdates: () => [
{
sessionUpdate: "tool_call",
toolCallId: "cmd-1",
name: "run_command",
kind: "execute",
title: "sleep 30",
status: "in_progress",
},
{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Waiting." } },
],
promptUpdates: (text) =>
text === "Start"
? [
{
sessionUpdate: "tool_call",
toolCallId: "cmd-1",
name: "run_command",
kind: "execute",
title: "sleep 30",
status: "in_progress",
},
{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Waiting." } },
]
: [],
});
const registration = runAcpProvider({
id: "out-of-turn-cancel",
@@ -2753,7 +2756,24 @@ describe("ACP out-of-turn background activity", () => {
});
expect(await queryCanStop(connection, events, "stop-after-cancel")).toBe(true);
// A late tool_call_update echoing the canceled tool's failure must not open a phantom turn.
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "msg-2",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "Follow-up" }] },
},
});
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:msg-2" &&
event.state === "completed",
);
// The canceled tool's terminal echo can arrive after the next prompt finishes.
const turnCountAfterCancel = events.filter((event) => event.type === "session.turn").length;
agent.notify("session/update", {
sessionId: "connector-session",
@@ -2966,6 +2986,28 @@ describe("ACP out-of-turn background activity", () => {
event.state === "completed",
);
expect(await queryCanStop(connection, events, "stop-after-thought-only")).toBe(true);
agent.notify("session/update", {
sessionId: "connector-session",
update: {
sessionUpdate: "tool_call",
toolCallId: "cmd-2",
kind: "execute",
title: "Long command",
status: "in_progress",
},
});
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:autonomous:3" &&
event.state === "completed",
);
expect(events.findLast((event) => event.type === "session.background_work")).toMatchObject({
items: [{ id: "cmd-2", description: "Long command" }],
});
expect(await queryCanStop(connection, events, "stop-with-detached-command")).toBe(false);
} finally {
await connection.close();
}
@@ -3079,7 +3121,7 @@ describe("ACP out-of-turn background activity", () => {
}
});
it("preserves other background work without sending cancel when a follow-up prompt arrives mid-wakeup", async () => {
it("preserves earlier background work when a follow-up is rejected", async () => {
let cancelCount = 0;
const { connector, instances } = connectorHarness({
handleMessage: (_instance, message) => {
@@ -3088,6 +3130,13 @@ describe("ACP out-of-turn background activity", () => {
}
return false;
},
handleRequest: (instance, request) => {
const params = request.params as { prompt?: Array<{ text?: string }> };
if (request.method !== "session/prompt" || params.prompt?.[0]?.text !== "Second")
return false;
instance.reject(request, "Follow-up rejected");
return true;
},
promptUpdates: (text) =>
text === "First"
? [
@@ -3112,12 +3161,7 @@ describe("ACP out-of-turn background activity", () => {
content: { type: "text", text: "Waiting on both." },
},
]
: [
{
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Handled follow-up." },
},
],
: [],
});
const registration = runAcpProvider({
id: "out-of-turn-followup",
@@ -3186,9 +3230,7 @@ describe("ACP out-of-turn background activity", () => {
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:msg-2" &&
event.state === "completed",
event.type === "session.turn" && event.turnId === "acp:msg-2" && event.state === "failed",
);
expect(events).toContainEqual({
type: "session.turn",
@@ -3200,12 +3242,12 @@ describe("ACP out-of-turn background activity", () => {
expect(events.findLast((event) => event.type === "session.background_work")).toEqual({
type: "session.background_work",
sessionId: "session-1",
canInterruptSession: true,
items: [
{
id: "cmd-2",
kind: "shell",
description: "cmd-2",
canStop: false,
},
],
});
+14 -1
View File
@@ -1,5 +1,18 @@
import { describe, expect, it } from "vitest";
import { ProviderInputSchema, type ProviderInput } from "./provider.js";
import { ProviderEventSchema, ProviderInputSchema, type ProviderInput } from "./provider.js";
it("advertises session interruption for background work without granting an item Stop", () => {
const item = { id: "tool", kind: "shell", description: "Build" };
const inventory = {
type: "session.background_work",
sessionId: "session-1",
canInterruptSession: true,
};
expect(ProviderEventSchema.parse({ ...inventory, items: [{ ...item, canStop: true }] })).toEqual({
...inventory,
items: [item],
});
});
type ReviewMode = "uncommitted" | "base" | "all";
type Delivery = "auto" | "steer";
+6 -2
View File
@@ -510,7 +510,6 @@ export interface ProviderBackgroundWorkItem {
kind: string;
description: string | null;
command?: string;
canStop?: boolean;
}
export interface ProviderPermissionAction {
@@ -731,6 +730,8 @@ export type ProviderEvent =
sessionId: string;
turnId: string;
state: "started" | "completed" | "failed" | "canceled";
/** On an autonomous start, signals that a new prompt can take over without interrupting. */
acceptsFollowUp?: boolean;
error?: ProviderError;
}
| { type: "session.usage"; sessionId: string; turnId?: string; usage: ProviderUsage }
@@ -744,6 +745,8 @@ export type ProviderEvent =
sessionId: string;
/** Full replacement of the session's live background work, or null to clear. */
items: ProviderBackgroundWorkItem[] | null;
/** The session's interrupt operation also stops its background work. */
canInterruptSession?: boolean;
}
| { type: "timeline.item"; sessionId: string; item: ProviderTimelineItem; timestamp?: string };
@@ -1560,6 +1563,7 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
sessionId: idSchema,
turnId: idSchema,
state: z.enum(["started", "completed", "failed", "canceled"]),
acceptsFollowUp: z.boolean().optional(),
error: providerErrorSchema.optional(),
})
.strip(),
@@ -1610,11 +1614,11 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
kind: z.string().min(1),
description: z.string().nullable(),
command: z.string().optional(),
canStop: z.boolean().optional(),
})
.strip(),
)
.nullable(),
canInterruptSession: z.boolean().optional(),
})
.strip(),
z
+2
View File
@@ -907,6 +907,8 @@ export const AgentBackgroundWorkSummarySchema = z.object({
count: z.number().int().nonnegative(),
/** Defaults to the total count when omitted. */
runningCount: z.number().int().nonnegative().optional(),
/** The session interrupt command also stops its current background work. */
canInterruptSession: z.boolean().optional(),
});
export type AgentBackgroundWorkSummary = z.infer<typeof AgentBackgroundWorkSummarySchema>;
@@ -3317,7 +3317,8 @@ export class AgentManager {
},
"agent.manager.stream.request",
);
if (existingAgent.activeForegroundTurnId || this.runs.hasRun(agentId)) {
const acceptsFollowUp = this.runs.acceptsFollowUp(agentId);
if (existingAgent.activeForegroundTurnId || (this.runs.hasRun(agentId) && !acceptsFollowUp)) {
this.logger.trace(
{
agentId,
@@ -3336,6 +3337,8 @@ 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);
@@ -3717,7 +3720,7 @@ export class AgentManager {
return { status: "starting" as const, run: starting };
}
assertAdmission?.(agent);
if (!this.hasInFlightRun(agent.id)) {
if (!this.hasInFlightRun(agent.id) || this.runs.acceptsFollowUp(agent.id)) {
return {
status: "reserved" as const,
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
@@ -3924,8 +3927,21 @@ export class AgentManager {
}
}
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
return this.runForegroundMutation(agentId, () => {
async cancelAgentRun(
agentId: string,
options?: { includeBackgroundWork?: boolean },
): Promise<AgentRunCancellationResult> {
return this.runForegroundMutation(agentId, async () => {
if (options?.includeBackgroundWork) {
await this.drainSessionEvents(agentId);
if (!this.hasInFlightRun(agentId)) {
if (!this.backgroundWork.canInterruptSession(agentId)) return { status: "not_running" };
const { session } = this.requireSessionAgent(agentId);
const acknowledged = await this.interruptSession(session, agentId);
await this.drainSessionEvents(agentId);
return { status: acknowledged ? "settled" : "refused" };
}
}
this.requireSessionAgent(agentId).pendingReplacement = false;
return this.cancelAgentRunNow(agentId);
});
@@ -4825,7 +4841,7 @@ export class AgentManager {
const items =
event.items === null
? this.backgroundWork.clear(agent.id)
: this.backgroundWork.apply(agent.id, event.items);
: this.backgroundWork.apply(agent.id, event.items, undefined, event.canInterruptSession);
this.publishBackgroundWork(agent.id, items);
return;
}
@@ -5391,7 +5407,13 @@ export class AgentManager {
});
return undefined;
case "turn_started":
this.onStreamTurnStarted({ agent, eventTurnId, isForegroundEvent, flags });
this.onStreamTurnStarted({
agent,
eventTurnId,
isForegroundEvent,
flags,
acceptsFollowUp: event.acceptsFollowUp,
});
return undefined;
case "permission_requested":
this.onStreamPermissionRequested(agent, event);
@@ -5570,6 +5592,7 @@ export class AgentManager {
eventTurnId: string | undefined;
isForegroundEvent: boolean;
flags: StreamEventFlags;
acceptsFollowUp?: boolean;
}): void {
const { agent, eventTurnId, isForegroundEvent, flags } = params;
this.logger.trace(
@@ -5593,7 +5616,7 @@ export class AgentManager {
flags.shouldNotifyWaiters = false;
return;
}
this.runs.trackAutonomousRun(agent.id, eventTurnId ?? null);
this.runs.trackAutonomousRun(agent.id, eventTurnId ?? null, params.acceptsFollowUp);
if (eventTurnId) {
this.openActiveTurn(agent, eventTurnId, new Date());
}
@@ -31,6 +31,7 @@ export interface AutonomousAgentRun {
token: string;
kind: "autonomous";
turnId: string | null;
acceptsFollowUp: boolean;
started: true;
settled: boolean;
settledPromise: Promise<void>;
@@ -99,7 +100,16 @@ export class AgentRunState {
return run.start.status === "started" ? run.start.turnId : null;
}
trackAutonomousRun(agentId: string, turnId: string | null): TrackedAgentRun {
acceptsFollowUp(agentId: string): boolean {
const run = this.runs.get(agentId);
return run?.kind === "autonomous" && run.acceptsFollowUp;
}
trackAutonomousRun(
agentId: string,
turnId: string | null,
acceptsFollowUp = false,
): TrackedAgentRun {
const current = this.runs.get(agentId);
if (current) {
return current;
@@ -109,6 +119,7 @@ export class AgentRunState {
...createTrackedRunState(),
kind: "autonomous",
turnId,
acceptsFollowUp,
started: true,
};
this.runs.set(agentId, run);
@@ -420,7 +420,7 @@ export type AgentTimelineItem =
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
| { type: "turn_started"; provider: AgentProvider; turnId?: string }
| { type: "turn_started"; provider: AgentProvider; turnId?: string; acceptsFollowUp?: boolean }
| { type: "turn_completed"; provider: AgentProvider; usage?: AgentUsage; turnId?: string }
| { type: "usage_updated"; provider: AgentProvider; usage: AgentUsage; turnId?: string }
| {
@@ -488,6 +488,7 @@ export type AgentStreamEvent =
type: "background_work";
provider: AgentProvider;
items: import("./background-work/index.js").AgentBackgroundWorkInput[] | null;
canInterruptSession?: boolean;
};
export function getAgentStreamEventTurnId(event: AgentStreamEvent): string | undefined {
@@ -61,16 +61,20 @@ function encodeProviderItemId(id: string): string {
* Daemon services publish individual items that outlive provider sessions.
*/
export class AgentBackgroundWorkStore {
private readonly providerItems = new Map<string, AgentBackgroundWorkItem[]>();
private readonly providerWork = new Map<
string,
{ items: AgentBackgroundWorkItem[]; canInterruptSession: boolean }
>();
private readonly daemonItems = new Map<string, Map<string, DaemonBackgroundWork>>();
apply(
agentId: string,
inputs: readonly AgentBackgroundWorkInput[],
timestamp: string = new Date().toISOString(),
canInterruptSession = false,
): AgentBackgroundWorkItem[] | null {
const previous = this.providerItems.get(agentId);
const previousById = new Map(previous?.map((item) => [item.id, item]));
const previous = this.providerWork.get(agentId);
const previousById = new Map(previous?.items.map((item) => [item.id, item]));
const seen = new Set<string>();
const next: AgentBackgroundWorkItem[] = [];
for (const input of inputs) {
@@ -88,8 +92,9 @@ export class AgentBackgroundWorkStore {
startedAt: previousById.get(id)?.startedAt ?? timestamp,
});
}
if (previous && sameItems(previous, next)) return null;
this.providerItems.set(agentId, next);
if (previous?.canInterruptSession === canInterruptSession && sameItems(previous.items, next))
return null;
this.providerWork.set(agentId, { items: next, canInterruptSession });
return this.list(agentId);
}
@@ -130,7 +135,7 @@ export class AgentBackgroundWorkStore {
}
authorizeProviderStop(agentId: string, itemId: string, stopToken: string): string {
const item = this.providerItems.get(agentId)?.find(({ id }) => id === itemId);
const item = this.providerWork.get(agentId)?.items.find(({ id }) => id === itemId);
if (!item?.canStop || item.stopToken !== stopToken) {
throw new Error("Background work is no longer available to stop");
}
@@ -138,15 +143,20 @@ export class AgentBackgroundWorkStore {
}
list(agentId: string): AgentBackgroundWorkItem[] {
const items = [...(this.providerItems.get(agentId) ?? [])];
const items = [...(this.providerWork.get(agentId)?.items ?? [])];
for (const { item } of this.daemonItems.get(agentId)?.values() ?? []) {
items.push(item);
}
return items;
}
canInterruptSession(agentId: string): boolean {
const work = this.providerWork.get(agentId);
return work?.canInterruptSession === true && work.items.length > 0;
}
summary(agentId: string): AgentBackgroundWorkSummary | undefined {
const items = this.providerItems.get(agentId);
const items = this.providerWork.get(agentId)?.items;
const daemonItems = this.daemonItems.get(agentId);
if (!items && !daemonItems) return undefined;
@@ -155,11 +165,15 @@ export class AgentBackgroundWorkStore {
for (const work of daemonItems?.values() ?? []) {
if (work.countsAsRunning) runningCount++;
}
return runningCount === count ? { count } : { count, runningCount };
return {
count,
...(runningCount === count ? {} : { runningCount }),
...(this.canInterruptSession(agentId) ? { canInterruptSession: true } : {}),
};
}
clear(agentId: string): AgentBackgroundWorkItem[] | null {
if (!this.providerItems.delete(agentId)) return null;
if (!this.providerWork.delete(agentId)) return null;
return this.list(agentId);
}
}
@@ -13,7 +13,10 @@ export type LifecycleAgentSnapshot = Pick<ManagedAgent, "id" | "cwd" | "lifecycl
export interface LifecycleAgentManager {
getAgent(agentId: string): LifecycleAgentSnapshot | null;
hasInFlightRun(agentId: string): boolean;
cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult>;
cancelAgentRun(
agentId: string,
options?: { includeBackgroundWork?: boolean },
): Promise<AgentRunCancellationResult>;
clearAgentAttention(agentId: string): Promise<void>;
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
archiveSnapshot(agentId: string, archivedAt: string): Promise<StoredAgentRecord>;
@@ -58,6 +61,7 @@ interface RequestedAgentRunCancellation extends CancelAgentRunResult {
async function requestAgentRunCancellation(
dependencies: Pick<AgentLifecycleCommandDependencies, "agentManager" | "logger">,
agentId: string,
includeBackgroundWork = false,
): Promise<RequestedAgentRunCancellation> {
const { agentManager, logger } = dependencies;
const agent = agentManager.getAgent(agentId);
@@ -67,7 +71,7 @@ async function requestAgentRunCancellation(
}
const hasInFlightRun = agentManager.hasInFlightRun(agentId);
if (!hasInFlightRun) {
if (!hasInFlightRun && !includeBackgroundWork) {
logger.trace(
{ agentId, lifecycle: agent.lifecycle, hasInFlightRun },
"cancelAgentRunCommand: skipping because agent is not running",
@@ -80,7 +84,9 @@ async function requestAgentRunCancellation(
"cancelAgentRunCommand: interrupting",
);
const startedAt = Date.now();
const cancellation = await agentManager.cancelAgentRun(agentId);
const cancellation = includeBackgroundWork
? await agentManager.cancelAgentRun(agentId, { includeBackgroundWork: true })
: await agentManager.cancelAgentRun(agentId);
logger.debug(
{ agentId, cancellation: cancellation.status, durationMs: Date.now() - startedAt },
"cancelAgentRunCommand: cancelAgentRun completed",
@@ -97,7 +103,7 @@ export async function cancelAgentRunCommand(
dependencies: Pick<AgentLifecycleCommandDependencies, "agentManager" | "logger">,
agentId: string,
): Promise<CancelAgentRunResult> {
const result = await requestAgentRunCancellation(dependencies, agentId);
const result = await requestAgentRunCancellation(dependencies, agentId, true);
if (result.cancellation.status === "refused") {
dependencies.logger.warn(
{ agentId },
@@ -13,6 +13,10 @@ import type {
ProviderInput,
ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { runAcpProvider } from "@getpaseo/plugin/server/acp";
import { AgentSideConnection, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
import { sendPromptToAgent } from "./agent-prompt.js";
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";
@@ -2815,83 +2819,112 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
}
});
test("plugin background work and autonomous turns update AgentManager state", async () => {
const home = await mkdtemp(join(tmpdir(), "plugin-bg-work-"));
const logger = createTestLogger();
const storage = new AgentStorage(join(home, "agents"), logger);
let emitEvent: ((event: ProviderEvent) => void) | null = null;
let openSessionId = "";
const harness = createProviderHarness({
capabilities: [...CAPABILITIES, "session.can_stop_runtime"],
handleInput: async (input, emit) => {
emitEvent = emit;
if (input.type === "session.open") openSessionId = input.sessionId;
return false;
},
});
const registry = new PluginAgentClientRegistry(logger);
registry.replace([harness.registration]);
const manager = new AgentManager({ clients: registry.clients(), registry: storage, logger });
const agent = await manager.createAgent(
{ provider: harness.registration.id, cwd: home },
undefined,
{ workspaceId: undefined },
);
try {
expect(openSessionId).not.toBe("");
emitEvent!({
type: "session.background_work",
sessionId: openSessionId,
items: [
{
id: "cmd-1",
kind: "shell",
description: "Typecheck workspace",
command: "npm run typecheck",
canStop: false,
},
],
});
await expect.poll(() => manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 1 });
expect(manager.listAgentBackgroundWork(agent.id)).toMatchObject([
{
id: "cmd-1",
kind: "shell",
description: "Typecheck workspace",
command: "npm run typecheck",
test.each(["steer", "stop"] as const)(
"Antigravity ACP background work through the daemon's %s command",
async (action) => {
const home = await mkdtemp(join(tmpdir(), "plugin-bg-work-"));
const logger = createTestLogger();
const storage = new AgentStorage(join(home, "agents"), logger);
const calls: string[] = [];
let wake!: () => Promise<void>;
const registration = runAcpProvider({
id: "test-antigravity",
label: "Test Antigravity",
acpOptions: { outOfTurnActivity: true },
connector: () => {
const clientToAgent = new TransformStream();
const agentToClient = new TransformStream();
const acp = new AgentSideConnection(
() => ({
initialize: async () => ({ protocolVersion: PROTOCOL_VERSION, agentCapabilities: {} }),
newSession: async () => ({ sessionId: "native-session" }),
prompt: async ({ sessionId, prompt }) => {
const text = prompt[0]?.type === "text" ? prompt[0].text : "";
calls.push(text);
if (text === "Start two commands") {
for (const toolCallId of ["cmd-1", "cmd-2"]) {
await acp.sessionUpdate({
sessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: toolCallId,
kind: "execute",
status: "in_progress",
},
});
}
wake = () =>
acp.sessionUpdate({
sessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "cmd-1",
status: "completed",
},
});
}
return { stopReason: "end_turn" };
},
cancel: async () => {
calls.push("session/cancel");
},
}),
{ writable: agentToClient.writable, readable: clientToAgent.readable },
);
return { writable: clientToAgent.writable, readable: agentToClient.readable };
},
]);
});
const registry = new PluginAgentClientRegistry(logger);
registry.replace([registration]);
const manager = new AgentManager({ clients: registry.clients(), registry: storage, logger });
try {
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
workspaceId: undefined,
});
const send = async (prompt: string, activeTurnBehavior?: "steer") => {
const result = await sendPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
logger,
prompt,
activeTurnBehavior,
});
if (result.disposition !== "turn_started")
throw new Error(`Unexpected dispatch: ${result.disposition}`);
await result.started;
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("idle");
};
await send("Start two commands");
expect(manager.listAgentBackgroundWork(agent.id)).toMatchObject([
{ id: "cmd-1", kind: "shell" },
{ id: "cmd-2", kind: "shell" },
]);
emitEvent!({
type: "session.background_work",
sessionId: openSessionId,
items: [],
});
emitEvent!({
type: "session.turn",
sessionId: openSessionId,
turnId: "acp:autonomous:1",
state: "started",
});
emitEvent!({
type: "timeline.item",
sessionId: openSessionId,
item: { type: "assistant_message", id: "auto-msg-1", text: "All checks passed." },
});
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("running");
expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 0 });
emitEvent!({
type: "session.turn",
sessionId: openSessionId,
turnId: "acp:autonomous:1",
state: "completed",
});
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("idle");
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await registry.shutdown();
await storage.flush();
await rm(home, { recursive: true, force: true });
}
});
if (action === "steer") {
await wake();
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("running");
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) },
]);
} else {
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.listAgentBackgroundWork(agent.id)).toEqual([]);
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
}
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await registry.shutdown();
await storage.flush();
await rm(home, { recursive: true, force: true });
}
},
);
@@ -1650,7 +1650,8 @@ class PluginAgentSession implements AgentSession {
{
type: "background_work",
provider: this.provider,
items: event.items ? event.items.map((item) => ({ ...item })) : null,
items: event.items,
canInterruptSession: event.canInterruptSession,
},
];
case "session.runtime_failed":
@@ -1665,7 +1666,12 @@ class PluginAgentSession implements AgentSession {
private translateTurn(event: Extract<ProviderEvent, { type: "session.turn" }>): AgentStreamEvent {
if (event.state === "started") {
this.currentTurnId = event.turnId;
return { type: "turn_started", provider: this.provider, turnId: event.turnId };
return {
type: "turn_started",
provider: this.provider,
turnId: event.turnId,
...(event.acceptsFollowUp ? { acceptsFollowUp: true } : {}),
};
}
if (this.currentTurnId === event.turnId) this.currentTurnId = null;
if (event.state === "completed") {
+7
View File
@@ -331,6 +331,9 @@ turn or finish as a side effect with a `completed` prompt result.
Advertise only capabilities you implement. If steering is unsupported, omit `prompt.steer`; Paseo
can replace the active turn instead.
For a turn the session starts on its own, set `acceptsFollowUp: true` on the started
`session.turn` event if the next ordinary prompt can take over without an interrupt.
## Permit idle runtime cleanup
Paseo can release an idle resumable session after one hour when its daemon baseline allows cleanup.
@@ -369,6 +372,10 @@ queued completion reports, or pending autonomous replies. This query must not st
session. Return `false` while work remains. A rejected query, invalid response, or timeout also
keeps the runtime alive. Never respond with `request.completed` for this query.
Publish `session.background_work` to replace the live background-work list. Set
`canInterruptSession: true` when `session.interrupt` also stops that work. Paseo offers a
session-wide Stop action while the list contains work. Publish an empty list when the work stops.
Paseo always checks foreground work, permissions, queued deliveries, lifecycle operations,
working managed/native descendants, and outstanding local or remote finish subscriptions for the
caller. Subscription protection lasts through registration, recovery and notification dispatch