feat(agents): show and stop heartbeats alongside background tasks (#10097)

This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-18 17:10:21 +07:00
1 parent 59ca1f5f77
commit 62fc15d77a
24 files changed
+985 -168

No files matched your search

+13 -2
View File
@@ -705,7 +705,7 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
});
const schedules = agent.client as unknown as Pick<
DaemonClient,
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete"
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" | "scheduleList"
>;
let scheduleId: string | undefined;
try {
@@ -743,7 +743,18 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
await expect(summaries).toHaveCount(2);
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2);
await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" });
const tasks = page.getByRole("button", { name: "1 background task", exact: true });
await expect(page.getByTestId("workspace-status-indicator-running").first()).toBeVisible();
await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toHaveCount(0);
await tasks.click();
const panel = page.getByTestId("background-work-panel");
await expect(panel).toContainText("Heartbeat");
await panel.getByRole("button", { name: "Stop Check the completed work" }).click();
await expect(tasks).toHaveCount(0);
await expect(page.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
const remaining = await schedules.scheduleList();
expect(remaining.error).toBeNull();
expect(remaining.schedules.map((schedule) => schedule.id)).not.toContain(scheduleId);
} finally {
if (scheduleId) await schedules.scheduleDelete({ id: scheduleId });
await agent.cleanup();
+2 -2
View File
@@ -10,8 +10,8 @@ import { createHostBackgroundWorkModel } from "./host";
import { backgroundWorkText } from "./presentation";
export { createHostBackgroundWorkModel } from "./host";
function kindKey(kind: string): "shell" | "monitor" | "other" {
if (kind === "shell" || kind === "monitor") return kind;
function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" {
if (kind === "shell" || kind === "monitor" || kind === "heartbeat") return kind;
return "other";
}
+1
View File
@@ -394,6 +394,7 @@ export const ar: TranslationResources = {
otherPlaceholder: "آخر...",
},
backgroundWork: {
heartbeat: "نبضة دورية",
pillOne: "مهمة واحدة في الخلفية",
pillMany: "{{count}} مهمة في الخلفية",
notRunning: "لم يعد قيد التشغيل",
+1
View File
@@ -393,6 +393,7 @@ export const en = {
otherPlaceholder: "Other...",
},
backgroundWork: {
heartbeat: "Heartbeat",
pillOne: "1 background task",
pillMany: "{{count}} background tasks",
notRunning: "No longer running",
+1
View File
@@ -399,6 +399,7 @@ export const es: TranslationResources = {
otherPlaceholder: "Otro...",
},
backgroundWork: {
heartbeat: "Latido",
pillOne: "1 tarea en segundo plano",
pillMany: "{{count}} tareas en segundo plano",
notRunning: "Ya no está en ejecución",
+1
View File
@@ -399,6 +399,7 @@ export const fr: TranslationResources = {
otherPlaceholder: "Autre…",
},
backgroundWork: {
heartbeat: "Battement périodique",
pillOne: "1 tâche en arrière-plan",
pillMany: "{{count}} tâches en arrière-plan",
notRunning: "N’est plus en cours",
+1
View File
@@ -399,6 +399,7 @@ export const ja: TranslationResources = {
otherPlaceholder: "その他...",
},
backgroundWork: {
heartbeat: "ハートビート",
pillOne: "バックグラウンドタスク1件",
pillMany: "バックグラウンドタスク{{count}}件",
notRunning: "実行は終了しました",
+1
View File
@@ -395,6 +395,7 @@ export const ko: TranslationResources = {
otherPlaceholder: "기타...",
},
backgroundWork: {
heartbeat: "하트비트",
pillOne: "백그라운드 작업 1개",
pillMany: "백그라운드 작업 {{count}}개",
notRunning: "더 이상 실행 중이 아님",
+1
View File
@@ -398,6 +398,7 @@ export const ptBR: TranslationResources = {
otherPlaceholder: "Outro...",
},
backgroundWork: {
heartbeat: "Batimento",
pillOne: "1 tarefa em segundo plano",
pillMany: "{{count}} tarefas em segundo plano",
notRunning: "Não está mais em execução",
+1
View File
@@ -398,6 +398,7 @@ export const ru: TranslationResources = {
otherPlaceholder: "Другой ответ...",
},
backgroundWork: {
heartbeat: "Периодический сигнал",
pillOne: "1 фоновая задача",
pillMany: "Фоновые задачи: {{count}}",
notRunning: "Больше не выполняется",
+1
View File
@@ -394,6 +394,7 @@ export const zhCN: TranslationResources = {
otherPlaceholder: "其他...",
},
backgroundWork: {
heartbeat: "心跳",
pillOne: "1 个后台任务",
pillMany: "{{count}} 个后台任务",
notRunning: "已不再运行",
@@ -15223,6 +15223,115 @@ test("stops only a currently owned public background item with its current token
await manager.closeAgent(agent.id);
});
test("lists and stops heartbeat background work across provider session closure", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-background-heartbeat-"));
const stopped: string[] = [];
let activeSession: TestAgentSession | undefined;
class StoppableSession extends TestAgentSession {
async stopBackgroundWork(id: string) {
stopped.push(id);
}
}
class BackgroundWorkClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
activeSession = new StoppableSession(config);
return activeSession;
}
}
const manager = new AgentManager({
clients: { codex: new BackgroundWorkClient() },
registry: new AgentStorage(join(workdir, "agents"), logger),
logger,
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false });
const heartbeat = {
agentId: agent.id,
scheduleId: "schedule-1",
name: "Check build",
createdAt: "2026-10-06T10:00:00.000Z",
stop: async () => {
stopped.push("schedule-1");
manager.removeHeartbeatBackgroundWork(agent.id, "schedule-1");
},
};
try {
manager.setHeartbeatBackgroundWork(heartbeat);
const [item] = manager.listAgentBackgroundWork(agent.id);
expect(item).toMatchObject({
kind: "heartbeat",
description: "Check build",
startedAt: heartbeat.createdAt,
canStop: true,
stopToken: expect.any(String),
});
manager.setHeartbeatBackgroundWork({ ...heartbeat, name: "Check CI" });
const renamed = { ...item, description: "Check CI" };
activeSession?.pushEvent({
type: "background_work",
provider: "codex",
items: [{ id: item.id, kind: "shell", description: null, canStop: true }],
});
await vi.waitFor(() =>
expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 2 }),
);
const providerItem = manager
.listAgentBackgroundWork(agent.id)
.find((row) => row.kind === "shell")!;
expect(providerItem.id).not.toBe(item.id);
expect(events).toContainEqual({
type: "background_work",
agentId: agent.id,
items: expect.arrayContaining([providerItem, renamed]),
});
await manager.stopAgentBackgroundWork({
agentId: agent.id,
itemId: providerItem.id,
stopToken: providerItem.stopToken!,
});
expect(stopped).toEqual([item.id]);
const eventsBeforeClose = events.length;
await manager.closeAgent(agent.id);
expect(manager.getAgent(agent.id)).toBeNull();
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([renamed]);
expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 1 });
expect(events.slice(eventsBeforeClose)).toContainEqual({
type: "background_work",
agentId: agent.id,
items: [renamed],
});
const stop = { agentId: agent.id, itemId: item.id, stopToken: item.stopToken! };
await expect(manager.stopAgentBackgroundWork(stop)).rejects.toThrow();
await expect(
manager.stopAgentBackgroundWork({
...stop,
stopToken: providerItem.stopToken!,
canManageAutomation: true,
}),
).rejects.toThrow();
expect(stopped).toEqual([item.id]);
await manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true });
expect(stopped).toEqual([item.id, "schedule-1"]);
expect(manager.getAgentBackgroundWorkSummary(agent.id)).toBeUndefined();
expect(events.at(-1)).toEqual({ type: "background_work", agentId: agent.id, items: [] });
manager.setHeartbeatBackgroundWork(heartbeat);
await expect(
manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true }),
).rejects.toThrow();
expect(manager.listAgentBackgroundWork(agent.id)[0].stopToken).not.toBe(item.stopToken);
} finally {
if (manager.getAgent(agent.id)) await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
test("turns keep distinct identities across an idle runtime collection and resume", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-identity-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -113,7 +113,12 @@ import {
type ProviderSubagentDescriptor,
type ProviderSubagentStoreEvent,
} from "./provider-subagents/store.js";
import { AgentBackgroundWorkStore, type AgentBackgroundWorkItem } from "./background-work/index.js";
import {
AgentBackgroundWorkStore,
isHeartbeatBackgroundWorkItem,
type AgentBackgroundWorkItem,
type HeartbeatBackgroundWorkInput,
} from "./background-work/index.js";
import { withTimeout } from "../../utils/promise-timeout.js";
import { buildSessionConfig, extractAttention } from "../persistence-hooks.js";
@@ -191,6 +196,7 @@ interface StopAgentBackgroundWorkOptions {
agentId: string;
itemId: string;
stopToken: string;
canManageAutomation?: boolean;
}
async function resolveResumePurpose(
@@ -1430,37 +1436,56 @@ export class AgentManager {
}
listAgentBackgroundWork(agentId: string): AgentBackgroundWorkItem[] {
this.requirePublicAgent(agentId);
const agent = this.agents.get(agentId);
if (agent?.internal || (!agent && !this.backgroundWork.summary(agentId))) {
throw new Error(`Unknown agent '${agentId}'`);
}
return this.backgroundWork.list(agentId);
}
setHeartbeatBackgroundWork(input: HeartbeatBackgroundWorkInput): void {
this.publishBackgroundWork(input.agentId, this.backgroundWork.setHeartbeat(input));
}
removeHeartbeatBackgroundWork(agentId: string, scheduleId: string): void {
this.publishBackgroundWork(agentId, this.backgroundWork.removeHeartbeat(agentId, scheduleId));
}
async stopAgentBackgroundWork({
agentId,
itemId,
stopToken,
canManageAutomation,
}: StopAgentBackgroundWorkOptions): Promise<void> {
if (isHeartbeatBackgroundWorkItem({ id: itemId })) {
if (this.agents.get(agentId)?.internal) throw new Error(`Unknown agent '${agentId}'`);
if (!canManageAutomation)
throw new Error("Managing automation is required to stop a heartbeat");
await this.backgroundWork.stopHeartbeat(agentId, itemId, stopToken);
return;
}
this.requirePublicAgent(agentId);
// Inventory events share the session queue; drain events already received before
// authorizing the token, including a reconnect's ownership revocation.
await this.sessionEventTails.get(agentId)?.catch(() => undefined);
const agent = this.requirePublicAgent(agentId);
if (!agent.session || !agent.session.stopBackgroundWork)
throw new Error("Background work cannot be stopped");
const item = this.backgroundWork.list(agentId).find((entry) => entry.id === itemId);
if (!item?.canStop || item.stopToken !== stopToken)
throw new Error("Background work is no longer available to stop");
await agent.session.stopBackgroundWork(itemId);
const { session } = this.requirePublicAgent(agentId);
if (!session?.stopBackgroundWork) throw new Error("Background work cannot be stopped");
const providerItemId = this.backgroundWork.authorizeProviderStop(agentId, itemId, stopToken);
await session.stopBackgroundWork(providerItemId);
}
getAgentBackgroundWorkSummary(agentId: string): { count: number } | undefined {
return this.backgroundWork.summary(agentId);
}
private clearBackgroundWork(agentId: string): void {
const items = this.backgroundWork.clear(agentId);
private publishBackgroundWork(agentId: string, items: AgentBackgroundWorkItem[] | null): void {
if (items) this.dispatch({ type: "background_work", agentId, items });
}
private clearProviderBackgroundWork(agentId: string): void {
this.publishBackgroundWork(agentId, this.backgroundWork.clear(agentId));
}
listProviderSubagentActivity(): ProviderSubagentDescriptor[] {
const publicParentIds = new Set(
Array.from(this.agents.values())
@@ -1922,7 +1947,7 @@ export class AgentManager {
await this.closeReloadedSession(existing.session, agentId);
await this.drainSessionEvents(agentId);
this.cancelRunningProviderSubagents(agentId);
this.clearBackgroundWork(agentId);
this.clearProviderBackgroundWork(agentId);
closedExisting = this.prepareAgentForClosure(existing, "agent reloaded");
await this.persistSnapshot(closedExisting);
this.assertAcceptingAgentRegistrations();
@@ -2178,7 +2203,7 @@ export class AgentManager {
await this.drainSessionEvents(agentId);
this.cancelRunningProviderSubagents(agentId);
// close() drops the session's subscribers before the provider could report an empty list.
this.clearBackgroundWork(agentId);
this.clearProviderBackgroundWork(agentId);
const closedAgent = this.prepareAgentForClosure(agent, "agent closed");
let persistError: unknown;
@@ -4674,7 +4699,7 @@ export class AgentManager {
for (const event of this.providerSubagents.deleteParent(agentId)) {
this.dispatch({ type: "provider_subagent", event });
}
this.clearBackgroundWork(agentId);
this.clearProviderBackgroundWork(agentId);
}
private emitClosedAgent(agent: ManagedAgentClosed, options?: { persist?: boolean }): void {
@@ -4789,7 +4814,7 @@ export class AgentManager {
event.items === null
? this.backgroundWork.clear(agent.id)
: this.backgroundWork.apply(agent.id, event.items);
if (items) this.dispatch({ type: "background_work", agentId: agent.id, items });
this.publishBackgroundWork(agent.id, items);
return;
}
const turnId = getAgentStreamEventTurnId(event);
@@ -260,10 +260,18 @@ function buildStoredOptionControls(
};
}
function visibleStoredBackgroundWork(
record: StoredAgentRecord,
summary: AgentSnapshotPayload["backgroundWork"],
): AgentSnapshotPayload["backgroundWork"] {
return record.internal || record.archivedAt ? undefined : summary;
}
export function buildStoredAgentPayload(
record: StoredAgentRecord,
validProviders: Iterable<AgentProvider>,
effectiveOptionsFor: EffectiveOptionsResolver,
backgroundWork?: AgentSnapshotPayload["backgroundWork"],
): AgentSnapshotPayload {
const defaultCapabilities = {
supportsStreaming: false,
@@ -304,6 +312,7 @@ export function buildStoredAgentPayload(
updatedAt: updatedAt.toISOString(),
lastUserMessageAt: lastUserMessageAt ? lastUserMessageAt.toISOString() : null,
status: record.lastStatus,
backgroundWork: visibleStoredBackgroundWork(record, backgroundWork),
capabilities: defaultCapabilities,
currentModeId: record.lastModeId ?? null,
availableModes: [],
@@ -14,55 +14,137 @@ export interface AgentBackgroundWorkItem extends AgentBackgroundWorkInput {
stopToken?: string;
}
export interface HeartbeatBackgroundWorkInput {
agentId: string;
scheduleId: string;
name: string | null;
createdAt: string;
stop: () => Promise<void>;
}
interface HeartbeatBackgroundWork {
item: AgentBackgroundWorkItem;
stop: HeartbeatBackgroundWorkInput["stop"];
}
const HEARTBEAT_ID_PREFIX = "heartbeat:";
const PROVIDER_ID_ESCAPE = "provider:";
export function isHeartbeatBackgroundWorkItem(item: { id: string }): boolean {
return item.id.startsWith(HEARTBEAT_ID_PREFIX);
}
function encodeProviderItemId(id: string): string {
// Preserve existing wire IDs outside the reserved namespaces.
return id.startsWith(HEARTBEAT_ID_PREFIX) || id.startsWith(PROVIDER_ID_ESCAPE)
? PROVIDER_ID_ESCAPE + id
: id;
}
/**
* Live background work per agent. Providers report the whole list on every change, so `apply`
* replaces it. `startedAt` is stamped the first time an id is seen and kept while it stays listed.
* Nothing is persisted; providers determine when their live inventory is no longer available.
* Live inventory per agent. Providers replace their entire contribution with `apply`.
* The scheduler publishes heartbeats individually and retains ownership across provider closure.
*/
export class AgentBackgroundWorkStore {
private readonly items = new Map<string, AgentBackgroundWorkItem[]>();
private readonly providerItems = new Map<string, AgentBackgroundWorkItem[]>();
private readonly heartbeats = new Map<string, Map<string, HeartbeatBackgroundWork>>();
apply(
agentId: string,
inputs: readonly AgentBackgroundWorkInput[],
timestamp: string = new Date().toISOString(),
): AgentBackgroundWorkItem[] | null {
const known = this.items.has(agentId);
const previous = this.items.get(agentId) ?? [];
const previousById = new Map(previous.map((item) => [item.id, item]));
const previous = this.providerItems.get(agentId);
const previousById = new Map(previous?.map((item) => [item.id, item]));
const seen = new Set<string>();
const next: AgentBackgroundWorkItem[] = [];
for (const input of inputs) {
if (seen.has(input.id)) continue;
seen.add(input.id);
const id = encodeProviderItemId(input.id);
if (seen.has(id)) continue;
seen.add(id);
next.push({
id: input.id,
id,
kind: input.kind,
description: input.description,
...(input.command ? { command: input.command } : {}),
...(input.canStop
? { canStop: true, stopToken: previousById.get(input.id)?.stopToken ?? randomUUID() }
? { canStop: true, stopToken: previousById.get(id)?.stopToken ?? randomUUID() }
: {}),
startedAt: previousById.get(input.id)?.startedAt ?? timestamp,
startedAt: previousById.get(id)?.startedAt ?? timestamp,
});
}
if (known && sameItems(previous, next)) return null;
this.items.set(agentId, next);
return [...next];
if (previous && sameItems(previous, next)) return null;
this.providerItems.set(agentId, next);
return this.list(agentId);
}
setHeartbeat({
agentId,
scheduleId,
name,
createdAt,
stop,
}: HeartbeatBackgroundWorkInput): AgentBackgroundWorkItem[] | null {
const id = HEARTBEAT_ID_PREFIX + scheduleId;
const heartbeats = this.heartbeats.get(agentId) ?? new Map<string, HeartbeatBackgroundWork>();
const previous = heartbeats.get(id)?.item;
const item: AgentBackgroundWorkItem = {
id,
kind: "heartbeat",
description: name,
startedAt: createdAt,
canStop: true,
stopToken: previous?.stopToken ?? randomUUID(),
};
heartbeats.set(id, { item, stop });
this.heartbeats.set(agentId, heartbeats);
return previous?.description === name && previous.startedAt === createdAt
? null
: this.list(agentId);
}
removeHeartbeat(agentId: string, scheduleId: string): AgentBackgroundWorkItem[] | null {
const heartbeats = this.heartbeats.get(agentId);
if (!heartbeats?.delete(HEARTBEAT_ID_PREFIX + scheduleId)) return null;
if (heartbeats.size === 0) this.heartbeats.delete(agentId);
return this.list(agentId);
}
async stopHeartbeat(agentId: string, itemId: string, stopToken: string): Promise<void> {
const heartbeat = this.heartbeats.get(agentId)?.get(itemId);
if (!heartbeat || heartbeat.item.stopToken !== stopToken) {
throw new Error("Background work is no longer available to stop");
}
await heartbeat.stop();
}
authorizeProviderStop(agentId: string, itemId: string, stopToken: string): string {
const item = this.providerItems.get(agentId)?.find(({ id }) => id === itemId);
if (!item?.canStop || item.stopToken !== stopToken) {
throw new Error("Background work is no longer available to stop");
}
return itemId.startsWith(PROVIDER_ID_ESCAPE) ? itemId.slice(PROVIDER_ID_ESCAPE.length) : itemId;
}
list(agentId: string): AgentBackgroundWorkItem[] {
return [...(this.items.get(agentId) ?? [])];
const items = [...(this.providerItems.get(agentId) ?? [])];
for (const { item } of this.heartbeats.get(agentId)?.values() ?? []) {
items.push(item);
}
return items;
}
summary(agentId: string): { count: number } | undefined {
const items = this.items.get(agentId);
return items ? { count: items.length } : undefined;
const items = this.providerItems.get(agentId);
const heartbeats = this.heartbeats.get(agentId);
return items || heartbeats
? { count: (items?.length ?? 0) + (heartbeats?.size ?? 0) }
: undefined;
}
clear(agentId: string): AgentBackgroundWorkItem[] | null {
if (!this.items.delete(agentId)) return null;
return [];
if (!this.providerItems.delete(agentId)) return null;
return this.list(agentId);
}
}
@@ -6197,35 +6197,50 @@ describe("agent snapshot MCP serialization", () => {
expect(structured.agents[0]).not.toHaveProperty("pendingPermissions");
});
it("reports an idle agent's background work from get_agent_status and list_agents", async () => {
const { agentManager, agentStorage, spies } = createTestDeps();
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
spies.agentManager.getAgent.mockReturnValue(agent);
spies.agentManager.listAgents.mockReturnValue([agent]);
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
it.each(["loaded", "stored"])(
"reports background work for a %s agent from get_agent_status and list_agents",
async (source) => {
const { agentManager, agentStorage, spies } = createTestDeps();
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
if (source === "stored") {
const record = createStoredRecord({
id: agent.id,
cwd: agent.cwd,
archivedAt: null,
lastStatus: "idle",
updatedAt: new Date().toISOString(),
});
spies.agentStorage.get.mockResolvedValue(record);
spies.agentStorage.listActive.mockResolvedValue([record]);
} else {
spies.agentManager.getAgent.mockReturnValue(agent);
spies.agentManager.listAgents.mockReturnValue([agent]);
}
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
const status = await registeredTool(server, "get_agent_status").handler({
agentId: "agent-with-shell",
});
const list = await registeredTool(server, "list_agents").handler({});
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createClaudeOnlyManager(),
logger,
});
const status = await registeredTool(server, "get_agent_status").handler({
agentId: "agent-with-shell",
});
const list = await registeredTool(server, "list_agents").handler({});
expect(status.structuredContent).toEqual({
status: "idle",
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
});
expect(list.structuredContent).toEqual({
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
});
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
"agent-with-shell",
);
});
expect(status.structuredContent).toEqual({
status: "idle",
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
});
expect(list.structuredContent).toEqual({
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
});
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
"agent-with-shell",
);
},
);
it("returns archived agent snapshots from storage for get_agent_status", async () => {
const { agentManager, agentStorage, spies } = createTestDeps();
@@ -33,7 +33,7 @@ import {
toAgentPayload,
} from "../agent-projections.js";
import { summarizeAgentActivity } from "../activity-curator.js";
import type { AgentStorage } from "../agent-storage.js";
import type { AgentStorage, StoredAgentRecord } from "../agent-storage.js";
import { AgentNotFoundError, ensureAgentLoaded } from "../agent-loading.js";
import { isStoredAgentProviderAvailable } from "../../persistence-hooks.js";
import {
@@ -2106,6 +2106,15 @@ function createToolCatalog(
return backgroundWork ? { ...snapshot, backgroundWork } : snapshot;
}
function projectStoredAgent(record: StoredAgentRecord) {
return buildStoredAgentPayload(
record,
new Set(providerSnapshotManager.listRegisteredProviderIds()),
(provider, own) => agentManager.effectiveOptionsFor(provider, own),
agentManager.getAgentBackgroundWorkSummary(record.id),
);
}
registerTool(
"get_agent_status",
{
@@ -2138,11 +2147,7 @@ function createToolCatalog(
throw new PaseoToolInputError(`Agent ${agentId} not found`);
}
const structuredSnapshot = buildStoredAgentPayload(
record,
new Set(providerSnapshotManager.listRegisteredProviderIds()),
(provider, own) => agentManager.effectiveOptionsFor(provider, own),
);
const structuredSnapshot = projectStoredAgent(record);
return {
content: [],
structuredContent: ensureValidJson({
@@ -2192,12 +2197,7 @@ function createToolCatalog(
storage: agentStorage,
workspaces: options.workspaceRegistry,
projectLive: projectLiveAgent,
projectStored: (record) =>
buildStoredAgentPayload(
record,
new Set(providerSnapshotManager.listRegisteredProviderIds()),
(provider, own) => agentManager.effectiveOptionsFor(provider, own),
),
projectStored: projectStoredAgent,
isProviderVisible: () => true,
isStoredProviderAvailable: (record) =>
isStoredAgentProviderAvailable(
@@ -29,7 +29,7 @@ export class SessionAuthorization {
this.permissions = new Set(permissions);
}
allowsInbound(message: SessionInboundMessage): boolean {
allowsInbound(message: Pick<SessionInboundMessage, "type">): boolean {
return this.allows(requiredPermissionForInbound(message.type));
}
@@ -649,6 +649,157 @@ describe("ScheduleService", () => {
expect(resumed.nextRunAt).toBe("2026-01-01T00:04:00.000Z");
});
test("shows an active heartbeat and stops it through agent background work", async () => {
const logger = createTestLogger();
const manager = new AgentManager({
logger,
clients: createTestAgentClients(),
registry: agentStorage,
});
const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, {
workspaceId: undefined,
});
const service = createScheduleService({
paseoHome: tempDir,
logger,
agentManager: manager,
agentStorage,
providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY,
now: () => now,
});
const input = {
prompt: "Private heartbeat instruction",
cadence: { type: "every", everyMs: 60_000 },
target: { type: "agent", agentId: agent.id },
} as const;
const created = await service.create(input);
const items = manager.listAgentBackgroundWork(agent.id);
expect(items).toEqual([
expect.objectContaining({
kind: "heartbeat",
description: null,
canStop: true,
startedAt: created.createdAt,
}),
]);
expect(JSON.stringify(items)).not.toContain(created.prompt);
await service.update({ id: created.id, name: "Status check" });
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([
expect.objectContaining({ description: "Status check", startedAt: created.createdAt }),
]);
const replacement = await service.createOrReplace({ ...input, name: "Status check" });
expect(replacement.id).toBe(created.id);
expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1);
await service.pause(created.id);
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
await service.resume(created.id);
const [firstResume] = manager.listAgentBackgroundWork(agent.id);
const pausing = service.pause(created.id);
const resuming = service.resume(created.id);
const staleStop = expect(
manager.stopAgentBackgroundWork({
agentId: agent.id,
itemId: firstResume.id,
stopToken: firstResume.stopToken!,
canManageAutomation: true,
}),
).rejects.toThrow("Background work is no longer available to stop");
await Promise.all([pausing, resuming, staleStop]);
const [resumed] = manager.listAgentBackgroundWork(agent.id);
await manager.stopAgentBackgroundWork({
agentId: agent.id,
itemId: resumed.id,
stopToken: resumed.stopToken!,
canManageAutomation: true,
});
await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`);
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
const deleted = await service.createOrReplace({ ...input, name: "Another check" });
expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1);
await service.delete(deleted.id);
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
});
test("removes heartbeats when they expire or finish their last run", async () => {
const logger = createTestLogger();
const manager = new AgentManager({ logger, clients: createTestAgentClients() });
const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, {
workspaceId: undefined,
});
const service = createScheduleService({
paseoHome: tempDir,
logger,
agentManager: manager,
agentStorage,
providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY,
now: () => now,
runner: async () => ({ agentId: agent.id, output: "done" }),
});
const input = {
prompt: "Check",
cadence: { type: "every", everyMs: 60_000 },
target: { type: "agent", agentId: agent.id },
} as const;
const expiring = await service.create({
...input,
expiresAt: "2026-01-01T00:00:30.000Z",
runOnCreate: false,
});
const finite = await service.create({ ...input, maxRuns: 1 });
expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(2);
now = new Date("2026-01-01T00:00:30.000Z");
await service.tick();
expect(await service.inspect(expiring.id)).toMatchObject({ status: "completed", runs: [] });
expect(await service.inspect(finite.id)).toMatchObject({
status: "completed",
runs: [{ status: "succeeded" }],
});
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
});
test("lets an already launched heartbeat turn finish after Stop deletes its schedule", async () => {
const logger = createTestLogger();
const manager = new AgentManager({ logger, clients: createTestAgentClients() });
const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, {
workspaceId: undefined,
});
const runner = new OverlappingTickRunner();
const service = createScheduleService({
paseoHome: tempDir,
logger,
agentManager: manager,
agentStorage,
providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY,
now: () => now,
runner: (schedule) => runner.run(schedule),
});
const created = await service.create({
prompt: "block the first tick",
cadence: { type: "every", everyMs: 60_000 },
target: { type: "agent", agentId: agent.id },
});
const tick = service.tick();
await runner.firstRunStarted;
try {
const [item] = manager.listAgentBackgroundWork(agent.id);
await manager.stopAgentBackgroundWork({
agentId: agent.id,
itemId: item.id,
stopToken: item.stopToken!,
canManageAutomation: true,
});
} finally {
runner.unblockFirstRun();
await tick;
}
await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`);
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
});
test("completes schedules when max runs is reached", async () => {
const service = createScheduleService({
paseoHome: tempDir,
@@ -3093,12 +3244,19 @@ describe("ScheduleService", () => {
target: { type: "agent", agentId: liveAgentId },
});
await service1.pause(pausedLive.id);
const expired = await service1.create({
prompt: "Expired check",
cadence: { type: "every", everyMs: 60_000 },
expiresAt: "2026-01-01T00:01:00.000Z",
target: { type: "agent", agentId: liveAgentId },
});
now = new Date("2026-01-01T00:10:00.000Z");
const replacementManager = new AgentManager({ logger: createTestLogger() });
const service2 = createScheduleService({
paseoHome: tempDir,
logger: createTestLogger(),
agentManager: new AgentManager({ logger: createTestLogger() }),
agentManager: replacementManager,
agentStorage,
providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY,
now: () => now,
@@ -3112,6 +3270,12 @@ describe("ScheduleService", () => {
expect((await service2.inspect(archived.id)).status).toBe("completed");
expect((await service2.inspect(live.id)).status).toBe("active");
expect((await service2.inspect(newAgent.id)).status).toBe("active");
expect((await service2.inspect(expired.id)).status).toBe("completed");
expect(replacementManager.getAgentBackgroundWorkSummary(missingAgentId)).toBeUndefined();
expect(replacementManager.getAgentBackgroundWorkSummary(archivedAgentId)).toBeUndefined();
expect(replacementManager.listAgentBackgroundWork(liveAgentId)).toEqual([
expect.objectContaining({ id: `heartbeat:${live.id}`, startedAt: live.createdAt }),
]);
// Paused schedules are swept too when their agent is gone, but survive when it lives.
expect((await service2.inspect(pausedMissing.id)).status).toBe("completed");
expect((await service2.inspect(pausedLive.id)).status).toBe("paused");
+70 -12
View File
@@ -243,6 +243,8 @@ type ScheduleAgentManager = Pick<
| "runAgent"
| "waitForAgentEvent"
| "waitForAgentClose"
| "setHeartbeatBackgroundWork"
| "removeHeartbeatBackgroundWork"
>;
interface ScheduleWorkspaceCreateInput {
@@ -286,12 +288,18 @@ export class ScheduleService {
runId: string,
) => Promise<ScheduleExecutionResult>;
private readonly runningScheduleIds = new Set<string>();
private readonly heartbeatStops = new Map<string, () => Promise<void>>();
private recovering = false;
private tickTimer: ReturnType<typeof setInterval> | null = null;
constructor(options: ScheduleServiceOptions) {
this.logger = options.logger.child({ module: "schedule-service" });
this.store = new ScheduleStore(join(options.paseoHome, "schedules"), this.logger);
this.agentManager = options.agentManager;
this.store = new ScheduleStore(
join(options.paseoHome, "schedules"),
this.logger,
(schedule, change) => this.syncHeartbeat(schedule, change),
);
this.agentStorage = options.agentStorage;
this.createAgent = options.createAgent;
this.createDirectoryWorkspace = options.createDirectoryWorkspace;
@@ -302,11 +310,19 @@ export class ScheduleService {
}
async start(): Promise<void> {
await this.recoverInterruptedRuns();
await this.sweepOrphanedSchedules();
if (this.tickTimer) {
return;
}
this.recovering = true;
try {
await this.recoverInterruptedRuns();
await this.sweepOrphanedSchedules();
} finally {
this.recovering = false;
}
for (const schedule of await this.store.list()) {
this.syncHeartbeat(schedule, "write");
}
const timer = setInterval(() => {
void this.tick().catch((error) => {
this.logger.error({ err: error }, "Failed to process schedule tick");
@@ -505,6 +521,46 @@ export class ScheduleService {
await this.store.delete(id);
}
private syncHeartbeat(schedule: StoredSchedule, change: "write" | "delete"): void {
if (schedule.target.type !== "agent") {
return;
}
const { agentId } = schedule.target;
const { id, name, createdAt } = schedule;
if (change === "delete" || schedule.status !== "active") {
this.heartbeatStops.delete(id);
this.agentManager.removeHeartbeatBackgroundWork(agentId, id);
return;
}
if (this.recovering) {
return;
}
let stop = this.heartbeatStops.get(id);
if (!stop) {
const stopHeartbeat = () =>
this.store.delete(id, (current) => {
// A queued Stop can reach the store after a pause and resume replaced its row.
if (
current?.status !== "active" ||
current.target.type !== "agent" ||
current.target.agentId !== agentId ||
this.heartbeatStops.get(id) !== stopHeartbeat
) {
throw new ScheduleStateConflictError("Background work is no longer available to stop");
}
});
this.heartbeatStops.set(id, stopHeartbeat);
stop = stopHeartbeat;
}
this.agentManager.setHeartbeatBackgroundWork({
agentId,
scheduleId: id,
name,
createdAt,
stop,
});
}
async completeForAgent(agentId: string): Promise<number> {
const now = this.now();
const schedules = await this.store.list();
@@ -590,7 +646,7 @@ export class ScheduleService {
}
private async completeScheduleIfDue(scheduleId: string, now: Date): Promise<void> {
const updated = await this.store.update(scheduleId, (schedule) => {
await this.store.update(scheduleId, (schedule) => {
if (
schedule.status !== "active" ||
!schedule.nextRunAt ||
@@ -600,7 +656,6 @@ export class ScheduleService {
}
return completeSchedule(schedule, now);
});
requireSchedule(updated, scheduleId);
}
private async recoverInterruptedRuns(): Promise<void> {
@@ -646,12 +701,16 @@ export class ScheduleService {
error: "Daemon restarted before the scheduled run completed",
};
updated = { ...updated, runs };
if (shouldCompleteSchedule(updated, now)) {
updated = completeSchedule(updated, now);
}
dirty = true;
}
if (
(updated.status === "active" || runningIndex !== -1) &&
shouldCompleteSchedule(updated, now)
) {
return completeSchedule(updated, now);
}
if (
updated.status === "active" &&
updated.nextRunAt &&
@@ -778,7 +837,7 @@ export class ScheduleService {
now: Date,
): Promise<{ schedule: StoredSchedule; runId: string } | null> {
let claimed: { schedule: StoredSchedule; runId: string } | null = null;
const updatedSchedule = await this.store.update(scheduleId, (schedule) => {
await this.store.update(scheduleId, (schedule) => {
if (
schedule.status !== "active" ||
!schedule.nextRunAt ||
@@ -821,7 +880,6 @@ export class ScheduleService {
claimed = { schedule: updated, runId };
return updated;
});
requireSchedule(updatedSchedule, scheduleId);
return claimed;
}
@@ -847,7 +905,8 @@ export class ScheduleService {
targetGone: boolean;
manual: boolean;
}): Promise<void> {
const updatedSchedule = await this.store.update(params.scheduleId, (schedule) => {
// A Stop can delete the schedule while its already launched turn is still running.
await this.store.update(params.scheduleId, (schedule) => {
const now = this.now();
const completedRuns = schedule.runs.map((run) =>
run.id === params.runId
@@ -900,7 +959,6 @@ export class ScheduleService {
return updated;
});
requireSchedule(updatedSchedule, params.scheduleId);
}
private async recordRunWorkspace(params: {
+41 -17
View File
@@ -100,6 +100,17 @@ function parseStoredSchedule(
return StoredScheduleSchema.safeParse(json);
}
async function readScheduleFile(filePath: string): Promise<string | null> {
try {
return await readFile(filePath, "utf-8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return null;
}
throw error;
}
}
export class ScheduleStore {
private readonly scheduleMutations = new Map<string, Promise<unknown>>();
private readonly identityMutations = new Map<string, Promise<unknown>>();
@@ -108,6 +119,7 @@ export class ScheduleStore {
constructor(
private readonly dir: string,
private readonly logger: Logger,
private readonly onChange?: (schedule: StoredSchedule, change: "write" | "delete") => void,
) {}
private filePath(id: string): string {
@@ -128,12 +140,17 @@ export class ScheduleStore {
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
.map(async (entry) => {
const filePath = join(this.dir, entry.name);
return { filePath, parsed: parseStoredSchedule(await readFile(filePath, "utf-8")) };
const content = await readScheduleFile(filePath);
return content === null ? null : { filePath, parsed: parseStoredSchedule(content) };
}),
);
const schedules: StoredSchedule[] = [];
const invalidFiles = new Set<string>();
for (const { filePath, parsed } of files) {
for (const file of files) {
if (!file) {
continue;
}
const { filePath, parsed } = file;
if (parsed.success) {
schedules.push(parsed.data);
continue;
@@ -149,21 +166,16 @@ export class ScheduleStore {
async get(id: string): Promise<StoredSchedule | null> {
await this.ensureDir();
try {
const content = await readFile(this.filePath(id), "utf-8");
return StoredScheduleSchema.parse(JSON.parse(content));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return null;
}
throw error;
}
const content = await readScheduleFile(this.filePath(id));
return content === null ? null : StoredScheduleSchema.parse(JSON.parse(content));
}
async create(schedule: Omit<StoredSchedule, "id">): Promise<StoredSchedule> {
const created = StoredScheduleSchema.parse({ ...schedule, id: generateScheduleId() });
await this.write(created);
return created;
return this.serializeScheduleMutation(created.id, async () => {
await this.write(created);
return created;
});
}
async update(id: string, updater: ScheduleUpdater): Promise<StoredSchedule | null> {
@@ -204,8 +216,10 @@ export class ScheduleStore {
if (!matchesNameAndTarget(created, name, target)) {
throw new Error("Created schedule does not match requested identity");
}
await this.write(created);
return created;
return this.serializeScheduleMutation(created.id, async () => {
await this.write(created);
return created;
});
}
const updated = await this.updateMatchedSchedule(existing.id, name, target, options.update);
@@ -219,12 +233,22 @@ export class ScheduleStore {
private async write(schedule: StoredSchedule): Promise<void> {
await this.ensureDir();
await writeJsonFileAtomic(this.filePath(schedule.id), schedule);
this.onChange?.(schedule, "write");
}
async delete(id: string): Promise<void> {
async delete(
id: string,
assertDeletable?: (schedule: StoredSchedule | null) => void,
): Promise<void> {
await this.serializeScheduleMutation(id, async () => {
await this.ensureDir();
const content = await readScheduleFile(this.filePath(id));
const parsed = content === null ? null : parseStoredSchedule(content);
const schedule = parsed?.success ? parsed.data : null;
assertDeletable?.(schedule);
await rm(this.filePath(id), { force: true });
if (schedule) {
this.onChange?.(schedule, "delete");
}
});
}
+289 -24
View File
@@ -48,7 +48,10 @@ import type { StoredAgentRecord } from "./agent/agent-storage.js";
import type { AgentManagerEvent } from "./agent/agent-manager.js";
import type { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
import { WorkspaceLabelError, type WorkspaceLabelService } from "./workspace-labels/index.js";
import { createPersistedProjectRecord } from "./workspace-registry.js";
import {
createPersistedProjectRecord,
createPersistedWorkspaceRecord,
} from "./workspace-registry.js";
import { deriveProjectKey } from "./project-key.js";
import type { SessionOptions } from "./session.js";
import type { SessionInboundMessage, SessionOutboundMessage } from "./messages.js";
@@ -6142,6 +6145,7 @@ test("answers an agent background work list request", async () => {
const messages: SessionOutboundMessage[] = [];
const session = createSessionForTest({
messages,
permissions: ["workspace.read", "workspace.write"],
agentManager: {
waitForAgentClose: vi.fn().mockResolvedValue(undefined),
getAgent: vi.fn(() => ({ id: "agent-a" })),
@@ -6151,6 +6155,8 @@ test("answers an agent background work list request", async () => {
id: "bash-1",
kind: "shell",
description: "sleep 20",
canStop: true,
stopToken: "provider-token",
startedAt: "2026-10-06T10:00:00.000Z",
},
]),
@@ -6173,6 +6179,8 @@ test("answers an agent background work list request", async () => {
id: "bash-1",
kind: "shell",
description: "sleep 20",
canStop: true,
stopToken: "provider-token",
startedAt: "2026-10-06T10:00:00.000Z",
},
],
@@ -6181,6 +6189,228 @@ test("answers an agent background work list request", async () => {
});
});
const heartbeatBackgroundWork = {
id: "heartbeat:heartbeat-a",
kind: "heartbeat",
description: "Check progress",
startedAt: "2026-10-06T10:00:00.000Z",
canStop: true,
stopToken: "heartbeat-token",
};
test.each([
{ permissions: ["workspace.read"], canStop: false },
{ permissions: ["workspace.read", "automation.manage"], canStop: false },
{ permissions: ["workspace.read", "workspace.write"], canStop: false },
{ permissions: ["workspace.read", "hub.execute", "automation.manage"], canStop: true },
] satisfies Array<{ permissions: DaemonPermission[]; canStop: boolean }>)(
"filters dormant heartbeat controls for $permissions on list and update",
async ({ permissions, canStop }) => {
const messages: SessionOutboundMessage[] = [];
let listener: ((event: AgentManagerEvent) => void) | undefined;
const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" });
const session = createSessionForTest({
messages,
permissions,
agentManager: {
getAgent: () => undefined,
getAgentBackgroundWorkSummary: () => ({ count: 1 }),
listAgentBackgroundWork: () => [heartbeatBackgroundWork],
subscribe: (callback: (event: AgentManagerEvent) => void) => {
listener = callback;
return () => {};
},
},
agentStorage: { get: async () => record },
});
await session.handleMessage({
type: "session.events.set_subscription.request",
requestId: "subscribe-heartbeat",
events: ["agent.background_work.update"],
});
await session.handleMessage({
type: "agent.background_work.list.request",
requestId: "list-heartbeat",
agentId: record.id,
});
if (!listener) throw new Error("Agent event listener was not installed");
listener({
type: "background_work",
agentId: record.id,
items: [heartbeatBackgroundWork],
});
const { canStop: _canStop, stopToken: _token, ...readOnly } = heartbeatBackgroundWork;
const items = [canStop ? heartbeatBackgroundWork : readOnly];
expect(findByType(messages, "agent.background_work.list.response")?.payload).toEqual({
requestId: "list-heartbeat",
agentId: record.id,
items,
error: null,
});
await expect
.poll(() => findByType(messages, "agent.background_work.update")?.payload)
.toEqual({ agentId: record.id, items });
await session.cleanup();
},
);
test("publishes the current dormant inventory when an older update waits on storage", async () => {
const messages: SessionOutboundMessage[] = [];
const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" });
const pendingRecord = deferred<StoredAgentRecord>();
let firstRead = true;
let listener: ((event: AgentManagerEvent) => void) | undefined;
let items = [heartbeatBackgroundWork];
const session = createSessionForTest({
messages,
agentManager: {
getAgent: () => null,
getAgentBackgroundWorkSummary: () => (items.length ? { count: items.length } : undefined),
listAgentBackgroundWork: () => items,
subscribe: (callback: (event: AgentManagerEvent) => void) => {
listener = callback;
return () => {};
},
},
agentStorage: {
get: async () => {
if (!firstRead) return record;
firstRead = false;
return pendingRecord.promise;
},
},
});
await session.handleMessage({
type: "session.events.set_subscription.request",
requestId: "subscribe-delayed-inventory",
events: ["agent.background_work.update"],
});
if (!listener) throw new Error("Agent event listener was not installed");
listener({ type: "background_work", agentId: record.id, items });
items = [];
listener({ type: "background_work", agentId: record.id, items });
await expect
.poll(() => findByType(messages, "agent.background_work.update")?.payload.items)
.toEqual([]);
pendingRecord.resolve(record);
await new Promise<void>((resolve) => setImmediate(resolve));
const updates = messages.filter((message) => message.type === "agent.background_work.update");
expect(updates.every((message) => message.payload.items.length === 0)).toBe(true);
await session.cleanup();
});
test("passes the automation grant to the dormant background work stop operation", async () => {
const messages: SessionOutboundMessage[] = [];
const stops: Parameters<SessionOptions["agentManager"]["stopAgentBackgroundWork"]>[0][] = [];
const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" });
const session = createSessionForTest({
messages,
permissions: ["workspace.read", "automation.manage"],
agentManager: {
getAgent: () => undefined,
stopAgentBackgroundWork: async (
request: Parameters<SessionOptions["agentManager"]["stopAgentBackgroundWork"]>[0],
) => {
stops.push(request);
},
},
agentStorage: { get: async () => record },
});
const request = {
type: "agent.background_work.stop.request",
requestId: "stop-heartbeat",
agentId: record.id,
itemId: heartbeatBackgroundWork.id,
stopToken: heartbeatBackgroundWork.stopToken,
} as const;
await session.handleMessage({ ...request, requestId: "stop-heartbeat-read-only" });
expect(findByType(messages, "rpc_error")?.payload.code).toBe("access_denied");
session.setPermissions(["workspace.read", "workspace.write"]);
await session.handleMessage(request);
session.setPermissions(["workspace.read", "workspace.write", "automation.manage"]);
await session.handleMessage({ ...request, requestId: "stop-heartbeat-owner" });
const { agentId, itemId, stopToken } = request;
expect(stops).toEqual([
{ agentId, itemId, stopToken, canManageAutomation: false },
{ agentId, itemId, stopToken, canManageAutomation: true },
]);
expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBeNull();
await session.cleanup();
});
test("projects dormant heartbeat counts in directory snapshots and live updates", async () => {
const messages: SessionOutboundMessage[] = [];
let listener: ((event: AgentManagerEvent) => void) | undefined;
let count = 1;
const record = createStoredAgentRecord({
id: "agent-a",
workspaceId: "workspace-a",
cwd: "/tmp/repo",
});
const workspace = createPersistedWorkspaceRecord({
workspaceId: "workspace-a",
projectId: "project-a",
cwd: record.cwd,
kind: "directory",
displayName: "Workspace",
createdAt: record.createdAt,
updatedAt: record.updatedAt,
});
const project = createPersistedProjectRecord({
projectId: workspace.projectId,
rootPath: workspace.cwd,
kind: "non_git",
displayName: "Project",
createdAt: record.createdAt,
updatedAt: record.updatedAt,
});
const providers = createProviderSnapshotManagerStub();
providers.listRegisteredProviderIds.mockReturnValue([record.provider]);
const session = createSessionForTest({
messages,
providerSnapshotManager: providers.manager,
permissions: ["workspace.read"],
agentManager: {
getAgent: () => undefined,
getAgentBackgroundWorkSummary: () => (count ? { count } : undefined),
subscribe: (callback: (event: AgentManagerEvent) => void) => {
listener = callback;
return () => {};
},
},
agentStorage: { get: async () => record, listAll: async () => [record] },
workspaceRegistry: { get: vi.fn(async () => workspace) },
projectRegistry: { get: async () => project },
});
await session.handleMessage({
type: "fetch_agents_request",
requestId: "list-heartbeat-agents",
subscribe: { subscriptionId: "heartbeat-agents" },
});
expect(findByType(messages, "fetch_agents_response")?.payload.entries).toMatchObject([
{ agent: { id: record.id, backgroundWork: { count: 1 } } },
]);
if (!listener) throw new Error("Agent event listener was not installed");
count = 0;
listener({ type: "background_work", agentId: record.id, items: [] });
await expect
.poll(() => findByType(messages, "agent_update")?.payload)
.toMatchObject({
kind: "upsert",
agent: { id: record.id },
});
const update = findByType(messages, "agent_update")?.payload;
expect(update?.kind === "upsert" && update.agent.backgroundWork).toBeUndefined();
await session.cleanup();
});
test("reports an unavailable inventory for a stored agent without loading it", async () => {
const messages: SessionOutboundMessage[] = [];
const resumeAgentFromPersistence = vi.fn();
@@ -6244,8 +6474,9 @@ test.each([
record: createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo", internal: true }),
error: "Unknown agent 'agent-a'",
},
])("rejects a background work list request for $name that is not loaded", async (scenario) => {
])("rejects background work control and updates for $name that is not loaded", async (scenario) => {
const messages: SessionOutboundMessage[] = [];
let listener: ((event: AgentManagerEvent) => void) | undefined;
const session = createSessionForTest({
messages,
agentManager: {
@@ -6254,20 +6485,45 @@ test.each([
getRegisteredProviderIds: vi.fn(() => ["codex"]),
resumeAgentFromPersistence: vi.fn(),
createAgent: vi.fn(),
subscribe: (callback: (event: AgentManagerEvent) => void) => {
listener = callback;
return () => {};
},
},
agentStorage: { get: vi.fn().mockResolvedValue(scenario.record) },
});
await session.handleMessage({
type: "session.events.set_subscription.request",
requestId: "subscribe-background-work",
events: ["agent.background_work.update"],
});
await session.handleMessage({
type: "agent.background_work.list.request",
agentId: "agent-a",
requestId: "list-rejected",
});
await session.handleMessage({
type: "agent.background_work.stop.request",
requestId: "stop-rejected",
agentId: "agent-a",
itemId: heartbeatBackgroundWork.id,
stopToken: heartbeatBackgroundWork.stopToken,
});
if (!listener) throw new Error("Agent event listener was not installed");
listener({ type: "background_work", agentId: "agent-a", items: [heartbeatBackgroundWork] });
await new Promise<void>((resolve) => setImmediate(resolve));
expect(messages).toContainEqual({
type: "agent.background_work.list.response",
payload: { requestId: "list-rejected", agentId: "agent-a", items: [], error: scenario.error },
});
expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBe(
scenario.error,
);
expect(findByType(messages, "agent.background_work.update")).toBeUndefined();
await session.cleanup();
});
test("never pushes background work to an old app", async () => {
@@ -6284,6 +6540,7 @@ test("never pushes background work to an old app", async () => {
return () => {};
}),
},
agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) },
});
// provider_subagents makes subagent updates flow to this legacy socket, so the
// manager listener is installed for it.
@@ -6300,6 +6557,7 @@ test("never pushes background work to an old app", async () => {
],
});
await new Promise<void>((resolve) => setImmediate(resolve));
const pushed = [...messages, ...targetedMessages.map((entry) => entry.message)];
expect(pushed.some((message) => message.type === "agent.background_work.update")).toBe(false);
});
@@ -6307,19 +6565,6 @@ test("never pushes background work to an old app", async () => {
test("pushes background work only to clients that subscribed to it", async () => {
const messages: SessionOutboundMessage[] = [];
const agentEventListeners: Array<(event: AgentManagerEvent) => void> = [];
const session = createSessionForTest({
messages,
agentManager: {
getAgent: vi.fn(() => undefined),
subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => {
agentEventListeners.push(listener);
return () => {};
}),
},
});
const forward = (event: AgentManagerEvent) => {
for (const listener of agentEventListeners) listener(event);
};
const event: AgentManagerEvent = {
type: "background_work",
agentId: "agent-a",
@@ -6327,6 +6572,22 @@ test("pushes background work only to clients that subscribed to it", async () =>
{ id: "bash-1", kind: "shell", description: null, startedAt: "2026-10-06T10:00:00.000Z" },
],
};
const session = createSessionForTest({
messages,
agentManager: {
getAgent: vi.fn(() => undefined),
getAgentBackgroundWorkSummary: () => ({ count: event.items.length }),
listAgentBackgroundWork: () => event.items,
subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => {
agentEventListeners.push(listener);
return () => {};
}),
},
agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) },
});
const forward = () => {
for (const listener of agentEventListeners) listener(event);
};
// Subscribe to an unrelated event so the manager listener is installed, then prove
// a client that did not ask for background work never receives it.
@@ -6336,7 +6597,8 @@ test("pushes background work only to clients that subscribed to it", async () =>
events: ["agent.provider_subagents.update"],
});
if (agentEventListeners.length === 0) throw new Error("Agent event listener was not installed");
forward(event);
forward();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false);
await session.handleMessage({
@@ -6346,14 +6608,16 @@ test("pushes background work only to clients that subscribed to it", async () =>
});
messages.length = 0;
forward(event);
forward();
expect(messages).toContainEqual(
expect.objectContaining({
type: "agent.background_work.update",
payload: expect.objectContaining({ agentId: "agent-a", items: event.items }),
}),
);
await expect
.poll(() => messages)
.toContainEqual(
expect.objectContaining({
type: "agent.background_work.update",
payload: expect.objectContaining({ agentId: "agent-a", items: event.items }),
}),
);
});
test("does not publish internal agents' background work to subscribed clients", async () => {
@@ -6363,7 +6627,7 @@ test("does not publish internal agents' background work to subscribed clients",
messages,
agentManager: {
getAgent: () => ({ id: "internal-agent", internal: true }) as never,
subscribe: (callback) => {
subscribe: (callback: (event: AgentManagerEvent) => void) => {
listener = callback;
return () => {};
},
@@ -6383,5 +6647,6 @@ test("does not publish internal agents' background work to subscribed clients",
{ id: "work", kind: "shell", description: "private", startedAt: "2026-10-06T10:00:00.000Z" },
],
});
await new Promise<void>((resolve) => setImmediate(resolve));
expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false);
});
+62 -24
View File
@@ -23,7 +23,10 @@ import { isAbsolute } from "node:path";
import { CreationService, type CreatedAgent } from "./creation/index.js";
import type { CreationSnapshot, AgentCreateRequest } from "@getpaseo/protocol/messages";
import type { MessageReceipts } from "./message-receipts/index.js";
import type { AgentBackgroundWorkItem } from "./agent/background-work/index.js";
import {
isHeartbeatBackgroundWorkItem,
type AgentBackgroundWorkItem,
} from "./agent/background-work/index.js";
import equal from "fast-deep-equal";
import { WorkspaceSetupObservation } from "./workspace-setup-observation.js";
import { SessionDelivery, type OwnedSubscription } from "./session/owned-subscriptions/index.js";
@@ -2180,7 +2183,12 @@ export class Session {
}
if (event.type === "background_work") {
this.forwardBackgroundWork(event);
void this.forwardBackgroundWork(event.agentId).catch((error) =>
this.sessionLogger.error(
{ err: error, agentId: event.agentId },
"Failed to emit background work update",
),
);
return;
}
@@ -2263,16 +2271,34 @@ export class Session {
this.forwardProviderSubagentUpdate(event);
}
private forwardBackgroundWork(
event: Extract<AgentManagerEvent, { type: "background_work" }>,
): void {
const agent = this.agentManager.getAgent(event.agentId);
if (agent?.internal) return;
private async forwardBackgroundWork(agentId: string): Promise<void> {
const target = await this.resolveBackgroundWorkAgent(agentId);
if ("error" in target) return;
const { agent, record } = target;
// The inventory may have changed while resolving a dormant agent.
const items = this.agentManager.getAgentBackgroundWorkSummary(agentId)
? this.agentManager.listAgentBackgroundWork(agentId)
: [];
this.emit({
type: "agent.background_work.update",
payload: { agentId: event.agentId, items: event.items },
payload: { agentId, items: this.projectBackgroundWorkItems(items) },
});
if (agent) await this.agentUpdates.forwardLiveAgent(agent);
else if (record) await this.agentUpdates.forwardStoredAgent(record);
}
private projectBackgroundWorkItems(items: AgentBackgroundWorkItem[]): AgentBackgroundWorkItem[] {
if (
this.authorization.allowsPermission("automation.manage") &&
this.authorization.allowsInbound({ type: "agent.background_work.stop.request" })
) {
return items;
}
return items.map((item) => {
if (!isHeartbeatBackgroundWorkItem(item)) return item;
const { canStop: _canStop, stopToken: _stopToken, ...visible } = item;
return visible;
});
if (agent) void this.agentUpdates.forwardLiveAgent(agent);
}
private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void {
@@ -2307,10 +2333,12 @@ export class Session {
}
private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise<AgentSnapshotPayload> {
payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id);
const storedRecord = await this.agentStorage.get(payload.id);
payload.title = storedRecord?.title ?? null;
payload.archivedAt = storedRecord?.archivedAt ?? null;
if (!payload.internal && !storedRecord?.internal && !payload.archivedAt) {
payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id);
}
return payload;
}
@@ -2322,8 +2350,11 @@ export class Session {
record: StoredAgentRecord,
registeredProviderIds = new Set(this.providerSnapshotManager.listRegisteredProviderIds()),
): AgentSnapshotPayload {
return buildStoredAgentPayload(record, registeredProviderIds, (provider, own) =>
this.agentManager.effectiveOptionsFor(provider, own),
return buildStoredAgentPayload(
record,
registeredProviderIds,
(provider, own) => this.agentManager.effectiveOptionsFor(provider, own),
this.agentManager.getAgentBackgroundWorkSummary(record.id),
);
}
@@ -8685,10 +8716,13 @@ export class Session {
): Promise<void> {
let error: string | null = null;
try {
const target = await this.resolveBackgroundWorkAgent(msg.agentId);
if ("error" in target) throw new Error(target.error);
await this.agentManager.stopAgentBackgroundWork({
agentId: msg.agentId,
itemId: msg.itemId,
stopToken: msg.stopToken,
canManageAutomation: this.authorization.allowsPermission("automation.manage"),
});
} catch (cause) {
error = cause instanceof Error ? cause.message : String(cause);
@@ -8730,23 +8764,27 @@ export class Session {
}
}
// Background work lives only in memory, so an agent that is not loaded has none.
// Answering from storage keeps a read from resuming a dormant agent.
private async readAgentBackgroundWork(agentId: string): Promise<AgentBackgroundWorkItem[]> {
if (this.agentManager.getAgent(agentId)) {
if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) {
throw new Error("Background work inventory is unavailable");
}
return this.agentManager.listAgentBackgroundWork(agentId);
const target = await this.resolveBackgroundWorkAgent(agentId);
if ("error" in target) throw new Error(target.error);
if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) {
throw new Error("Background work inventory is unavailable");
}
return this.projectBackgroundWorkItems(this.agentManager.listAgentBackgroundWork(agentId));
}
private async resolveBackgroundWorkAgent(
agentId: string,
): Promise<{ agent: ManagedAgent | null; record: StoredAgentRecord | null } | { error: string }> {
const record = await this.agentStorage.get(agentId);
if (!record || record.internal) {
throw new Error(`Unknown agent '${agentId}'`);
const agent = this.agentManager.getAgent(agentId);
if ((!agent && !record) || agent?.internal || record?.internal) {
return { error: `Unknown agent '${agentId}'` };
}
if (record.archivedAt) {
throw new Error(`Agent is archived: ${agentId}`);
if (record?.archivedAt) {
return { error: `Agent is archived: ${agentId}` };
}
throw new Error("Background work inventory is unavailable");
return { agent, record };
}
private async handleProviderSubagentTimelineRequest(
@@ -44,6 +44,7 @@ export interface AgentUpdatesService {
hasSubscription(): boolean;
includesLiveAgent(agent: ManagedAgent, subscriptionIds?: ReadonlySet<string>): Promise<boolean>;
forwardLiveAgent(agent: ManagedAgent): Promise<void>;
forwardStoredAgent(record: StoredAgentRecord): Promise<void>;
emitStoredRecord(record: StoredAgentRecord): Promise<AgentSnapshotPayload>;
removeAgent(agentId: string): Promise<void>;
dispose(): void;
@@ -302,10 +303,13 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
return payload;
}
async function emitLiveAgentUpdate(payload: AgentSnapshotPayload): Promise<void> {
async function emitAgentUpdate(
workspaceId: string | undefined,
projectPayload?: () => AgentSnapshotPayload | Promise<AgentSnapshotPayload>,
): Promise<void> {
try {
if (hasSubscription()) await publishPayload(await deps.enrichAgentPayload(payload));
if (payload.workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(payload.workspaceId);
if (projectPayload && hasSubscription()) await publishPayload(await projectPayload());
if (workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId);
} catch (error) {
deps.logger.error({ err: error }, "Failed to emit agent update");
}
@@ -330,17 +334,20 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
if (!hasSubscription()) {
const workspaceId = agent.workspaceId;
return workspaceId
? enqueueAgentUpdate(agent.id, async () => {
try {
await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId);
} catch (error) {
deps.logger.error({ err: error }, "Failed to emit workspace update");
}
})
? enqueueAgentUpdate(agent.id, () => emitAgentUpdate(workspaceId))
: Promise.resolve();
}
const payload = toAgentPayload(agent);
return enqueueAgentUpdate(payload.id, () => emitLiveAgentUpdate(payload));
return enqueueAgentUpdate(payload.id, () =>
emitAgentUpdate(payload.workspaceId, () => deps.enrichAgentPayload(payload)),
);
}
function forwardStoredAgent(record: StoredAgentRecord): Promise<void> {
if (!hasSubscription() && !record.workspaceId) return Promise.resolve();
return enqueueAgentUpdate(record.id, () =>
emitAgentUpdate(record.workspaceId, () => deps.buildStoredAgentPayload(record)),
);
}
function removeAgent(agentId: string): Promise<void> {
@@ -362,6 +369,7 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
hasSubscription,
includesLiveAgent,
forwardLiveAgent,
forwardStoredAgent,
emitStoredRecord,
removeAgent,
dispose,