From 5bb8e4f77b5dc36917fd6358151dd99196dc280d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 30 Nov 2026 09:09:05 +0100 Subject: [PATCH] feat(protocol,server,client): add agent message queue RPCs and client sync Expose the daemon's durable per-agent message queue over the session protocol so clients can hydrate, observe live updates, withdraw, and promote queued messages without maintaining a local queue. - Keep queue updates opt-in via session.events.set_subscription and legacyWantsEvent=false so older clients never receive unknown frames. - Sequence per-agent queue broadcasts on the session so out-of-order storage reads cannot overwrite newer queue state, while still publishing empty lists when an archived or deleted agent's queue is cleared. - Ignore AbortError on withdrawn queued dispatch promises so user or lifecycle withdrawals do not log spurious run errors. Refs #8436, #9023 --- packages/client/src/daemon-client-core.ts | 90 ++++ packages/client/src/daemon-client.test.ts | 197 +++++++ packages/client/src/index.test.ts | 187 +++++++ packages/client/src/index.ts | 144 +++-- .../protocol/src/messages.agent-queue.test.ts | 210 ++++++++ packages/protocol/src/messages.ts | 120 +++++ .../protocol/src/messages.wire-compat.test.ts | 24 + .../tests/validation/evolvability.test.ts | 39 ++ .../tests/validation/ws-outbound.test.ts | 63 +++ .../finish-subscriptions.test.ts | 59 +++ .../src/server/authorization/index.test.ts | 23 + .../authorization/operation-permissions.ts | 7 + packages/server/src/server/session.test.ts | 498 ++++++++++++++++++ packages/server/src/server/session.ts | 235 ++++++++- .../websocket-server.relay-reconnect.test.ts | 1 + .../server/src/server/websocket-server.ts | 2 + 16 files changed, 1855 insertions(+), 44 deletions(-) create mode 100644 packages/protocol/src/messages.agent-queue.test.ts diff --git a/packages/client/src/daemon-client-core.ts b/packages/client/src/daemon-client-core.ts index 71e43a622c..aec0dad850 100644 --- a/packages/client/src/daemon-client-core.ts +++ b/packages/client/src/daemon-client-core.ts @@ -44,6 +44,7 @@ import type { RestartRequestedStatusPayloadSchema, ShutdownRequestedStatusPayloadSchema, DaemonUpdateResponseSchema, + ActiveTurnBehavior, AgentActiveTurnBehavior, ServerInfoStatusPayload, TerminalDefaultColors, @@ -510,6 +511,7 @@ export interface AgentMessageReceipt { deliveryStatus?: "queued"; activeTurnBehavior?: AgentActiveTurnBehavior; guidance?: string; + messageId?: string; } export interface SendMessageOptions { @@ -1139,6 +1141,20 @@ type CorrelatedResponsePayload = export type AgentBackgroundWorkListPayload = CorrelatedResponsePayload<"agent.background_work.list.response">; export type AgentBackgroundWorkItem = AgentBackgroundWorkListPayload["items"][number]; +export type AgentQueueListPayload = CorrelatedResponsePayload<"agent.queue.list.response">; +export type AgentQueueItem = AgentQueueListPayload["items"][number]; +export interface AgentQueueListResult { + held: boolean; + items: AgentQueueItem[]; +} +export type AgentQueueWithdrawPayload = CorrelatedResponsePayload<"agent.queue.withdraw.response">; +export type AgentQueueWithdrawResult = + | { withdrawn: true; item: AgentQueueItem } + | { withdrawn: false; reason: "not_found" | "already_dispatching" }; +export type AgentQueuePromotePayload = CorrelatedResponsePayload<"agent.queue.promote.response">; +export type AgentQueuePromoteResult = + | { promoted: true } + | { promoted: false; reason: "not_found" | "already_dispatching" }; type PluginCatalogResponseEntry = CorrelatedResponsePayload<"plugin.catalog.get.response">["plugins"][number]; @@ -4243,6 +4259,79 @@ export class DaemonClientCore { } } + async listAgentQueue( + agentId: string, + options: { requestId?: string; timeout?: number } = {}, + ): Promise { + this.assertAgentMessageQueueSupported(); + const payload = await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.list.response">({ + requestId: options.requestId, + timeout: options.timeout, + message: { type: "agent.queue.list.request", agentId }, + }); + if (payload.error) throw new Error(payload.error); + return { held: payload.held, items: payload.items }; + } + + async withdrawAgentQueueItem( + agentId: string, + messageId: string, + options: { requestId?: string; timeout?: number } = {}, + ): Promise { + this.assertAgentMessageQueueSupported(); + const payload = + await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.withdraw.response">({ + requestId: options.requestId, + timeout: options.timeout, + message: { type: "agent.queue.withdraw.request", agentId, messageId }, + }); + if (payload.error) throw new Error(payload.error); + if (payload.withdrawn) { + if (!payload.item) throw new Error("Missing withdrawn queue item."); + return { withdrawn: true, item: payload.item }; + } + if (!payload.reason) throw new Error("Missing queue withdraw failure reason."); + return { withdrawn: false, reason: payload.reason }; + } + + async promoteAgentQueueItem( + agentId: string, + messageId: string, + activeTurnBehavior: ActiveTurnBehavior, + options: { requestId?: string; timeout?: number } = {}, + ): Promise { + this.assertAgentMessageQueueSupported(); + const payload = + await this.sendNamespacedCorrelatedSessionRequest<"agent.queue.promote.response">({ + requestId: options.requestId, + timeout: options.timeout, + message: { + type: "agent.queue.promote.request", + agentId, + messageId, + activeTurnBehavior, + }, + }); + if (payload.error) throw new Error(payload.error); + if (payload.promoted) return { promoted: true }; + if (!payload.reason) throw new Error("Missing queue promote failure reason."); + return { promoted: false, reason: payload.reason }; + } + + observeAgentQueue( + options: { signal?: AbortSignal } = {}, + ): OwnedSubscription> { + this.assertAgentMessageQueueSupported(); + return this.observeEvents(["agent.queue.update"], options); + } + + private assertAgentMessageQueueSupported(): void { + // COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01. + if (this.lastServerInfoMessage?.features?.agentMessageQueue !== true) { + throw new Error("Update the host to view or manage an agent's message queue."); + } + } + async fetchProviderSubagentTimeline( parentAgentId: string, subagentId: string, @@ -4405,6 +4494,7 @@ export class DaemonClientCore { ...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}), ...(payload.activeTurnBehavior ? { activeTurnBehavior: payload.activeTurnBehavior } : {}), ...(payload.guidance ? { guidance: payload.guidance } : {}), + ...(payload.messageId ? { messageId: payload.messageId } : {}), }; } diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 6a202e3806..e2aff8ea7e 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -9661,6 +9661,7 @@ describe("agent sender active-turn behaviors", () => { deliveryStatus: "queued", activeTurnBehavior: "queue", guidance: "Queued, not delivered yet.", + messageId: "msg-queued-1", }); expect(request.activeTurnBehavior).toBe("queue"); expect("sourceAgentId" in request).toBe(false); @@ -9668,6 +9669,7 @@ describe("agent sender active-turn behaviors", () => { deliveryStatus: "queued", activeTurnBehavior: "queue", guidance: "Queued, not delivered yet.", + messageId: "msg-queued-1", }); }); @@ -11325,3 +11327,198 @@ describe("findWorkspace", () => { await expect(finding).resolves.toMatchObject({ id: targetId }); }); }); + +describe("agent queue RPCs and observation", () => { + const QUEUED_ITEM = { + id: "msg-1", + seq: 1, + enqueuedAt: "2026-11-30T08:00:00.000Z", + text: "Check tests", + sender: { kind: "user" as const }, + held: false, + state: "queued" as const, + }; + + async function connectQueueClient(features: Record) { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "queue-client", + transportFactory: () => transport.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + transport.triggerOpen({ features }); + await connecting; + return { client, transport }; + } + + test("gates queue methods when host lacks agentMessageQueue", async () => { + const { client, transport } = await connectQueueClient({ ownedSubscriptions: true }); + await expect(client.listAgentQueue("agent-a")).rejects.toThrow("Update the host"); + await expect(client.withdrawAgentQueueItem("agent-a", "msg-1")).rejects.toThrow( + "Update the host", + ); + await expect(client.promoteAgentQueueItem("agent-a", "msg-1", "steer")).rejects.toThrow( + "Update the host", + ); + expect(() => client.observeAgentQueue()).toThrow("Update the host"); + expect(transport.sent).toHaveLength(0); + }); + + test("lists, withdraws, promotes, and observes agent queue", async () => { + const { client, transport } = await connectQueueClient({ + ownedSubscriptions: true, + agentMessageQueue: true, + }); + + const listPromise = client.listAgentQueue("agent-a"); + const listReq = parseSentFrame(transport.sent.at(-1)); + expect(listReq).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" }); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.list.response", + payload: { + requestId: listReq.requestId, + agentId: "agent-a", + held: true, + items: [QUEUED_ITEM], + error: null, + }, + }), + ); + await expect(listPromise).resolves.toEqual({ held: true, items: [QUEUED_ITEM] }); + + const withdrawOk = client.withdrawAgentQueueItem("agent-a", "msg-1"); + const withdrawReq1 = parseSentFrame(transport.sent.at(-1)); + expect(withdrawReq1).toMatchObject({ + type: "agent.queue.withdraw.request", + agentId: "agent-a", + messageId: "msg-1", + }); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.withdraw.response", + payload: { + requestId: withdrawReq1.requestId, + agentId: "agent-a", + messageId: "msg-1", + withdrawn: true, + item: QUEUED_ITEM, + reason: null, + error: null, + }, + }), + ); + await expect(withdrawOk).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM }); + + const withdrawMiss = client.withdrawAgentQueueItem("agent-a", "msg-2"); + const withdrawReq2 = parseSentFrame(transport.sent.at(-1)); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.withdraw.response", + payload: { + requestId: withdrawReq2.requestId, + agentId: "agent-a", + messageId: "msg-2", + withdrawn: false, + item: null, + reason: "already_dispatching", + error: null, + }, + }), + ); + await expect(withdrawMiss).resolves.toEqual({ + withdrawn: false, + reason: "already_dispatching", + }); + + const promoteOk = client.promoteAgentQueueItem("agent-a", "msg-1", "interrupt"); + const promoteReq1 = parseSentFrame(transport.sent.at(-1)); + expect(promoteReq1).toMatchObject({ + type: "agent.queue.promote.request", + agentId: "agent-a", + messageId: "msg-1", + activeTurnBehavior: "interrupt", + }); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.promote.response", + payload: { + requestId: promoteReq1.requestId, + agentId: "agent-a", + messageId: "msg-1", + promoted: true, + reason: null, + error: null, + }, + }), + ); + await expect(promoteOk).resolves.toEqual({ promoted: true }); + + const promoteMiss = client.promoteAgentQueueItem("agent-a", "msg-9", "steer"); + const promoteReq2 = parseSentFrame(transport.sent.at(-1)); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.promote.response", + payload: { + requestId: promoteReq2.requestId, + agentId: "agent-a", + messageId: "msg-9", + promoted: false, + reason: "not_found", + error: null, + }, + }), + ); + await expect(promoteMiss).resolves.toEqual({ promoted: false, reason: "not_found" }); + + const updates: unknown[] = []; + const observation = client.observeAgentQueue(); + observation.subscribe({ + snapshot: () => {}, + update: (message) => updates.push(message), + error: () => {}, + }); + const subReq = parseSentFrame(transport.sent.at(-1)); + expect(subReq).toMatchObject({ + type: "session.events.set_subscription.request", + events: ["agent.queue.update"], + }); + transport.triggerMessage( + wrapSessionMessage({ + type: "session.events.set_subscription.response", + payload: { requestId: subReq.requestId, subscriptionId: "sub-q" }, + }), + ); + transport.triggerMessage( + wrapSessionMessage({ + type: "agent.queue.update", + payload: { + subscriptionId: "sub-q", + agentId: "agent-a", + held: false, + items: [QUEUED_ITEM], + }, + }), + ); + await vi.waitFor(() => expect(updates).toHaveLength(1)); + expect(updates[0]).toMatchObject({ + type: "agent.queue.update", + payload: { agentId: "agent-a", held: false, items: [QUEUED_ITEM] }, + }); + const releasing = observation.release(); + await vi.waitFor(() => + expect(parseSentFrame(transport.sent.at(-1)).type).toBe("subscription.release.request"), + ); + const releaseReq = parseSentFrame(transport.sent.at(-1)); + transport.triggerMessage( + wrapSessionMessage({ + type: "subscription.release.response", + payload: { requestId: releaseReq.requestId, subscriptionId: "sub-q" }, + }), + ); + await releasing; + }); +}); diff --git a/packages/client/src/index.test.ts b/packages/client/src/index.test.ts index 6a49405a4a..1d8d07eab0 100644 --- a/packages/client/src/index.test.ts +++ b/packages/client/src/index.test.ts @@ -2196,3 +2196,190 @@ test("background stop rejects when the host does not advertise the operation", a ).rejects.toThrow("Update the host"); await client.close(); }); + +const AGENT_QUEUE_FEATURES = { ownedSubscriptions: true, agentMessageQueue: true }; +const QUEUED_ITEM = { + id: "msg-1", + seq: 1, + enqueuedAt: "2026-11-30T08:00:00.000Z", + text: "Check logs", + sender: { kind: "user" as const }, + held: false, + state: "queued" as const, +}; + +function answerQueueList(ws: FakeWebSocket, held: boolean, items: unknown[]): void { + const request = parseSentSessionMessage(ws.sent.at(-1)); + expect(request).toMatchObject({ type: "agent.queue.list.request", agentId: "agent-a" }); + ws.message( + sessionMessage({ + type: "agent.queue.list.response", + payload: { requestId: request.requestId, agentId: "agent-a", held, items, error: null }, + }), + ); +} + +test("agent handles list, withdraw, and promote queue items", async () => { + const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES); + const queue = client.agents.ref("agent-a").queue; + + const listed = queue.list(); + answerQueueList(ws, true, [QUEUED_ITEM]); + await expect(listed).resolves.toEqual({ held: true, items: [QUEUED_ITEM] }); + + const withdrawn = queue.withdraw("msg-1"); + const withdrawReq = parseSentSessionMessage(ws.sent.at(-1)); + expect(withdrawReq).toMatchObject({ + type: "agent.queue.withdraw.request", + agentId: "agent-a", + messageId: "msg-1", + }); + ws.message( + sessionMessage({ + type: "agent.queue.withdraw.response", + payload: { + requestId: withdrawReq.requestId, + agentId: "agent-a", + messageId: "msg-1", + withdrawn: true, + item: QUEUED_ITEM, + reason: null, + error: null, + }, + }), + ); + await expect(withdrawn).resolves.toEqual({ withdrawn: true, item: QUEUED_ITEM }); + + const promoted = queue.promote("msg-1", "steer"); + const promoteReq = parseSentSessionMessage(ws.sent.at(-1)); + expect(promoteReq).toMatchObject({ + type: "agent.queue.promote.request", + agentId: "agent-a", + messageId: "msg-1", + activeTurnBehavior: "steer", + }); + ws.message( + sessionMessage({ + type: "agent.queue.promote.response", + payload: { + requestId: promoteReq.requestId, + agentId: "agent-a", + messageId: "msg-1", + promoted: false, + reason: "already_dispatching", + error: null, + }, + }), + ); + await expect(promoted).resolves.toEqual({ promoted: false, reason: "already_dispatching" }); + await client.close(); +}); + +test("agent queue subscriptions filter by agentId, re-list on reconnect, and keep overtaking updates", async () => { + const { client, ws } = await connectClient(AGENT_QUEUE_FEATURES); + const received: unknown[] = []; + + const unsubscribe = client.agents.ref("agent-a").queue.subscribe((state) => received.push(state)); + expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({ + type: "session.events.set_subscription.request", + events: ["agent.queue.update"], + }); + acknowledgeObservation(ws, "queue-sdk"); + await vi.waitFor(() => + expect(parseSentSessionMessage(ws.sent.at(-1))).toMatchObject({ + type: "agent.queue.list.request", + agentId: "agent-a", + }), + ); + const listReq = parseSentSessionMessage(ws.sent.at(-1)); + // An update overtakes the initial list response: the stale list is ignored. + ws.message( + sessionMessage({ + type: "agent.queue.update", + payload: { subscriptionId: "queue-sdk", agentId: "agent-a", held: true, items: [] }, + }), + ); + ws.message( + sessionMessage({ + type: "agent.queue.list.response", + payload: { + requestId: listReq.requestId, + agentId: "agent-a", + held: false, + items: [QUEUED_ITEM], + error: null, + }, + }), + ); + await vi.waitFor(() => expect(received).toEqual([{ held: true, items: [] }])); + + // Other agent updates are ignored. + ws.message( + sessionMessage({ + type: "agent.queue.update", + payload: { + subscriptionId: "queue-sdk", + agentId: "agent-b", + held: false, + items: [QUEUED_ITEM], + }, + }), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(received).toEqual([{ held: true, items: [] }]); + + // Reconnect re-subscribes and re-lists. + ws.readyState = 3; + ws.onclose?.({ code: 1006, reason: "Connection lost" }); + const reconnecting = client.connect(); + const next = FakeWebSocket.instances[1]; + next.open(); + next.message( + sessionMessage({ + type: "status", + payload: { + status: "server_info", + serverId: "srv_sdk_test", + hostname: null, + version: null, + features: AGENT_QUEUE_FEATURES, + }, + }), + ); + await reconnecting; + await vi.waitFor(() => + expect(parseSentSessionMessage(next.sent.at(-1))).toMatchObject({ + type: "session.events.set_subscription.request", + }), + ); + acknowledgeObservation(next, "queue-sdk-2"); + answerQueueList(next, false, [QUEUED_ITEM]); + + await vi.waitFor(() => + expect(received).toEqual([ + { held: true, items: [] }, + { held: false, items: [QUEUED_ITEM] }, + ]), + ); + + unsubscribe(); + next.message( + sessionMessage({ + type: "agent.queue.update", + payload: { subscriptionId: "queue-sdk-2", agentId: "agent-a", held: false, items: [] }, + }), + ); + expect(received).toHaveLength(2); + await client.close(); +}); + +test("agent queue asks for a host update when the daemon lacks agentMessageQueue", async () => { + const { client } = await connectClient({ ownedSubscriptions: true }); + const handle = client.agents.ref("agent-a"); + + await expect(handle.queue.list()).rejects.toThrow("Update the host"); + await expect(handle.queue.withdraw("msg-1")).rejects.toThrow("Update the host"); + await expect(handle.queue.promote("msg-1", "steer")).rejects.toThrow("Update the host"); + expect(() => handle.queue.subscribe(() => {})).toThrow("Update the host"); + await client.close(); +}); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index e1943ab56e..4388b498ee 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -11,6 +11,7 @@ export type { OwnedSubscription, SubscriptionObserver } from "./connection/index import type { DaemonClientConfig } from "./daemon-client.js"; import type { AgentPermissionResponse, JsonValue } from "@getpaseo/protocol/agent-types"; import type { + ActiveTurnBehavior, AgentSnapshotPayload, CreationSnapshot, CreateAgentRequestMessage, @@ -58,6 +59,10 @@ export type { import type { PluginTimelineItem } from "@getpaseo/protocol/agent-types"; import type { AgentBackgroundWorkItem, + AgentQueueItem, + AgentQueueListResult, + AgentQueuePromoteResult, + AgentQueueWithdrawResult, FetchAgentsEntry, FetchAgentsOptions, FetchAgentsPageInfo, @@ -414,6 +419,33 @@ export interface PaseoAgentBackgroundWorkSubscribeOptions { onError?: (error: unknown) => void; } +export type PaseoAgentQueueItem = AgentQueueItem; +export type PaseoAgentQueueState = AgentQueueListResult; +export type PaseoAgentQueueWithdrawResult = AgentQueueWithdrawResult; +export type PaseoAgentQueuePromoteResult = AgentQueuePromoteResult; + +export interface PaseoAgentQueueSubscribeOptions { + /** Receives the error when reading the agent's current queue fails. */ + onError?: (error: unknown) => void; +} + +export interface PaseoAgentQueueHandle { + list(options?: { requestId?: string; timeout?: number }): Promise; + withdraw( + messageId: string, + options?: { requestId?: string; timeout?: number }, + ): Promise; + promote( + messageId: string, + activeTurnBehavior: ActiveTurnBehavior, + options?: { requestId?: string; timeout?: number }, + ): Promise; + subscribe( + listener: (state: PaseoAgentQueueState) => void, + options?: PaseoAgentQueueSubscribeOptions, + ): () => void; +} + export interface PaseoAgentHandle { readonly id: string; readonly address: AgentAddress; @@ -445,6 +477,7 @@ export interface PaseoAgentHandle { readonly archivedAt: NonNullable | null; readonly timeline: PaseoAgentTimelineHandle; readonly backgroundWork: PaseoAgentBackgroundWorkHandle; + readonly queue: PaseoAgentQueueHandle; current(): PaseoAgent | null; refresh(requestId?: string): Promise; /** @@ -713,6 +746,7 @@ export function createPaseoApi( listenAgents, (agentId, handler) => own(() => daemonClient.subscribeAgentTimeline(agentId, handler)), () => own(() => daemonClient.observeAgentBackgroundWork()), + () => own(() => daemonClient.observeAgentQueue()), ); const createAgent = async ( options: PaseoAgentCreateOptions, @@ -1009,11 +1043,54 @@ function createWorkspaceHandleFactory( }; } +function subscribeAgentObservation( + createObservation: () => OwnedSubscription, + fetchSnapshot: () => Promise, + extractUpdate: (message: SessionOutboundMessage) => T | null, + listener: (value: T) => void, + options: { onError?: (error: unknown) => void; label: string }, +): () => void { + const observation = createObservation(); + // Bumped by every delivery so a list answered after a newer update is dropped. + let sequence = 0; + let released = false; + const reportError = (error: unknown) => { + if (released) return; + if (options.onError) options.onError(error); + else console.error(`${options.label} subscription failed`, error); + }; + observation.subscribe({ + error: reportError, + snapshot: () => { + const listed = ++sequence; + void fetchSnapshot() + .then((value) => { + if (!released && listed === sequence) listener(value); + return undefined; + }) + .catch(reportError); + }, + update: (message) => { + const value = extractUpdate(message); + if (value === null) return; + sequence++; + listener(value); + }, + }); + return () => { + released = true; + void observation + .release() + .catch((error) => console.error(`${options.label} subscription cleanup failed`, error)); + }; +} + function createAgentHandleFactory( daemonClient: DaemonClient, listen: (handler: PaseoAgentUpdateHandler) => () => void, subscribeTimeline: DaemonClient["subscribeAgentTimeline"], observeBackgroundWork: () => ReturnType, + observeAgentQueue: () => ReturnType, ): AgentHandleFactory { return (agent) => { const id = typeof agent === "string" ? agent : agent.id; @@ -1073,44 +1150,35 @@ function createAgentHandleFactory( backgroundWork: { stop: (item, options) => daemonClient.stopAgentBackgroundWork(id, item, options), list: (options) => daemonClient.listAgentBackgroundWork(id, options), - subscribe: (listener, options) => { - const observation = observeBackgroundWork(); - // Bumped by every delivery so a list answered after a newer update is dropped. - let sequence = 0; - let released = false; - const reportError = (error: unknown) => { - if (released) return; - if (options?.onError) options.onError(error); - else console.error("Background work subscription failed", error); - }; - observation.subscribe({ - error: reportError, - snapshot: () => { - const listed = ++sequence; - void daemonClient - .listAgentBackgroundWork(id) - .then((items) => { - if (!released && listed === sequence) listener(items); - return undefined; - }) - .catch(reportError); - }, - update: (message) => { - if (message.type !== "agent.background_work.update") return; - if (message.payload.agentId !== id) return; - sequence++; - listener(message.payload.items); - }, - }); - return () => { - released = true; - void observation - .release() - .catch((error) => - console.error("Background work subscription cleanup failed", error), - ); - }; - }, + subscribe: (listener, options) => + subscribeAgentObservation( + observeBackgroundWork, + () => daemonClient.listAgentBackgroundWork(id), + (message) => + message.type === "agent.background_work.update" && message.payload.agentId === id + ? message.payload.items + : null, + listener, + { onError: options?.onError, label: "Background work" }, + ), + }, + queue: { + list: (options) => daemonClient.listAgentQueue(id, options), + withdraw: (messageId, options) => + daemonClient.withdrawAgentQueueItem(id, messageId, options), + promote: (messageId, activeTurnBehavior, options) => + daemonClient.promoteAgentQueueItem(id, messageId, activeTurnBehavior, options), + subscribe: (listener, options) => + subscribeAgentObservation( + observeAgentQueue, + () => daemonClient.listAgentQueue(id), + (message) => + message.type === "agent.queue.update" && message.payload.agentId === id + ? { held: message.payload.held, items: message.payload.items } + : null, + listener, + { onError: options?.onError, label: "Agent queue" }, + ), }, get workspaceId() { return current?.workspaceId ?? null; diff --git a/packages/protocol/src/messages.agent-queue.test.ts b/packages/protocol/src/messages.agent-queue.test.ts new file mode 100644 index 0000000000..a88cc38fc2 --- /dev/null +++ b/packages/protocol/src/messages.agent-queue.test.ts @@ -0,0 +1,210 @@ +import { describe, expect, test } from "vitest"; + +import { + QueuedAgentMessagePayloadSchema, + QueuedMessageSenderSchema, + SendAgentMessageResponseMessageSchema, + ServerInfoStatusPayloadSchema, + SessionEventSubscriptionSchema, + SessionInboundMessageSchema, + SessionOutboundMessageSchema, +} from "./messages.js"; + +const USER_ITEM = { + id: "msg-1", + seq: 1, + enqueuedAt: "2026-11-30T08:00:00.000Z", + text: "Follow up on the build", + sender: { kind: "user" as const }, + held: false, + state: "queued" as const, +}; + +const AGENT_ITEM = { + id: "msg-2", + seq: 2, + enqueuedAt: "2026-11-30T08:00:01.000Z", + text: "Worker finished", + attachments: [ + { + type: "uploaded_file" as const, + id: "up-1", + fileName: "shot.png", + mimeType: "image/png", + size: 123, + path: "/tmp/uploads/up-1/shot.png", + role: "image" as const, + }, + ], + sender: { + kind: "agent_message" as const, + agentId: "agent-worker", + serverId: "server-1", + title: "Worker", + }, + held: true, + state: "dispatching" as const, +}; + +describe("agent message queue protocol", () => { + test("parses all queued message sender variants and payloads", () => { + for (const sender of [ + { kind: "user" }, + { kind: "agent_message", agentId: "agent-1", serverId: "srv-1", title: "Worker" }, + { kind: "agent_notification", agentId: "agent-2", event: "finished" }, + { kind: "change_request_update", url: "https://github.com/org/repo/pull/42" }, + ]) { + expect(QueuedMessageSenderSchema.parse(sender)).toEqual(sender); + } + + expect(QueuedAgentMessagePayloadSchema.parse(USER_ITEM)).toEqual(USER_ITEM); + expect(QueuedAgentMessagePayloadSchema.parse(AGENT_ITEM)).toEqual(AGENT_ITEM); + }); + + test("accepts queue list, withdraw, and promote requests and responses", () => { + expect( + SessionInboundMessageSchema.parse({ + type: "agent.queue.list.request", + agentId: "agent-1", + requestId: "req-list", + }), + ).toMatchObject({ agentId: "agent-1", requestId: "req-list" }); + + expect( + SessionOutboundMessageSchema.parse({ + type: "agent.queue.list.response", + payload: { + requestId: "req-list", + agentId: "agent-1", + held: false, + items: [USER_ITEM, AGENT_ITEM], + error: null, + }, + }), + ).toMatchObject({ payload: { held: false, items: [USER_ITEM, AGENT_ITEM] } }); + + expect( + SessionInboundMessageSchema.parse({ + type: "agent.queue.withdraw.request", + agentId: "agent-1", + messageId: "msg-1", + requestId: "req-withdraw", + }), + ).toMatchObject({ agentId: "agent-1", messageId: "msg-1", requestId: "req-withdraw" }); + + expect( + SessionOutboundMessageSchema.parse({ + type: "agent.queue.withdraw.response", + payload: { + requestId: "req-withdraw", + agentId: "agent-1", + messageId: "msg-1", + withdrawn: true, + item: USER_ITEM, + reason: null, + error: null, + }, + }), + ).toMatchObject({ payload: { withdrawn: true, item: USER_ITEM } }); + + for (const reason of ["not_found", "already_dispatching"] as const) { + expect( + SessionOutboundMessageSchema.parse({ + type: "agent.queue.withdraw.response", + payload: { + requestId: "req-withdraw", + agentId: "agent-1", + messageId: "msg-1", + withdrawn: false, + item: null, + reason, + error: null, + }, + }), + ).toMatchObject({ payload: { withdrawn: false, reason } }); + } + + expect( + SessionInboundMessageSchema.parse({ + type: "agent.queue.promote.request", + agentId: "agent-1", + messageId: "msg-1", + activeTurnBehavior: "steer", + requestId: "req-promote", + }), + ).toMatchObject({ activeTurnBehavior: "steer" }); + + expect( + SessionInboundMessageSchema.safeParse({ + type: "agent.queue.promote.request", + agentId: "agent-1", + messageId: "msg-1", + activeTurnBehavior: "queue", + requestId: "req-promote", + }).success, + ).toBe(false); + + expect( + SessionOutboundMessageSchema.parse({ + type: "agent.queue.promote.response", + payload: { + requestId: "req-promote", + agentId: "agent-1", + messageId: "msg-1", + promoted: true, + reason: null, + error: null, + }, + }), + ).toMatchObject({ payload: { promoted: true } }); + }); + + test("accepts queue updates with or without subscriptionId and registers subscription", () => { + for (const payload of [ + { agentId: "agent-1", held: false, items: [] }, + { subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [USER_ITEM] }, + ]) { + expect( + SessionOutboundMessageSchema.parse({ type: "agent.queue.update", payload }), + ).toMatchObject({ payload }); + } + + expect(SessionEventSubscriptionSchema.parse("agent.queue.update")).toBe("agent.queue.update"); + }); + + test("keeps send_agent_message_response.messageId and server_info.features.agentMessageQueue optional", () => { + expect( + SendAgentMessageResponseMessageSchema.parse({ + type: "send_agent_message_response", + payload: { + requestId: "req-1", + agentId: "agent-1", + accepted: true, + deliveryStatus: "queued", + messageId: "msg-1", + error: null, + }, + }).payload.messageId, + ).toBe("msg-1"); + + expect( + SendAgentMessageResponseMessageSchema.parse({ + type: "send_agent_message_response", + payload: { + requestId: "req-1", + agentId: "agent-1", + accepted: true, + error: null, + }, + }).payload.messageId, + ).toBeUndefined(); + + expect( + ServerInfoStatusPayloadSchema.parse({ + status: "server_info", + serverId: "server-1", + features: {}, + }).features?.agentMessageQueue, + ).toBeUndefined(); + }); +}); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index b816834b30..1ce086fca4 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -2214,6 +2214,27 @@ export const AgentBackgroundWorkStopRequestMessageSchema = z.object({ requestId: z.string(), }); +export const AgentQueueListRequestMessageSchema = z.object({ + type: z.literal("agent.queue.list.request"), + agentId: z.string(), + requestId: z.string(), +}); + +export const AgentQueueWithdrawRequestMessageSchema = z.object({ + type: z.literal("agent.queue.withdraw.request"), + agentId: z.string(), + messageId: z.string(), + requestId: z.string(), +}); + +export const AgentQueuePromoteRequestMessageSchema = z.object({ + type: z.literal("agent.queue.promote.request"), + agentId: z.string(), + messageId: z.string(), + activeTurnBehavior: ActiveTurnBehaviorSchema, + requestId: z.string(), +}); + export const ProviderSubagentTimelineRequestMessageSchema = z.object({ type: z.literal("agent.provider_subagents.timeline.get.request"), parentAgentId: z.string(), @@ -3637,6 +3658,7 @@ export const SessionEventSubscriptionSchema = z.enum([ "workspace_setup_progress", "agent.provider_subagents.update", "agent.background_work.update", + "agent.queue.update", "terminal_attention_required", "plugin.notification", "status.server_info", @@ -3810,6 +3832,9 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ ProviderSubagentListRequestMessageSchema, AgentBackgroundWorkListRequestMessageSchema, AgentBackgroundWorkStopRequestMessageSchema, + AgentQueueListRequestMessageSchema, + AgentQueueWithdrawRequestMessageSchema, + AgentQueuePromoteRequestMessageSchema, ProviderSubagentTimelineRequestMessageSchema, SetAgentTimelineSubscriptionRequestMessageSchema, AgentForkContextRequestMessageSchema, @@ -4343,6 +4368,8 @@ export const ServerInfoStatusPayloadSchema = z agentActiveTurnBehaviors: z.boolean().optional(), // COMPAT(nonAgentMessageQueue): added in v0.18.2, remove gate after 2027-06-01. nonAgentMessageQueue: z.boolean().optional(), + // COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01. + agentMessageQueue: z.boolean().optional(), // COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31. agentTurnIdentity: z.boolean().optional(), // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. @@ -5480,6 +5507,93 @@ export const AgentBackgroundWorkUpdateMessageSchema = z.object({ }), }); +export const QueuedMessageSenderSchema = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("user") }), + z.object({ + kind: z.literal("agent_message"), + agentId: z.string(), + serverId: z.string().optional(), + title: z.string().optional(), + }), + z.object({ + kind: z.literal("agent_notification"), + agentId: z.string(), + serverId: z.string().optional(), + title: z.string().optional(), + event: z.enum(["finished", "errored", "permission-required", "closed"]), + }), + z.object({ + kind: z.literal("change_request_update"), + url: z.string(), + }), +]); + +export type QueuedMessageSender = z.infer; + +export const QueuedAgentMessagePayloadSchema = z.object({ + id: z.string(), + seq: z.number().int().positive(), + enqueuedAt: z.string(), + text: z.string(), + attachments: z.array(AgentAttachmentSchema).optional(), + sender: QueuedMessageSenderSchema, + held: z.boolean(), + state: z.enum(["queued", "dispatching"]), +}); + +export type QueuedAgentMessagePayload = z.infer; + +export const AgentQueueMissReasonSchema = z.enum(["not_found", "already_dispatching"]); +export type AgentQueueMissReason = z.infer; + +export const AgentQueueListResponseMessageSchema = z.object({ + type: z.literal("agent.queue.list.response"), + payload: z.object({ + requestId: z.string(), + agentId: z.string(), + held: z.boolean(), + items: z.array(QueuedAgentMessagePayloadSchema), + error: z.string().nullable(), + }), +}); + +export const AgentQueueWithdrawResponseMessageSchema = z.object({ + type: z.literal("agent.queue.withdraw.response"), + payload: z.object({ + requestId: z.string(), + agentId: z.string(), + messageId: z.string(), + withdrawn: z.boolean(), + item: QueuedAgentMessagePayloadSchema.nullable().optional(), + reason: AgentQueueMissReasonSchema.nullable().optional(), + error: z.string().nullable(), + }), +}); + +export const AgentQueuePromoteResponseMessageSchema = z.object({ + type: z.literal("agent.queue.promote.response"), + payload: z.object({ + requestId: z.string(), + agentId: z.string(), + messageId: z.string(), + promoted: z.boolean(), + reason: AgentQueueMissReasonSchema.nullable().optional(), + error: z.string().nullable(), + }), +}); + +// Event push delivered through session.events.set_subscription; it has no .request/.response pair. +// Each update replaces the agent's whole queue list. +export const AgentQueueUpdateMessageSchema = z.object({ + type: z.literal("agent.queue.update"), + payload: z.object({ + subscriptionId: z.string().optional(), + agentId: z.string(), + held: z.boolean(), + items: z.array(QueuedAgentMessagePayloadSchema), + }), +}); + export const ProviderSubagentTimelineResponseMessageSchema = z.object({ type: z.literal("agent.provider_subagents.timeline.get.response"), payload: z.object({ @@ -5723,6 +5837,8 @@ export const SendAgentMessageResponseMessageSchema = z.object({ agentId: z.string(), accepted: z.boolean(), deliveryStatus: z.literal("queued").optional(), + /** The queued message ID when admitted to the daemon queue. */ + messageId: z.string().optional(), /** The behavior applied to a queued agent message. */ activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), /** What happens to a queued agent message, and how the sender can change it. */ @@ -8062,6 +8178,10 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ AgentBackgroundWorkListResponseMessageSchema, AgentBackgroundWorkStopResponseMessageSchema, AgentBackgroundWorkUpdateMessageSchema, + AgentQueueListResponseMessageSchema, + AgentQueueWithdrawResponseMessageSchema, + AgentQueuePromoteResponseMessageSchema, + AgentQueueUpdateMessageSchema, SetAgentTimelineSubscriptionResponseMessageSchema, AgentAttentionRequiredMessageSchema, AgentForkContextResponseMessageSchema, diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index 0c7c7c80ba..b5204904dd 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -857,4 +857,28 @@ describe("provider metrics", () => { }).success, ).toBe(false); }); + + test("send_agent_message_response accepts messageId while older apps ignore it", () => { + const withMessageId = { + type: "send_agent_message_response", + payload: { + requestId: "req-1", + agentId: "agent-1", + accepted: true, + deliveryStatus: "queued" as const, + messageId: "msg-1", + error: null, + }, + }; + expect(SessionOutboundMessageSchema.parse(withMessageId)).toEqual(withMessageId); + + const legacyPayload = z.object({ + requestId: z.string(), + agentId: z.string(), + accepted: z.boolean(), + deliveryStatus: z.literal("queued").optional(), + error: z.string().nullable(), + }); + expect(legacyPayload.parse(withMessageId.payload)).not.toHaveProperty("messageId"); + }); }); diff --git a/packages/protocol/tests/validation/evolvability.test.ts b/packages/protocol/tests/validation/evolvability.test.ts index 925c164066..c03123f4cb 100644 --- a/packages/protocol/tests/validation/evolvability.test.ts +++ b/packages/protocol/tests/validation/evolvability.test.ts @@ -198,6 +198,45 @@ describe("unknown list variants degrade to one skipped element", () => { }, }); }); + + it("skips a queued message item with an unknown sender variant and keeps the update", () => { + const knownItem = { + id: "msg-1", + seq: 1, + enqueuedAt: "2026-11-30T08:00:00.000Z", + text: "Check logs", + sender: { kind: "user" }, + held: false, + state: "queued", + }; + const futureItem = { + id: "msg-2", + seq: 2, + enqueuedAt: "2026-11-30T08:00:01.000Z", + text: "Future trigger", + sender: { kind: "future_trigger", source: "cron" }, + held: false, + state: "queued", + }; + const envelope = session({ + type: "agent.queue.update", + payload: { + agentId: "agent-1", + held: false, + items: [knownItem, futureItem], + }, + }); + + const generated = validateWSOutboundMessage(envelope); + const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope); + + expect(generated).toMatchObject({ + success: true, + data: { message: { payload: { agentId: "agent-1", held: false, items: [knownItem] } } }, + }); + expect(zod.success).toBe(true); + expect(zod.success && zod.data).toEqual(generated.success && generated.data); + }); }); describe("what still fails", () => { diff --git a/packages/protocol/tests/validation/ws-outbound.test.ts b/packages/protocol/tests/validation/ws-outbound.test.ts index c1c63054ab..eb63440c1c 100644 --- a/packages/protocol/tests/validation/ws-outbound.test.ts +++ b/packages/protocol/tests/validation/ws-outbound.test.ts @@ -472,3 +472,66 @@ it("accepts omitted RPC output so the receiving client can apply schema defaults const message = { type: "plugin.rpc.invoke.response", payload: { requestId: "default-output" } }; expect(PluginRpcInvokeResponseSchema.safeParse(message).success).toBe(true); }); + +it("validates agent.queue outbound responses and update events via zod-aot", () => { + const item = { + id: "msg-1", + seq: 1, + enqueuedAt: "2026-11-30T08:00:00.000Z", + text: "Queued prompt", + sender: { kind: "user" }, + held: false, + state: "queued", + }; + for (const message of [ + { + type: "agent.queue.list.response", + payload: { requestId: "req-1", agentId: "agent-1", held: false, items: [item], error: null }, + }, + { + type: "agent.queue.withdraw.response", + payload: { + requestId: "req-2", + agentId: "agent-1", + messageId: "msg-1", + withdrawn: true, + item, + reason: null, + error: null, + }, + }, + { + type: "agent.queue.promote.response", + payload: { + requestId: "req-3", + agentId: "agent-1", + messageId: "msg-1", + promoted: false, + reason: "already_dispatching", + error: null, + }, + }, + { + type: "agent.queue.update", + payload: { subscriptionId: "sub-1", agentId: "agent-1", held: true, items: [item] }, + }, + { + type: "send_agent_message_response", + payload: { + requestId: "req-4", + agentId: "agent-1", + accepted: true, + deliveryStatus: "queued", + messageId: "msg-1", + error: null, + }, + }, + ]) { + const envelope = { type: "session", message }; + expect(validateWSOutboundMessage(envelope)).toEqual({ + success: true, + data: envelope, + skipped: [], + }); + } +}); diff --git a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts index 2b56b5419d..f757bdd828 100644 --- a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts +++ b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts @@ -5,6 +5,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, test } from "vitest"; import { formatAgentMessage, parseAgentMessage } from "../agent-messages/envelope.js"; +import { + createAgentMessageDelivery, + createMemoryAgentMessageQueueStore, +} from "../agent-messages/index.js"; import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-client"; import { buildStoredAgentPayload } from "../agent-projections.js"; import { createTestLogger } from "../../../test-utils/test-logger.js"; @@ -830,3 +834,58 @@ test("withdrawing a queued message after a restart cancels its completion notice expect(second.service.hasPendingForCaller("parent")).toBe(false); expect(second.delivery.prompts).toEqual([]); }); + +test("daemon-level agentMessages.withdraw cancels a pending FinishSubscription via onWithdrawn", async () => { + const home = await mkdtemp(join(tmpdir(), "finish-withdraw-")); + homes.push(home); + const store = createJsonFinishSubscriptionStore(home); + const observation = new Observation(); + const agentMessages = createAgentMessageDelivery({ + store: createMemoryAgentMessageQueueStore(), + isRunning: () => true, + dispatch: async () => "turn_started", + onError: (error) => { + throw error; + }, + }); + const finishSubscriptions = createFinishSubscriptions({ + store, + messages: () => agentMessages, + callerIsActive: async () => true, + serverId: "server-1", + logger: createTestLogger(), + retryDelayMs: 1, + open: (record, signal) => observation.open(record, signal), + pendingWork: (record) => observation.pendingWork(record), + }); + services.push(finishSubscriptions); + const unsubscribeWithdrawn = agentMessages.onWithdrawn(({ id }) => + finishSubscriptions.withdraw(id), + ); + + try { + await finishSubscriptions.start(); + const messageId = "queued-child-msg"; + await finishSubscriptions.register({ ...intent, messageId }, true); + await agentMessages.enqueue({ + recipientId: intent.childAgentId, + messageId, + text: "Investigate failure", + source: { kind: "agent-message", agentId: intent.callerAgentId, title: "Parent" }, + activeTurnBehavior: "queue", + }); + + expect(await store.list()).toHaveLength(1); + expect(finishSubscriptions.hasPendingForCaller(intent.callerAgentId)).toBe(true); + + const withdrawn = await agentMessages.withdraw(intent.childAgentId, messageId); + expect(withdrawn.status).toBe("withdrawn"); + + await expect.poll(async () => (await store.list()).length).toBe(0); + expect(finishSubscriptions.hasPendingForCaller(intent.callerAgentId)).toBe(false); + expect(observation.waits).toEqual([]); + } finally { + unsubscribeWithdrawn(); + await agentMessages.close(); + } +}); diff --git a/packages/server/src/server/authorization/index.test.ts b/packages/server/src/server/authorization/index.test.ts index 5230e51261..5311bf0f9b 100644 --- a/packages/server/src/server/authorization/index.test.ts +++ b/packages/server/src/server/authorization/index.test.ts @@ -149,4 +149,27 @@ describe("SessionAuthorization", () => { expect(parseDaemonPermissions(["hub.execute", "hub.execute"])).toEqual(["hub.execute"]); expect(() => parseDaemonPermissions(["hub.execution.*"])).toThrow("Invalid daemon permission"); }); + + test("authorizes agent.queue operations with workspace.read, workspace.write, and hub.execute", () => { + const readOnly = new SessionAuthorization(["workspace.read"]); + expect(readOnly.allowsInbound(inboundMessage("agent.queue.list.request"))).toBe(true); + expect(readOnly.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(false); + expect(readOnly.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(false); + expect(readOnly.allowsOutbound(outboundMessage("agent.queue.list.response"))).toBe(true); + expect(readOnly.allowsOutbound(outboundMessage("agent.queue.update"))).toBe(true); + expect(readOnly.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(false); + expect(readOnly.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(false); + + const writer = new SessionAuthorization(["workspace.write"]); + expect(writer.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(true); + expect(writer.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(true); + expect(writer.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(true); + expect(writer.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(true); + + const hub = new SessionAuthorization(["hub.execute"]); + expect(hub.allowsInbound(inboundMessage("agent.queue.withdraw.request"))).toBe(true); + expect(hub.allowsInbound(inboundMessage("agent.queue.promote.request"))).toBe(true); + expect(hub.allowsOutbound(outboundMessage("agent.queue.withdraw.response"))).toBe(true); + expect(hub.allowsOutbound(outboundMessage("agent.queue.promote.response"))).toBe(true); + }); }); diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index b10b70f553..3535f59c25 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -26,6 +26,9 @@ const INBOUND_PERMISSION = { "agent.provider_subagents.list.request": "workspace.read", "agent.background_work.list.request": "workspace.read", "agent.background_work.stop.request": ["workspace.write", "hub.execute"], + "agent.queue.list.request": "workspace.read", + "agent.queue.withdraw.request": ["workspace.write", "hub.execute"], + "agent.queue.promote.request": ["workspace.write", "hub.execute"], "agent.provider_subagents.timeline.get.request": "workspace.read", "agent.provider.switch.request": "workspace.write", "agent.rewind.request": "workspace.write", @@ -283,6 +286,10 @@ const OUTBOUND_PERMISSION = { "agent.background_work.stop.response": ["workspace.write", "hub.execute"], "agent.background_work.update": "workspace.read", "agent.provider.switch.response": "workspace.write", + "agent.queue.list.response": "workspace.read", + "agent.queue.withdraw.response": ["workspace.write", "hub.execute"], + "agent.queue.promote.response": ["workspace.write", "hub.execute"], + "agent.queue.update": "workspace.read", "agent.rewind.response": "workspace.write", "agent.skills.get_status.response": "daemon.read", "agent.skills.import_legacy_selection.response": "daemon.manage", diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 0c67698d27..1f0d7faec3 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -6919,6 +6919,7 @@ describe("non-agent activeTurnBehavior queue in Session", () => { accepted: true, deliveryStatus: "queued", activeTurnBehavior: "queue", + messageId: "msg-d4", error: null, }, }); @@ -6967,3 +6968,500 @@ describe("non-agent activeTurnBehavior queue in Session", () => { } }); }); + +describe("agent.queue RPCs and live updates in Session", () => { + test("lists queued items with mapped senders and attachments, and rejects unknown or archived agents", async () => { + const receiptDir = mkdtempSync(join(tmpdir(), "paseo-queue-list-")); + const listeners = new Set<(id: string) => void>(); + const agentMessages = createAgentMessageDelivery({ + store: createMemoryAgentMessageQueueStore(), + paseoHome: receiptDir, + isRunning: () => true, + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + dispatch: async () => "turn_started", + onError: (error) => { + throw error; + }, + }); + const messages: SessionOutboundMessage[] = []; + const session = createSessionForTest({ + messages, + agentMessages, + messageReceipts: new MessageReceipts(receiptDir), + paseoHome: receiptDir, + agentManager: { + getAgent: (id: string) => { + if (id === "agent-1") { + return { id: "agent-1", status: "running", config: { title: "Recipient" } } as never; + } + if (id === "internal-1") { + return { id: "internal-1", internal: true, status: "running", config: {} } as never; + } + return undefined; + }, + }, + agentStorage: { + get: async (id: string) => { + if (id === "agent-1") return { id: "agent-1", title: "Recipient" } as never; + if (id === "archived-1") { + return { id: "archived-1", archivedAt: "2026-11-30T00:00:00.000Z" } as never; + } + if (id === "internal-1") return { id: "internal-1", internal: true } as never; + return null; + }, + }, + }); + + try { + const attachment = { + type: "text" as const, + fileName: "notes.txt", + mimeType: "text/plain", + content: "hello", + }; + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-user", + text: "Human follow-up", + attachments: [attachment], + activeTurnBehavior: "queue", + }); + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-agent", + text: "Worker reply", + source: { kind: "agent-message", agentId: "worker-1", serverId: "srv-2", title: "Worker" }, + activeTurnBehavior: "queue", + }); + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-notify", + text: "Finished", + source: { + kind: "agent-notification", + agentId: "worker-2", + title: "Helper", + event: "finished", + }, + activeTurnBehavior: "queue", + }); + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-cr", + text: "CI failed", + source: { kind: "change-request-update", url: "https://github.com/org/repo/pull/7" }, + activeTurnBehavior: "queue", + }); + + await session.handleMessage({ + type: "agent.queue.list.request", + requestId: "req-list", + agentId: "agent-1", + }); + + const listResponse = findByType(messages, "agent.queue.list.response"); + expect(listResponse?.payload).toMatchObject({ + requestId: "req-list", + agentId: "agent-1", + held: false, + error: null, + items: [ + { + id: "m-user", + seq: 1, + text: "Human follow-up", + attachments: [attachment], + sender: { kind: "user" }, + held: false, + state: "queued", + }, + { + id: "m-agent", + seq: 2, + text: "Worker reply", + sender: { + kind: "agent_message", + agentId: "worker-1", + serverId: "srv-2", + title: "Worker", + }, + held: false, + state: "queued", + }, + { + id: "m-notify", + seq: 3, + text: "Finished", + sender: { + kind: "agent_notification", + agentId: "worker-2", + title: "Helper", + event: "finished", + }, + held: false, + state: "queued", + }, + { + id: "m-cr", + seq: 4, + text: "CI failed", + sender: { + kind: "change_request_update", + url: "https://github.com/org/repo/pull/7", + }, + held: false, + state: "queued", + }, + ], + }); + expect("attachments" in listResponse!.payload.items[1]!).toBe(false); + + for (const [index, badId] of ["missing-1", "internal-1", "archived-1"].entries()) { + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.list.request", + requestId: `bad-${index}`, + agentId: badId, + }); + expect(findByType(messages, "agent.queue.list.response")?.payload).toMatchObject({ + requestId: `bad-${index}`, + agentId: badId, + held: false, + items: [], + error: expect.any(String), + }); + } + } finally { + await session.cleanup(); + await agentMessages.close(); + rmSync(receiptDir, { recursive: true, force: true }); + } + }); + + test("withdraws queued messages cleanly, distinguishes not_found and already_dispatching, and suppresses AbortError logs", async () => { + const receiptDir = mkdtempSync(join(tmpdir(), "paseo-queue-withdraw-")); + let running = true; + const inFlight = deferred<"turn_started">(); + const agentMessages = createAgentMessageDelivery({ + store: createMemoryAgentMessageQueueStore(), + paseoHome: receiptDir, + isRunning: () => running, + canSteer: () => true, + dispatch: () => inFlight.promise, + onError: (error) => { + throw error; + }, + }); + const messages: SessionOutboundMessage[] = []; + const session = createSessionForTest({ + messages, + agentMessages, + messageReceipts: new MessageReceipts(receiptDir), + paseoHome: receiptDir, + agentManager: { + waitForAgentClose: async () => undefined, + setTitle: async () => {}, + getAgent: (id: string) => + id === "agent-1" + ? ({ id: "agent-1", status: "running", config: { title: "Agent 1" } } as never) + : undefined, + }, + agentStorage: { + get: async (id: string) => (id === "agent-1" ? ({ id: "agent-1" } as never) : null), + }, + }); + + try { + await session.handleMessage({ + type: "send_agent_message_request", + requestId: "send-1", + agentId: "agent-1", + text: "Withdraw me", + activeTurnBehavior: "queue", + }); + const sendResponse = findByType(messages, "send_agent_message_response"); + const generatedId = sendResponse?.payload.messageId; + expect(typeof generatedId).toBe("string"); + + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.withdraw.request", + requestId: "withdraw-1", + agentId: "agent-1", + messageId: generatedId!, + }); + expect(findByType(messages, "agent.queue.withdraw.response")?.payload).toMatchObject({ + requestId: "withdraw-1", + agentId: "agent-1", + messageId: generatedId, + withdrawn: true, + item: { + id: generatedId, + text: "Withdraw me", + sender: { kind: "user" }, + }, + reason: null, + error: null, + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(findByType(messages, "activity_log")).toBeUndefined(); + + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.withdraw.request", + requestId: "withdraw-missing", + agentId: "agent-1", + messageId: generatedId!, + }); + expect(findByType(messages, "agent.queue.withdraw.response")?.payload).toEqual({ + requestId: "withdraw-missing", + agentId: "agent-1", + messageId: generatedId, + withdrawn: false, + item: null, + reason: "not_found", + error: null, + }); + + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-dispatching", + text: "Going out", + activeTurnBehavior: "interrupt", + }); + await expect + .poll(async () => (await agentMessages.list("agent-1")).items[0]?.state) + .toBe("dispatching"); + + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.withdraw.request", + requestId: "withdraw-busy", + agentId: "agent-1", + messageId: "m-dispatching", + }); + expect(findByType(messages, "agent.queue.withdraw.response")?.payload).toEqual({ + requestId: "withdraw-busy", + agentId: "agent-1", + messageId: "m-dispatching", + withdrawn: false, + item: null, + reason: "already_dispatching", + error: null, + }); + + inFlight.resolve("turn_started"); + await expect.poll(async () => (await agentMessages.list("agent-1")).items.length).toBe(0); + } finally { + running = false; + inFlight.resolve("turn_started"); + await session.cleanup(); + await agentMessages.close(); + rmSync(receiptDir, { recursive: true, force: true }); + } + }); + + test("promotes queued messages and distinguishes not_found and already_dispatching", async () => { + const receiptDir = mkdtempSync(join(tmpdir(), "paseo-queue-promote-")); + const inFlight = deferred<"turn_started">(); + const dispatchedBehaviors: string[] = []; + const agentMessages = createAgentMessageDelivery({ + store: createMemoryAgentMessageQueueStore(), + paseoHome: receiptDir, + isRunning: () => true, + canSteer: () => true, + dispatch: async (request) => { + dispatchedBehaviors.push(request.activeTurnBehavior); + return inFlight.promise; + }, + onError: (error) => { + throw error; + }, + }); + const messages: SessionOutboundMessage[] = []; + const session = createSessionForTest({ + messages, + agentMessages, + messageReceipts: new MessageReceipts(receiptDir), + paseoHome: receiptDir, + agentManager: { + getAgent: (id: string) => + id === "agent-1" + ? ({ id: "agent-1", status: "running", config: {} } as never) + : undefined, + }, + agentStorage: { + get: async (id: string) => (id === "agent-1" ? ({ id: "agent-1" } as never) : null), + }, + }); + + try { + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-1", + text: "First queued", + activeTurnBehavior: "queue", + }); + + await session.handleMessage({ + type: "agent.queue.promote.request", + requestId: "promote-ok", + agentId: "agent-1", + messageId: "m-1", + activeTurnBehavior: "steer", + }); + expect(findByType(messages, "agent.queue.promote.response")?.payload).toEqual({ + requestId: "promote-ok", + agentId: "agent-1", + messageId: "m-1", + promoted: true, + reason: null, + error: null, + }); + await expect.poll(() => dispatchedBehaviors).toEqual(["steer"]); + + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.promote.request", + requestId: "promote-busy", + agentId: "agent-1", + messageId: "m-1", + activeTurnBehavior: "interrupt", + }); + expect(findByType(messages, "agent.queue.promote.response")?.payload).toEqual({ + requestId: "promote-busy", + agentId: "agent-1", + messageId: "m-1", + promoted: false, + reason: "already_dispatching", + error: null, + }); + + messages.length = 0; + await session.handleMessage({ + type: "agent.queue.promote.request", + requestId: "promote-missing", + agentId: "agent-1", + messageId: "missing-msg", + activeTurnBehavior: "interrupt", + }); + expect(findByType(messages, "agent.queue.promote.response")?.payload).toEqual({ + requestId: "promote-missing", + agentId: "agent-1", + messageId: "missing-msg", + promoted: false, + reason: "not_found", + error: null, + }); + + inFlight.resolve("turn_started"); + await expect.poll(async () => (await agentMessages.list("agent-1")).items.length).toBe(0); + } finally { + inFlight.resolve("turn_started"); + await session.cleanup(); + await agentMessages.close(); + rmSync(receiptDir, { recursive: true, force: true }); + } + }); + + test("pushes agent.queue.update only to subscribed sessions, suppresses legacy and internal updates, and pushes empty on clearRecipient", async () => { + const receiptDir = mkdtempSync(join(tmpdir(), "paseo-queue-push-")); + const agentMessages = createAgentMessageDelivery({ + store: createMemoryAgentMessageQueueStore(), + paseoHome: receiptDir, + isRunning: () => true, + dispatch: async () => "turn_started", + onError: (error) => { + throw error; + }, + }); + const legacyMessages: SessionOutboundMessage[] = []; + const legacyTargeted: Array<{ source: object; message: SessionOutboundMessage }> = []; + const legacySession = createSessionForTest({ + messages: legacyMessages, + targetedMessages: legacyTargeted, + agentMessages, + agentStorage: { + get: async () => createStoredAgentRecord({ id: "agent-1", cwd: "/tmp/repo" }), + }, + }); + legacySession.updateClientCapabilities({ provider_subagents: true }, {}); + + const subscribedMessages: SessionOutboundMessage[] = []; + const subscribedSession = createSessionForTest({ + messages: subscribedMessages, + agentMessages, + agentManager: { + getAgent: (id: string) => + id === "internal-1" ? ({ id: "internal-1", internal: true } as never) : undefined, + }, + agentStorage: { + get: async (id: string) => + id === "internal-1" + ? createStoredAgentRecord({ id: "internal-1", cwd: "/tmp/repo", internal: true }) + : createStoredAgentRecord({ id: "agent-1", cwd: "/tmp/repo" }), + }, + }); + + try { + // Subscribe first to an unrelated event: no queue updates yet. + await subscribedSession.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "sub-other", + events: ["agent.background_work.update"], + }); + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-before-sub", + text: "Early", + activeTurnBehavior: "queue", + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(subscribedMessages.some((m) => m.type === "agent.queue.update")).toBe(false); + + // Now subscribe to agent.queue.update. + await subscribedSession.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "sub-queue", + events: ["agent.queue.update"], + }); + subscribedMessages.length = 0; + + // Internal agent queue changes never emit. + await agentMessages.enqueue({ + recipientId: "internal-1", + messageId: "m-internal", + text: "Private", + activeTurnBehavior: "queue", + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(subscribedMessages.some((m) => m.type === "agent.queue.update")).toBe(false); + + const latestQueueUpdate = () => + subscribedMessages.findLast((m) => m.type === "agent.queue.update"); + + // Visible agent queue change pushes to subscribed session only, never to legacy session. + await agentMessages.enqueue({ + recipientId: "agent-1", + messageId: "m-visible", + text: "Visible", + activeTurnBehavior: "queue", + }); + await expect.poll(() => latestQueueUpdate()?.payload.items.length).toBe(2); + const legacyAll = [...legacyMessages, ...legacyTargeted.map((e) => e.message)]; + expect(legacyAll.some((m) => m.type === "agent.queue.update")).toBe(false); + + // Clearing the queue (archive/delete) pushes an empty agent.queue.update. + await agentMessages.clearRecipient("agent-1"); + await expect.poll(() => latestQueueUpdate()?.payload.items).toEqual([]); + } finally { + await legacySession.cleanup(); + await subscribedSession.cleanup(); + await agentMessages.close(); + rmSync(receiptDir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index bf0f40eb0a..f1c546fae4 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -1,6 +1,10 @@ import { DiffSession } from "./diff/index.js"; import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; -import type { AgentMessageBehavior, AgentMessageDelivery } from "./agent/agent-messages/index.js"; +import type { + AgentMessageBehavior, + AgentMessageDelivery, + PersistedQueuedMessage, +} from "./agent/agent-messages/index.js"; import { AgentDirectory, type BackgroundVisibility } from "./agent/directory.js"; import { ConnectedHostSession } from "./connected-hosts/index.js"; import { TunnelSession, type TunnelManager } from "./tunnels/index.js"; @@ -48,6 +52,8 @@ import { type AgentSnapshotPayload, type AgentAttachment, type FirstAgentContext, + type QueuedAgentMessagePayload, + type QueuedMessageSender, type SessionInboundMessage, type SessionOutboundMessage, type ScriptStatusUpdateMessage, @@ -906,6 +912,8 @@ export class Session { } private readonly orchestrationSkills: SessionOptions["orchestrationSkills"]; private unsubscribeAgentEvents: (() => void) | null = null; + private unsubscribeAgentQueueChanges: (() => void) | null = null; + private readonly agentQueueUpdateSeq = new Map(); private unsubscribeProjectMutations: (() => void) | null = null; private unsubscribePluginChanges: (() => void) | null = null; private unsubscribeUsageReports: (() => void) | null = null; @@ -2045,6 +2053,16 @@ export class Session { this.unsubscribeAgentEvents?.(); this.unsubscribeAgentEvents = null; } + if (this.wantsEvent("agent.queue.update")) { + this.unsubscribeAgentQueueChanges ??= this.agentMessages.onChange((agentId) => { + void this.forwardAgentQueue(agentId).catch((error) => + this.sessionLogger.error({ err: error, agentId }, "Failed to emit agent queue update"), + ); + }); + } else { + this.unsubscribeAgentQueueChanges?.(); + this.unsubscribeAgentQueueChanges = null; + } this.refreshWorkspaceProducers(workspaces); this.refreshCatalogProducers(legacy); } @@ -2478,7 +2496,7 @@ export class Session { } private async forwardBackgroundWork(agentId: string): Promise { - const target = await this.resolveBackgroundWorkAgent(agentId); + const target = await this.resolveVisibleAgent(agentId); if ("error" in target) return; const { agent, record } = target; // The inventory may have changed while resolving a dormant agent. @@ -2493,6 +2511,34 @@ export class Session { else if (record) await this.agentUpdates.forwardStoredAgent(record); } + private async forwardAgentQueue(agentId: string): Promise { + if (!this.wantsEvent("agent.queue.update")) return; + const seq = (this.agentQueueUpdateSeq.get(agentId) ?? 0) + 1; + this.agentQueueUpdateSeq.set(agentId, seq); + try { + const [record, agent] = await Promise.all([ + this.agentStorage.get(agentId), + Promise.resolve(this.agentManager.getAgent(agentId)), + ]); + if (this.isCleanedUp || this.agentQueueUpdateSeq.get(agentId) !== seq) return; + if (agent?.internal || record?.internal) return; + const { held, items } = await this.agentMessages.list(agentId); + if (this.isCleanedUp || this.agentQueueUpdateSeq.get(agentId) !== seq) return; + this.emit({ + type: "agent.queue.update", + payload: { + agentId, + held, + items: items.map(toQueuedAgentMessagePayload), + }, + }); + } finally { + if (this.agentQueueUpdateSeq.get(agentId) === seq) { + this.agentQueueUpdateSeq.delete(agentId); + } + } + } + private projectBackgroundWorkItems(items: AgentBackgroundWorkItem[]): AgentBackgroundWorkItem[] { if ( this.authorization.allowsPermission("automation.manage") && @@ -3399,6 +3445,12 @@ export class Session { return this.handleAgentBackgroundWorkListRequest(msg); case "agent.background_work.stop.request": return this.handleAgentBackgroundWorkStopRequest(msg); + case "agent.queue.list.request": + return this.handleAgentQueueListRequest(msg); + case "agent.queue.withdraw.request": + return this.handleAgentQueueWithdrawRequest(msg); + case "agent.queue.promote.request": + return this.handleAgentQueuePromoteRequest(msg); case "agent.provider_subagents.timeline.get.request": return this.handleProviderSubagentTimelineRequest(msg, source); case "session.events.set_subscription.request": { @@ -9401,7 +9453,7 @@ export class Session { ): Promise { let error: string | null = null; try { - const target = await this.resolveBackgroundWorkAgent(msg.agentId); + const target = await this.resolveVisibleAgent(msg.agentId); if ("error" in target) throw new Error(target.error); await this.agentManager.stopAgentBackgroundWork({ agentId: msg.agentId, @@ -9449,8 +9501,132 @@ export class Session { } } + private async handleAgentQueueListRequest( + msg: Extract, + ): Promise { + try { + const target = await this.resolveVisibleAgent(msg.agentId); + if ("error" in target) throw new Error(target.error); + const { held, items } = await this.agentMessages.list(msg.agentId); + this.emit({ + type: "agent.queue.list.response", + payload: { + requestId: msg.requestId, + agentId: msg.agentId, + held, + items: items.map(toQueuedAgentMessagePayload), + error: null, + }, + }); + } catch (error) { + this.emit({ + type: "agent.queue.list.response", + payload: { + requestId: msg.requestId, + agentId: msg.agentId, + held: false, + items: [], + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } + + private async handleAgentQueueWithdrawRequest( + msg: Extract, + ): Promise { + try { + const target = await this.resolveVisibleAgent(msg.agentId); + if ("error" in target) throw new Error(target.error); + const result = await this.agentMessages.withdraw(msg.agentId, msg.messageId); + this.emit({ + type: "agent.queue.withdraw.response", + payload: + result.status === "withdrawn" + ? { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + withdrawn: true, + item: toQueuedAgentMessagePayload(result.item), + reason: null, + error: null, + } + : { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + withdrawn: false, + item: null, + reason: result.status, + error: null, + }, + }); + } catch (error) { + this.emit({ + type: "agent.queue.withdraw.response", + payload: { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + withdrawn: false, + item: null, + reason: null, + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } + + private async handleAgentQueuePromoteRequest( + msg: Extract, + ): Promise { + try { + const target = await this.resolveVisibleAgent(msg.agentId); + if ("error" in target) throw new Error(target.error); + const outcome = await this.agentMessages.promote( + msg.agentId, + msg.messageId, + msg.activeTurnBehavior, + ); + this.emit({ + type: "agent.queue.promote.response", + payload: + outcome === "promoted" + ? { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + promoted: true, + reason: null, + error: null, + } + : { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + promoted: false, + reason: outcome, + error: null, + }, + }); + } catch (error) { + this.emit({ + type: "agent.queue.promote.response", + payload: { + requestId: msg.requestId, + agentId: msg.agentId, + messageId: msg.messageId, + promoted: false, + reason: null, + error: error instanceof Error ? error.message : String(error), + }, + }); + } + } + private async readAgentBackgroundWork(agentId: string): Promise { - const target = await this.resolveBackgroundWorkAgent(agentId); + const target = await this.resolveVisibleAgent(agentId); if ("error" in target) throw new Error(target.error); if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) { throw new Error("Background work inventory is unavailable"); @@ -9458,7 +9634,7 @@ export class Session { return this.projectBackgroundWorkItems(this.agentManager.listAgentBackgroundWork(agentId)); } - private async resolveBackgroundWorkAgent( + private async resolveVisibleAgent( agentId: string, ): Promise<{ agent: ManagedAgent | null; record: StoredAgentRecord | null } | { error: string }> { const record = await this.agentStorage.get(agentId); @@ -9862,7 +10038,9 @@ export class Session { activeTurnBehavior: msg.activeTurnBehavior ?? (msg.sourceAgentId ? "steer" : "interrupt"), }; const fingerprint = msg.messageId ? fingerprintRequest(request) : undefined; - let queuedReceipt: { activeTurnBehavior: AgentMessageBehavior; guidance: string } | undefined; + let queuedReceipt: + | { messageId: string; activeTurnBehavior: AgentMessageBehavior; guidance: string } + | undefined; const enqueue = async () => { if (!msg.sourceAgentId) await this.prepareAgentMessage(agentId, msg.text); const receipt = await this.agentMessages.enqueue({ @@ -9889,6 +10067,7 @@ export class Session { }); queuedReceipt = receipt; void receipt.dispatched.catch((error) => { + if (error instanceof Error && error.name === "AbortError") return; this.handleAgentRunError(agentId, error, "Failed to dispatch queued agent message"); }); }; @@ -9942,6 +10121,7 @@ export class Session { ...(queuedReceipt ? { deliveryStatus: "queued" as const, + messageId: queuedReceipt.messageId, activeTurnBehavior: queuedReceipt.activeTurnBehavior, guidance: queuedReceipt.guidance, } @@ -10307,6 +10487,8 @@ export class Session { this.unsubscribeAgentEvents(); this.unsubscribeAgentEvents = null; } + this.unsubscribeAgentQueueChanges?.(); + this.unsubscribeAgentQueueChanges = null; this.unsubscribeProjectMutations?.(); this.unsubscribeProjectMutations = null; this.unsubscribePluginChanges?.(); @@ -10415,6 +10597,7 @@ function sessionEventCategory(message: SessionOutboundMessage): SessionEventSubs case "workspace_setup_progress": case "agent.provider_subagents.update": case "agent.background_work.update": + case "agent.queue.update": case "terminal_attention_required": case "plugin.notification": case "activity_log": @@ -10445,6 +10628,7 @@ function legacyWantsEvent( return capabilities.has(CLIENT_CAPS.providerSubagents); // Old apps parse outbound messages strictly and do not know this type. case "agent.background_work.update": + case "agent.queue.update": case "plugin.notification": // Older apps poll usage instead; this event only reaches sources that ask for it. case "status.usage_report_changed": @@ -10479,6 +10663,45 @@ function hostSource(options: SessionOptions): string { return options.sourceId ?? "owner"; } +function toQueuedMessageSender(source: PersistedQueuedMessage["source"]): QueuedMessageSender { + if (!source) return { kind: "user" }; + switch (source.kind) { + case "agent-message": + return { + kind: "agent_message", + agentId: source.agentId, + ...(source.serverId ? { serverId: source.serverId } : {}), + ...(source.title ? { title: source.title } : {}), + }; + case "agent-notification": + return { + kind: "agent_notification", + agentId: source.agentId, + ...(source.serverId ? { serverId: source.serverId } : {}), + ...(source.title ? { title: source.title } : {}), + event: source.event, + }; + case "change-request-update": + return { + kind: "change_request_update", + url: source.url, + }; + } +} + +function toQueuedAgentMessagePayload(record: PersistedQueuedMessage): QueuedAgentMessagePayload { + return { + id: record.id, + seq: record.seq, + enqueuedAt: record.enqueuedAt, + text: record.text, + ...(record.attachments.length > 0 ? { attachments: record.attachments } : {}), + sender: toQueuedMessageSender(record.source), + held: record.held, + state: record.state, + }; +} + function dedupeSlashCommands(commands: readonly T[]): T[] { const seen = new Set(); const unique: T[] = []; diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index ac36723960..6d34a2e291 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -1162,6 +1162,7 @@ describe("relay external socket reconnect behavior", () => { expect(serverInfo.features?.["terminal-size-ownership"]).toBe(true); expect(serverInfo.features?.["terminal-palette-ownership"]).toBe(true); expect(serverInfo.features?.["terminal-grapheme-widths"]).toBe(true); + expect(serverInfo.features?.agentMessageQueue).toBe(true); expect(serverInfo.features?.agentTurnIdentity).toBeUndefined(); expect(serverInfo.permissions).toEqual(DAEMON_PERMISSIONS); await server.close(); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index cfb7b90768..515431c52c 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2378,6 +2378,8 @@ export class VoiceAssistantWebSocketServer { agentActiveTurnBehaviors: true, // COMPAT(nonAgentMessageQueue): added in v0.18.2, remove gate after 2027-06-01. nonAgentMessageQueue: true, + // COMPAT(agentMessageQueue): added in v0.18.2, remove gate after 2027-06-01. + agentMessageQueue: true, // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. stableProjectIdentity: true, // COMPAT(workspaceScriptManagement): added in v0.1.105, remove gate after 2027-01-10.