diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 1fb9a9352b..1f982aeb82 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -198,20 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits notification. Clean shutdown can also flush an already queued callback while retaining its intent, so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery. -A turn end is not always a settled child. When the child ends its turn with work that will start its -next turn by itself, the caller hears nothing and the subscription follows the child until it settles. -That work is a running turn, queued messages, a pending provider wake-up +A turn end is not always a settled child. A child can end its turn with work that will start its next +turn by itself: a running turn, queued messages, a pending provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring crons, change-request watches, and other daemon background items never count: they are external -triggers, not work the caller is waiting for. While following, turn ends and work changes stay silent -until nothing is pending, which sends `finished` and removes the subscription. Errors, permission -requests, and closes still report as they happen. `followingSince` is stored when following starts, -so a restart keeps following instead of waiting for another turn end. After 24 hours of following, -the caller gets `finished` with the child's last reply, so a task that never ends (a dev server, for -example) cannot hold the caller forever. Remote children and providers without the probe report -their first turn end as `finished`. There is no interim notice, because it would only wake the caller -to wait again. +triggers, not work the caller is waiting for. + +Every turn end reports `finished` at once. When work is still pending, the notice names it and the +subscription follows the child: each later turn end reports `finished` again, and the child settling +with nothing pending sends a final `finished` and removes the subscription, even when the work +drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from +leaving the caller without the child's reply. Following is what lets the caller hear the reply a +background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change +that leaves work pending sends nothing. Errors, permission requests, and closes report as they +happen. `followingSince` is stored when following starts, so a restart keeps following instead of +waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with +the child's last reply and the subscription ends. Remote children and providers without the probe +report their first turn end as a settled `finished`. Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission. The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status. diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index 48cce08e6c..a684b85c13 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -315,7 +315,7 @@ async function callPaseoToolAs( } } -test("a delegated child reports once, as a compact tool call, when its own delegate is done", async ({ +test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({ page, }, testInfo) => { const frames: string[] = []; @@ -345,28 +345,33 @@ test("a delegated child reports once, as a compact tool call, when its own deleg settings: { modeId: "load-test" }, initialPrompt: "Take your time", }); - await parent.client.waitForAgentUpsert(childId, (agent) => agent.status === "running"); - await parent.client.waitForAgentUpsert(childId, (agent) => agent.status === "idle", 30_000); + const notices = page.getByRole("button", { name: /^Agent .*Child/ }); + const finished = page.getByRole("button", { name: /^Agent finished.*Child/ }); - // The child ended its turn while waiting on its delegate: the parent hears nothing yet. - await page.waitForTimeout(1_500); + // The child ended its turn while waiting on its delegate: the parent hears it now. + await expect(finished).toHaveCount(1, { timeout: 30_000 }); const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true); expect(delegate.status, "the delegate must still be running").toBe("running"); - expect(childNoticeFrames()).toEqual([]); - await expect(page.getByRole("button", { name: /^Agent .*Child/ })).toHaveCount(0); + expect( + childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")), + ).toBe(true); - const finished = page.getByRole("button", { name: /^Agent finished.*Child/ }); - await expect(finished).toBeVisible({ timeout: 60_000 }); - await expect(page.getByRole("button", { name: /^Agent .*Child/ })).toHaveCount(1); + // The delegate reports to the child, and the child's settled turn reaches the parent. + await expect(finished).toHaveCount(2, { timeout: 60_000 }); + await expect(notices).toHaveCount(2); + await expect(page.getByText(/still working/i)).toHaveCount(0); await expect(page.getByText(/Sent by/)).toHaveCount(0); await expect(page.getByText(//)).toHaveCount(0); - await finished.scrollIntoViewIfNeeded(); + await finished.last().scrollIntoViewIfNeeded(); await page.screenshot({ path: testInfo.outputPath("child-notices.png") }); // Notification events stay on the daemon: clients get only plain tool calls. expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]); expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe( true, ); + expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual( + [], + ); } finally { await parent.cleanup(); } 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 bf73b6fb1f..1a5aecd5a3 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 @@ -558,51 +558,74 @@ test("an undispatched follow-up does not block the running child's permission no expect(await state.store.list()).toHaveLength(2); }); +const STILL_WORKING = "You will be notified again when it settles"; + describe("a child that ends its turn with work pending", () => { - async function following(state: Awaited>) { + /** Ends the child's first turn with `work` pending; the caller accepts the turn-end notice. */ + async function following( + state: Awaited>, + work: PendingWork[] = ["background work"], + ) { await state.service.register(intent); await until(() => state.observation.waits.length === 1); - state.observation.work.set("child", ["background work"]); + state.observation.work.set("child", work); state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Waiting for the build")); + await until(() => state.delivery.prompts.length === 1); + state.delivery.acknowledgments[0]!.resolve("steered"); await until(() => state.observation.waits.length === 2); } + const wait = (state: Awaited>, child: string, index = 0) => + state.observation.waitsFor(child)[index]!; - test("tells the caller nothing until the child settles, then reports finished once", async () => { + test("reports the turn end at once with its pending work, then the final finish", async () => { const state = await scenario(); await following(state); - expect(state.delivery.prompts).toEqual([]); + // A task such as a dev server can run for as long as the child lives. + expect(state.delivery.prompts[0]).toContain("Agent child (Child) finished."); + expect(state.delivery.prompts[0]).toContain("Waiting for the build"); + expect(state.delivery.prompts[0]).toContain("It still has background work that will wake it."); + expect(state.delivery.prompts[0]).toContain(STILL_WORKING); + expect(parseAgentMessage(state.delivery.enqueued[0]!)).toMatchObject({ + source: { kind: "agent-notification", event: "finished" }, + }); expect(await state.store.list()).toEqual([ expect.objectContaining({ followingSince: expect.any(String) }), ]); state.observation.work.set("child", []); state.observation.waits[1]!.result.resolve(outcome("idle", "child", "FINAL: done")); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent child (Child) finished."); - expect(state.delivery.prompts[0]).toContain("FINAL: done"); - expect(parseAgentMessage(state.delivery.enqueued[0]!)).toMatchObject({ + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished."); + expect(state.delivery.prompts[1]).toContain("FINAL: done"); + expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING); + expect(parseAgentMessage(state.delivery.enqueued[1]!)).toMatchObject({ source: { kind: "agent-notification", event: "finished" }, }); - state.delivery.acknowledgments[0]!.resolve("steered"); + state.delivery.acknowledgments[1]!.resolve("steered"); await expect.poll(async () => (await state.store.list()).length).toBe(0); // A turn a person starts after the child settled has no observer left to report it. expect(state.observation.waits).toHaveLength(2); expect(state.service.hasPendingForCaller("parent")).toBe(false); }); - test("stays silent for turns that end while work is still pending", async () => { + test("reports each later turn that ends while work is still pending", async () => { const state = await scenario(); - await following(state); + await following(state, ["queued messages"]); + expect(state.delivery.prompts[0]).toContain("It still has queued messages."); state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Still waiting")); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Still waiting"); + expect(state.delivery.prompts[1]).toContain(STILL_WORKING); + state.delivery.acknowledgments[1]!.resolve("steered"); await until(() => state.observation.waits.length === 3); - expect(state.delivery.prompts).toEqual([]); state.observation.work.set("child", []); state.observation.waits[2]!.result.resolve(outcome("idle", "child", "FINAL")); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("finished."); + await until(() => state.delivery.prompts.length === 3); + expect(state.delivery.prompts[2]).toContain("FINAL"); + expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING); }); - test("sends finished when its work drains while it is idle, without another turn", async () => { + test("sends the final finish when its work drains while it is idle, without another turn", async () => { const state = await scenario(); await following(state); state.observation.work.set("child", []); @@ -610,8 +633,22 @@ describe("a child that ends its turn with work pending", () => { ...outcome("idle", "child", "Waiting for the build"), workChanged: true, }); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent child (Child) finished."); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished."); + expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING); + state.delivery.acknowledgments[1]!.resolve("steered"); + await expect.poll(async () => (await state.store.list()).length).toBe(0); + }); + + test("a work change that leaves work pending sends nothing", async () => { + const state = await scenario(); + await following(state); + state.observation.waits[1]!.result.resolve({ + ...outcome("idle", "child", "Waiting for the build"), + workChanged: true, + }); + await until(() => state.observation.waits.length === 3); + expect(state.delivery.prompts).toHaveLength(1); }); test("ignores a work change before the child's first turn ends", async () => { @@ -629,9 +666,6 @@ describe("a child that ends its turn with work pending", () => { test("restart while following keeps following and still reports the final finish", async () => { const first = await scenario(); await following(first); - await expect - .poll(async () => (await first.store.list())[0]?.followingSince) - .toEqual(expect.any(String)); await first.service.close(); const restarted = await scenario(first.home); await until(() => restarted.observation.waits.length === 1); @@ -643,6 +677,7 @@ describe("a child that ends its turn with work pending", () => { await until(() => restarted.delivery.prompts.length === 1); expect(restarted.delivery.prompts[0]).toContain("finished."); expect(restarted.delivery.prompts[0]).toContain("FINAL"); + expect(restarted.delivery.prompts[0]).not.toContain(STILL_WORKING); }); test("a permission request raised after waking up reaches the parent", async () => { @@ -656,39 +691,42 @@ describe("a child that ends its turn with work pending", () => { >["pendingPermissions"][number], ]; state.observation.waits[1]!.result.resolve(result); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("needs permission"); - expect(state.delivery.prompts[0]).toContain("respond_to_permission"); - state.delivery.acknowledgments[0]!.resolve("steered"); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("needs permission"); + expect(state.delivery.prompts[1]).toContain("respond_to_permission"); + state.delivery.acknowledgments[1]!.resolve("steered"); await until(() => state.observation.waits.length === 3); state.observation.work.set("child", []); state.observation.waits[2]!.result.resolve(outcome("idle", "child", "Plan approved and done")); - await until(() => state.delivery.prompts.length === 2); - expect(state.delivery.prompts[1]).toContain("finished."); - expect(state.delivery.prompts[1]).toContain("Plan approved and done"); + await until(() => state.delivery.prompts.length === 3); + expect(state.delivery.prompts[2]).toContain("finished."); + expect(state.delivery.prompts[2]).toContain("Plan approved and done"); }); - test("a helper waiting on its own delegated agent is followed until that delegation settles", async () => { + test("a helper waiting on its own delegated agent reports now and again once it settles", async () => { const state = await scenario(); await state.service.register({ callerAgentId: "parent", childAgentId: "helper" }); await state.service.register({ callerAgentId: "helper", childAgentId: "sub" }); await until(() => state.observation.waits.length === 2); - const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!; - wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper")); - await until(() => state.observation.waitsFor("helper").length === 2); - expect(state.delivery.prompts).toEqual([]); - - wait("sub").result.resolve(outcome("idle", "sub", "Sub result")); + wait(state, "helper").result.resolve(outcome("idle", "helper", "Waiting for my helper")); await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent sub (Child) finished."); + expect(state.delivery.prompts[0]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[0]).toContain("It still has agents it is waiting on."); state.delivery.acknowledgments[0]!.resolve("steered"); + + wait(state, "sub").result.resolve(outcome("idle", "sub", "Sub result")); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent sub (Child) finished."); + state.delivery.acknowledgments[1]!.resolve("steered"); await until(() => !state.service.hasPendingForCaller("helper")); - wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final")); - await until(() => state.delivery.prompts.length === 2); - expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished."); - expect(state.delivery.prompts[1]).toContain("Helper final"); + await until(() => state.observation.waitsFor("helper").length === 2); + wait(state, "helper", 1).result.resolve(outcome("idle", "helper", "Helper final")); + await until(() => state.delivery.prompts.length === 3); + expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[2]).toContain("Helper final"); + expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING); }); test("a followed helper settles when its last delegation ends without reporting to it", async () => { @@ -700,18 +738,19 @@ describe("a child that ends its turn with work pending", () => { requireParentOwnership: true, }); await until(() => state.observation.waits.length === 2); - const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!; - wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper")); + wait(state, "helper").result.resolve(outcome("idle", "helper", "Waiting for my helper")); + await until(() => state.delivery.prompts.length === 1); + state.delivery.acknowledgments[0]!.resolve("steered"); await until(() => state.observation.waitsFor("helper").length === 2); - expect(state.delivery.prompts).toEqual([]); // The sub was detached from the helper, so its result is not reported to the helper. - wait("sub").result.resolve(outcome("idle", "sub", "Sub result")); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent helper (Child) finished."); - expect(state.delivery.prompts[0]).toContain("Waiting for my helper"); - expect(state.delivery.prompts[0]).not.toContain("Sub result"); + wait(state, "sub").result.resolve(outcome("idle", "sub", "Sub result")); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[1]).toContain("Waiting for my helper"); + expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING); + expect(state.delivery.prompts.join("\n")).not.toContain("Sub result"); }); test("agents that only wait on each other settle and both callers hear finished", async () => { @@ -721,35 +760,41 @@ describe("a child that ends its turn with work pending", () => { // The helper asks its parent a question and waits for the answer. await state.service.register({ callerAgentId: "helper", childAgentId: "parent" }); await until(() => state.observation.waits.length === 2); - const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!; state.observation.work.set("parent", ["turn"]); - wait("helper").result.resolve(outcome("idle", "helper", "Asked my parent")); - await until(() => state.observation.waitsFor("helper").length === 2); - expect(state.delivery.prompts).toEqual([]); + wait(state, "helper").result.resolve(outcome("idle", "helper", "Asked my parent")); + await until(() => state.delivery.prompts.length === 1); + expect(state.delivery.prompts[0]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[0]).toContain(STILL_WORKING); + state.delivery.acknowledgments[0]!.resolve("steered"); // The parent answers. It waits on the helper, and the helper waits only on it. state.observation.work.set("parent", []); - wait("parent").result.resolve(outcome("idle", "parent", "The answer")); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent parent (Child) finished."); - expect(state.delivery.prompts[0]).toContain("The answer"); - state.delivery.acknowledgments[0]!.resolve("steered"); + wait(state, "parent").result.resolve(outcome("idle", "parent", "The answer")); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent parent (Child) finished."); + expect(state.delivery.prompts[1]).toContain("The answer"); + expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING); + state.delivery.acknowledgments[1]!.resolve("steered"); await until(() => !state.service.hasPendingForCaller("helper")); - wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final")); - await until(() => state.delivery.prompts.length === 2); - expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished."); - expect(state.delivery.prompts[1]).toContain("Helper final"); + await until(() => state.observation.waitsFor("helper").length === 2); + wait(state, "helper", 1).result.resolve(outcome("idle", "helper", "Helper final")); + await until(() => state.delivery.prompts.length === 3); + expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[2]).toContain("Helper final"); + expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING); }); - test("at the follow limit the caller gets finished with the child's last reply", async () => { + test("at the follow limit the caller gets a final finished with the child's last reply", async () => { const state = await scenario(undefined, 0, 1, 50); await following(state); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("Agent child (Child) finished."); - expect(state.delivery.prompts[0]).toContain("Waiting for the build"); - state.delivery.acknowledgments[0]!.resolve("steered"); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished."); + expect(state.delivery.prompts[1]).toContain("Waiting for the build"); + expect(state.delivery.prompts[1]).toContain("Paseo stopped following it"); + expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING); + state.delivery.acknowledgments[1]!.resolve("steered"); await expect.poll(async () => (await state.store.list()).length).toBe(0); }); @@ -757,9 +802,9 @@ describe("a child that ends its turn with work pending", () => { const state = await scenario(); await following(state); state.observation.waits[1]!.result.resolve(outcome("error")); - await until(() => state.delivery.prompts.length === 1); - expect(state.delivery.prompts[0]).toContain("errored"); - state.delivery.acknowledgments[0]!.resolve("steered"); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("errored"); + state.delivery.acknowledgments[1]!.resolve("steered"); await expect.poll(async () => (await state.store.list()).length).toBe(0); }); }); diff --git a/packages/server/src/server/agent/finish-subscriptions/index.ts b/packages/server/src/server/agent/finish-subscriptions/index.ts index 149c4ea1a0..385ae5fb50 100644 --- a/packages/server/src/server/agent/finish-subscriptions/index.ts +++ b/packages/server/src/server/agent/finish-subscriptions/index.ts @@ -14,6 +14,7 @@ import { import { createFollowing, FOLLOW_LIMIT, + type Decision, type FollowOutcome, type Notice, } from "./internal/following.js"; @@ -226,6 +227,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio reason, lastAssistantMessage: result?.lastMessage ?? null, permissionRequest: request, + pendingWork: notice.pendingWork, + followLimit: notice.followLimit, }), source: { kind: "agent-notification", @@ -303,9 +306,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio const permissions = new Set(); let observation: FinishObservationSession | undefined; /** One outcome and how far it got. Retries resume it: nothing is lost or sent twice. */ - let current: - | { outcome: FollowOutcome; decided: boolean; notice?: Notice; sent: boolean } - | undefined; + let current: { outcome: FollowOutcome; decision?: Decision; sent: boolean } | undefined; let remoteFailures = 0; let retries = 0; let warned = false; @@ -338,7 +339,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio if (!notified) recheckCallerOf(watch); return true; } - async function decide(outcome: FollowOutcome): Promise { + async function decide(outcome: FollowOutcome): Promise { // A queued follow-up cannot start until the current permission is answered. // Its pending registration must not hold the running turn's checkpoint. if (outcome === FOLLOW_LIMIT || outcome.status !== "permission" || watch.pending) @@ -357,23 +358,24 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio await delay(signal, retries++); return false; } - current = { outcome, decided: false, sent: false }; + current = { outcome, sent: false }; } signal.throwIfAborted(); - if (!current.decided) { - const notice = await decide(current.outcome); - if (notice === "suppressed") return end(false); - current = { ...current, decided: true, notice }; + let { decision } = current; + if (!decision) { + const decided = await decide(current.outcome); + if (decided === "suppressed") return end(false); + decision = decided; + current = { ...current, decision }; } - const { notice } = current; + const { notice, done } = decision; if (notice && !current.sent) { await deliver(record, notice, permissions, signal); signal.throwIfAborted(); current.sent = true; } // A removal failure retries only the commit, never the already accepted callback. - // A permission request is a checkpoint; the caller still hears how the child ends. - if (notice && notice.reason !== "needs permission") return end(true); + if (done) return end(notice !== undefined); current = undefined; retries = 0; warned = false; diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/following.ts b/packages/server/src/server/agent/finish-subscriptions/internal/following.ts index b9b6076cae..a6bbcd9982 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/following.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/following.ts @@ -11,8 +11,20 @@ export type FollowOutcome = FinishObservationResult | typeof FOLLOW_LIMIT; export interface Notice { reason: FinishNotificationReason; result: FinishObservationResult | null; + /** The turn ended with this work pending; the watch keeps following the child. */ + pendingWork?: readonly PendingWork[]; + /** The follow limit passed while the child still had pending work; the watch ends. */ + followLimit?: true; } +/** What one outcome means for the watch: what to tell the caller, and whether to stop watching. */ +export interface Decision { + notice?: Notice; + done: boolean; +} + +const KEEP_WATCHING: Decision = { done: false }; + interface Options { /** The watch's coalesced records; any one already following makes the watch follow. */ records: readonly FinishSubscription[]; @@ -25,10 +37,11 @@ interface Options { /** * Separates "the turn ended" from "the child has stopped". A watch waits for its prompt's turn. - * If that turn ends while the child still has pending work, the watch follows the child without - * telling the caller: later turn ends and work changes stay silent until the child settles, - * which reports `finished`. When the follow limit passes first, the caller gets `finished` - * with the child's last reply, as it would have when that turn ended. + * Each turn end reports `finished` at once. When work that will start the child's next turn is + * still pending, the notice names that work and the watch follows the child: later turn ends + * report again, and the child settling with nothing pending, even without another turn, sends the + * final `finished` and ends the watch. When the follow limit passes first, the caller gets a final + * `finished` with the child's last reply. */ export function createFollowing(options: Options) { let since = options.records @@ -91,17 +104,22 @@ export function createFollowing(options: Options) { stale = true; wake?.(); }, - /** Returns nothing when the outcome is not worth telling the caller. */ - async decide(outcome: FollowOutcome): Promise { - if (outcome === FOLLOW_LIMIT) return { reason: "finished", result: latest }; + async decide(outcome: FollowOutcome): Promise { + if (outcome === FOLLOW_LIMIT) + return { notice: { reason: "finished", result: latest, followLimit: true }, done: true }; latest = outcome; const reason = options.reasonFor(outcome); - if (reason !== "finished") return { reason, result: outcome }; + // A permission request is a checkpoint; the caller still hears how the child ends. + if (reason !== "finished") + return { notice: { reason, result: outcome }, done: reason !== "needs permission" }; // Before the prompt's turn ends, a work change says nothing about its outcome. - if (outcome.workChanged && !since) return undefined; - if (!options.pendingWork().length) return { reason, result: outcome }; + if (outcome.workChanged && !since) return KEEP_WATCHING; + const pendingWork = options.pendingWork(); + if (!pendingWork.length) return { notice: { reason, result: outcome }, done: true }; if (!since) await follow(); - return undefined; + // Work that changed but is still pending brings no new reply. + if (outcome.workChanged) return KEEP_WATCHING; + return { notice: { reason, result: outcome, pendingWork }, done: false }; }, }; } diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/notification.ts b/packages/server/src/server/agent/finish-subscriptions/internal/notification.ts index d712b7ba7f..d78acf52bf 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/notification.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/notification.ts @@ -1,4 +1,5 @@ import type { AgentPermissionRequest } from "../../agent-sdk-types.js"; +import type { PendingWork } from "../index.js"; export type FinishNotificationReason = | "host unreachable" | "host removed" @@ -20,6 +21,13 @@ export const finishNotificationEvents = { "was canceled": "errored", } as const; +const PENDING_WORK_DESCRIPTIONS: Record = { + turn: "a turn in progress", + "background work": "background work that will wake it", + "queued messages": "queued messages", + "delegated agents": "agents it is waiting on", +}; + const FINISH_NOTIFICATION_MESSAGE_LIMIT = 4000; interface FinishNotificationBodyInput { @@ -29,6 +37,10 @@ interface FinishNotificationBodyInput { reason: FinishNotificationReason; lastAssistantMessage: string | null; permissionRequest?: AgentPermissionRequest; + /** The turn ended with this work pending; the subscription stays. */ + pendingWork?: readonly PendingWork[]; + /** The follow limit ended the subscription while the child still had pending work. */ + followLimit?: true; } export function formatFinishNotificationBody(params: FinishNotificationBodyInput): string { @@ -42,6 +54,14 @@ export function formatFinishNotificationBody(params: FinishNotificationBodyInput const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}.`; const sections = [statusLine]; if (params.serverId) sections.push(`Server: ${params.serverId}`); + if (params.pendingWork?.length) + sections.push( + `It still has ${params.pendingWork.map((work) => PENDING_WORK_DESCRIPTIONS[work]).join(", ")}. You will be notified again when it settles, errors, or needs permission.`, + ); + if (params.followLimit) + sections.push( + "Paseo stopped following it while it still had pending work. Check the agent with `get_agent_status`.", + ); if (params.reason === "needs permission" && params.permissionRequest) { sections.push( "Respond with `respond_to_permission` using the `agentId` and `requestId` below.", diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/observation-buffer.ts b/packages/server/src/server/agent/finish-subscriptions/internal/observation-buffer.ts index 124daf7ed8..5e9c38d523 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/observation-buffer.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/observation-buffer.ts @@ -13,6 +13,8 @@ export function createObservationBuffer(signal: AbortSignal) { const resolvedBeforeInitial = new Set(); let initialPending = true; let terminal: FinishObservationResult | undefined; + /** A turn end arrived from the stream; the initial wait can only repeat it. */ + let ended = false; let failure: unknown; let wake: (() => void) | undefined; const abort = () => { @@ -25,7 +27,10 @@ export function createObservationBuffer(signal: AbortSignal) { if (result.status === "permission") { for (const request of result.final?.pendingPermissions ?? []) if (!delivered.has(request.id)) permissions.set(request.id, result); - } else if (!result.workChanged || !terminal || terminal.workChanged) terminal = result; + } else if (!result.workChanged || !terminal || terminal.workChanged) { + terminal = result; + if (!result.workChanged) ended = true; + } wake?.(); } return { @@ -38,7 +43,7 @@ export function createObservationBuffer(signal: AbortSignal) { if (pendingPermissions.length) push({ ...result, final: { ...result.final, pendingPermissions } }); } else if ( - !terminal && + !ended && result.final?.status !== "running" && result.final?.status !== "initializing" ) diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/observation-stream.test.ts b/packages/server/src/server/agent/finish-subscriptions/internal/observation-stream.test.ts index 5bc0b3f7d7..35bbec5587 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/observation-stream.test.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/observation-stream.test.ts @@ -148,6 +148,35 @@ test("late initial permission snapshot cannot resurrect an already resolved requ } }); +test("the initial wait that resolves after a turn end does not report that turn again", async () => { + const { host, observation } = await scenario(); + try { + host.emit("idle", { type: "turn_completed", provider: "codex" }); + const ended = await observation.next(); + expect(ended.status).toBe("idle"); + // The ordinary wait was waiting on the same turn and resolves after it. + host.baseline.resolve({ + status: "idle", + final: ended.final, + lastMessage: "Last response", + error: null, + }); + await host.baseline.promise; + await Promise.resolve(); + let settled = false; + const next = observation.next().then((result) => { + settled = true; + return result; + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(settled).toBe(false); + host.emit("idle", { type: "turn_completed", provider: "codex" }); + expect((await next).status).toBe("idle"); + } finally { + await observation.close(); + } +}); + test("lookup failure uses its error channel and never fabricates a missing-child result", async () => { const { host, observation } = await scenario(); try { diff --git a/packages/server/src/server/agent/mcp-parity.e2e.test.ts b/packages/server/src/server/agent/mcp-parity.e2e.test.ts index 635e94f429..c6f5cd5fd9 100644 --- a/packages/server/src/server/agent/mcp-parity.e2e.test.ts +++ b/packages/server/src/server/agent/mcp-parity.e2e.test.ts @@ -568,14 +568,14 @@ describe("Suite A: Core Fixes", () => { timeoutMs: 10000, label: `${outcome} notification`, check: () => { - const items = daemonHandle.daemon.agentManager - .getTimeline(parentAgentId) - .filter( - (item) => - item.type === "tool_call" && - item.detail.type === "plain_text" && - item.detail.label === "Follow-up child", - ); + const items = daemonHandle.daemon.agentManager.getTimeline(parentAgentId).filter( + (item) => + item.type === "tool_call" && + item.detail.type === "plain_text" && + item.detail.label === "Follow-up child" && + // Each case creates its own child under the same title and parent. + item.detail.text.includes(childId), + ); return items.length > 0 ? items : null; }, }); diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 0f8ac2d405..9c6e863e2e 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -5452,12 +5452,6 @@ describe("finish notifications for a child that ends its turn with work pending" return { id, session }; } const parentPrompts = () => parentClient.sessions[0]?.prompts ?? []; - /** The child's turn ended and the parent still has not heard about it. */ - async function expectParentNotNotified(childId: string) { - await vi.waitFor(() => expect(agentManager.getAgent(childId)?.lifecycle).toBe("idle")); - await new Promise((resolve) => setTimeout(resolve, 100)); - expect(parentPrompts()).toEqual([]); - } return { workdir, storage, @@ -5466,11 +5460,10 @@ describe("finish notifications for a child that ends its turn with work pending" server, createChild, parentPrompts, - expectParentNotNotified, }; } - it("tells the parent nothing until the child's autonomous final reply", async () => { + it("reports the turn end now with its background task, and again when the task wakes the child", async () => { const context = await setup(); const { workdir, storage, agentManager, server, createChild, parentPrompts } = context; try { @@ -5478,7 +5471,11 @@ describe("finish notifications for a child that ends its turn with work pending" child.session.pendingWakeup = true; child.session.publishBackgroundWork([{ id: "build", description: "npm run build" }]); child.session.finishTurn("WAITING for the build"); - await context.expectParentNotNotified(child.id); + // The task can run for as long as the child lives, so the parent hears this turn now. + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); + expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Builder) finished.`); + expect(parentPrompts()[0]).toContain("WAITING for the build"); + expect(parentPrompts()[0]).toContain("It still has background work that will wake it."); // Claude publishes the empty roster before the turn its task notification starts. child.session.publishBackgroundWork([]); @@ -5487,10 +5484,11 @@ describe("finish notifications for a child that ends its turn with work pending" child.session.pendingWakeup = false; child.session.finishTurn("FINAL: done"); - await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); - expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Builder) finished.`); - expect(parentPrompts()[0]).toContain("FINAL: done"); - expect(parseAgentMessage(parentPrompts()[0]!)).toMatchObject({ + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2)); + expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Builder) finished.`); + expect(parentPrompts()[1]).toContain("FINAL: done"); + expect(parentPrompts()[1]).not.toContain("It still has"); + expect(parseAgentMessage(parentPrompts()[1]!)).toMatchObject({ source: { kind: "agent-notification", agentId: child.id, event: "finished" }, }); @@ -5499,13 +5497,13 @@ describe("finish notifications for a child that ends its turn with work pending" child.session.finishTurn("Unrelated later work"); await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle")); await new Promise((resolve) => setTimeout(resolve, 100)); - expect(parentPrompts()).toHaveLength(1); + expect(parentPrompts()).toHaveLength(2); } finally { await removeAgentStateDir(agentManager, storage, workdir); } }); - it("reports finished when the child's background work drains without another turn", async () => { + it("sends the final finish when the background task stops without another turn", async () => { const context = await setup(); const { workdir, storage, agentManager, server, createChild, parentPrompts } = context; try { @@ -5513,13 +5511,23 @@ describe("finish notifications for a child that ends its turn with work pending" child.session.pendingWakeup = true; child.session.publishBackgroundWork([{ id: "server", description: "dev server" }]); child.session.finishTurn("Started the dev server"); - await context.expectParentNotNotified(child.id); - - child.session.pendingWakeup = false; - child.session.publishBackgroundWork([]); await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Builder) finished.`); expect(parentPrompts()[0]).toContain("Started the dev server"); + + child.session.pendingWakeup = false; + child.session.publishBackgroundWork([]); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2)); + expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Builder) finished.`); + expect(parentPrompts()[1]).toContain("Started the dev server"); + expect(parentPrompts()[1]).not.toContain("It still has"); + + // The subscription ended there: a later turn reports nothing. + child.session.startAutonomousTurn(); + child.session.finishTurn("Unrelated later work"); + await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle")); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(parentPrompts()).toHaveLength(2); } finally { await removeAgentStateDir(agentManager, storage, workdir); } @@ -5547,7 +5555,7 @@ describe("finish notifications for a child that ends its turn with work pending" } }); - it("follows a helper that waits on its own child until the helper's final reply", async () => { + it("reports a helper's turn end while it waits on its own child, then its final reply", async () => { const context = await setup(); const { workdir, storage, agentManager, server, createChild, parentPrompts } = context; try { @@ -5566,7 +5574,9 @@ describe("finish notifications for a child that ends its turn with work pending" ); const sub = await createChild(helperServer, "Sub helper"); helper.session.finishTurn("Waiting for my helper"); - await context.expectParentNotNotified(helper.id); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); + expect(parentPrompts()[0]).toContain(`Agent ${helper.id} (Helper) finished.`); + expect(parentPrompts()[0]).toContain("It still has agents it is waiting on."); sub.session.finishTurn("SUB RESULT"); // The sub helper's finish starts the helper's next turn. @@ -5575,9 +5585,10 @@ describe("finish notifications for a child that ends its turn with work pending" await vi.waitFor(() => expect(agentManager.getAgent(helper.id)?.lifecycle).toBe("running")); helper.session.finishTurn("HELPER FINAL"); - await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); - expect(parentPrompts()[0]).toContain(`Agent ${helper.id} (Helper) finished.`); - expect(parentPrompts()[0]).toContain("HELPER FINAL"); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2)); + expect(parentPrompts()[1]).toContain(`Agent ${helper.id} (Helper) finished.`); + expect(parentPrompts()[1]).toContain("HELPER FINAL"); + expect(parentPrompts()[1]).not.toContain("It still has"); } finally { await removeAgentStateDir(agentManager, storage, workdir); } @@ -5590,14 +5601,15 @@ describe("finish notifications for a child that ends its turn with work pending" const child = await createChild(server, "Planner"); child.session.pendingWakeup = true; child.session.finishTurn("Waiting for research"); - await context.expectParentNotNotified(child.id); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); + expect(parentPrompts()[0]).toContain("Waiting for research"); child.session.startAutonomousTurn(); child.session.pendingWakeup = false; child.session.requestPermission("plan-approval"); - await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1)); - expect(parentPrompts()[0]).toContain("needs permission"); - expect(parentPrompts()[0]).toContain("plan-approval"); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2)); + expect(parentPrompts()[1]).toContain("needs permission"); + expect(parentPrompts()[1]).toContain("plan-approval"); await invokeToolWithParsedInput(registeredTool(server, "respond_to_permission"), { agentId: child.id, @@ -5605,9 +5617,9 @@ describe("finish notifications for a child that ends its turn with work pending" response: { behavior: "allow" }, }); child.session.finishTurn("Plan executed"); - await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2)); - expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Planner) finished.`); - expect(parentPrompts()[1]).toContain("Plan executed"); + await vi.waitFor(() => expect(parentPrompts()).toHaveLength(3)); + expect(parentPrompts()[2]).toContain(`Agent ${child.id} (Planner) finished.`); + expect(parentPrompts()[2]).toContain("Plan executed"); } finally { await removeAgentStateDir(agentManager, storage, workdir); } diff --git a/packages/server/src/server/daemon-e2e/claude-finish-notification-background-wake.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/claude-finish-notification-background-wake.real.e2e.test.ts index e48b65a977..312edf2c13 100644 --- a/packages/server/src/server/daemon-e2e/claude-finish-notification-background-wake.real.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/claude-finish-notification-background-wake.real.e2e.test.ts @@ -43,7 +43,7 @@ describe("daemon E2E (real claude) - finish notification across a background wak if (!canRun) context.skip(); }); - test("the caller hears nothing until the child's autonomous final reply", async () => { + test("the caller hears the turn that started the task, then the autonomous final reply", async () => { const logger = pino({ level: "silent" }); const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-claude-finish-wake-")); const callerPrompts: string[] = []; @@ -85,21 +85,26 @@ describe("daemon E2E (real claude) - finish notification across a background wak ].join(" "), }); - await vi.waitFor(() => expect(callerPrompts).toHaveLength(1), { + await vi.waitFor(() => expect(callerPrompts).toHaveLength(2), { timeout: 360_000, interval: 250, }); - // The turn that replied SPAWNED ended with the background task still running: no notice. - const final = parseAgentMessage(callerPrompts[0]!); - expect(final.source).toMatchObject({ - kind: "agent-notification", - agentId: childId, - event: "finished", - }); - expect(final.text).toContain("Background child) finished."); - expect(final.text).toContain(token); + const [spawned, final] = callerPrompts.map((prompt) => parseAgentMessage(prompt)!); + // The turn that replied SPAWNED ends with the background task still running: it reports now + // and names the pending work, and the subscription stays until the task wakes the child. + for (const notice of [spawned, final]) + expect(notice.source).toMatchObject({ + kind: "agent-notification", + agentId: childId, + event: "finished", + }); + expect(spawned!.text).toContain("Background child) finished."); + expect(spawned!.text).toContain("SPAWNED"); + expect(spawned!.text).toContain("It still has background work that will wake it."); + expect(final!.text).not.toContain("It still has"); + expect(final!.text).toContain(token); expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("idle"); - expect(callerPrompts).toHaveLength(1); + expect(callerPrompts).toHaveLength(2); } finally { await client.close(); await daemon.close();