Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 99ab18c473 Publish running provider subagents on the agent snapshot
The tab close asked the daemon for the agent's subagent list before
deciding, and that request resumes a released agent's provider session
only for the close to archive it. The daemon now reports how many of an
agent's provider subagents are running on its snapshot, and re-sends the
parent's snapshot when a subagent changes. The close policy reads that
field synchronously, so the request, the client cache read and the
descriptors parameter are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:48:30 +00:00
paseo-bot[bot]andClaude Opus 5.5 3e34be1228 Check the daemon's subagent list before closing an agent tab
The app only holds provider subagents for agents it has rendered or
heard about while connected. After a reload, a restored tab that was
never activated had no subagents loaded, so closing it still archived
the agent without asking while its background subagent ran. Before
deciding, the tab close now refreshes that agent's subagent list from
the daemon, and falls back to the loaded list if the request fails.

Refs #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:09:17 +00:00
paseo-bot[bot]andClaude Opus 5.5 20d7ae6cd5 Count running background subagents when closing an agent tab
Claude reports background subagents in the subagents track, not in the
agent's background work count. An agent whose turn ended while a
background subagent was still working was idle with no background work,
so closing its tab still archived it without asking and stopped the
subagent. The close-tab policy now also asks when the agent has a
running provider subagent.

Refs #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:56:50 +00:00
paseo-bot[bot]andClaude Opus 5.5 32e7df0554 Ask before closing a tab archives an agent with background work
Closing a root agent's tab archives it, and archiving stops background
work the agent left running after its turn ended, such as a background
subagent. The "Archive running agent?" confirmation only checked
status === "running", so an idle agent with background work was
archived without asking. The close-tab policy now decides whether to
confirm, and counts background work as running.

Closes #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:48:35 +00:00
14 changed files with 160 additions and 33 deletions
@@ -2003,9 +2003,8 @@ function WorkspaceScreenContent({
const agent =
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
let closePolicy = resolveCloseAgentTabPolicy(agent);
const isRunning = agent?.status === "running";
if (isRunning && closePolicy.kind === "archive-on-close") {
if (closePolicy.kind === "archive-on-close" && closePolicy.confirmArchive) {
const confirmed = await confirmDialog({
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
+1
View File
@@ -79,6 +79,7 @@ export interface Agent {
provider: AgentProvider;
status: AgentLifecycleStatus;
backgroundWork?: { count: number };
runningProviderSubagents?: { count: number };
turn: TurnLiveness;
createdAt: Date;
updatedAt: Date;
@@ -1,21 +1,48 @@
import { describe, expect, it } from "vitest";
import { resolveCloseAgentTabPolicy } from "./close-tab-policy";
function rootAgent(overrides: Partial<Parameters<typeof resolveCloseAgentTabPolicy>[0]> = {}) {
return { parentAgentId: null, status: "idle" as const, ...overrides };
}
describe("resolveCloseAgentTabPolicy", () => {
it("archives root agents when their tab closes", () => {
expect(resolveCloseAgentTabPolicy({ parentAgentId: null })).toEqual({
it("archives an idle root agent without asking", () => {
expect(resolveCloseAgentTabPolicy(rootAgent())).toEqual({
kind: "archive-on-close",
confirmArchive: false,
});
});
it("asks before archiving a running root agent", () => {
expect(resolveCloseAgentTabPolicy(rootAgent({ status: "running" }))).toEqual({
kind: "archive-on-close",
confirmArchive: true,
});
});
it("asks before archiving a root agent whose turn ended while background work still runs", () => {
expect(resolveCloseAgentTabPolicy(rootAgent({ backgroundWork: { count: 1 } }))).toEqual({
kind: "archive-on-close",
confirmArchive: true,
});
});
it("asks before archiving a root agent whose turn ended while its background subagent still runs", () => {
expect(
resolveCloseAgentTabPolicy(rootAgent({ runningProviderSubagents: { count: 1 } })),
).toEqual({ kind: "archive-on-close", confirmArchive: true });
});
it("keeps subagent tab close layout-only", () => {
expect(resolveCloseAgentTabPolicy({ parentAgentId: "parent-agent" })).toEqual({
kind: "layout-only",
});
expect(
resolveCloseAgentTabPolicy(rootAgent({ parentAgentId: "parent-agent", status: "running" })),
).toEqual({ kind: "layout-only" });
});
it("preserves the existing archive fallback when the agent is missing", () => {
expect(resolveCloseAgentTabPolicy(null)).toEqual({ kind: "archive-on-close" });
expect(resolveCloseAgentTabPolicy(undefined)).toEqual({ kind: "archive-on-close" });
expect(resolveCloseAgentTabPolicy(null)).toEqual({
kind: "archive-on-close",
confirmArchive: false,
});
});
});
+20 -3
View File
@@ -1,13 +1,30 @@
import type { Agent } from "@/stores/session-store";
export type CloseAgentTabPolicy = { kind: "archive-on-close" } | { kind: "layout-only" };
export type CloseAgentTabPolicy =
| { kind: "archive-on-close"; confirmArchive: boolean }
| { kind: "layout-only" };
type CloseTabAgent = Pick<
Agent,
"parentAgentId" | "status" | "backgroundWork" | "runningProviderSubagents"
>;
export function resolveCloseAgentTabPolicy(
agent: Pick<Agent, "parentAgentId"> | null | undefined,
agent: CloseTabAgent | null | undefined,
): CloseAgentTabPolicy {
if (agent?.parentAgentId) {
return { kind: "layout-only" };
}
return { kind: "archive-on-close" };
return { kind: "archive-on-close", confirmArchive: agent ? hasRunningWork(agent) : false };
}
// Archiving stops the agent's process, which also stops work it left running after its turn
// ended: background subagents and background shells.
function hasRunningWork(agent: CloseTabAgent): boolean {
return (
agent.status === "running" ||
(agent.backgroundWork?.count ?? 0) > 0 ||
(agent.runningProviderSubagents?.count ?? 0) > 0
);
}
@@ -72,6 +72,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
lastUserMessageAt: agent.lastUserMessageAt?.toISOString() ?? null,
status: agent.status,
backgroundWork: agent.backgroundWork,
runningProviderSubagents: agent.runningProviderSubagents,
...projectActiveTurn(agent),
capabilities: agent.capabilities,
currentModeId: agent.currentModeId,
@@ -116,6 +117,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
provider: snapshot.provider,
status: snapshot.status,
backgroundWork: snapshot.backgroundWork,
runningProviderSubagents: snapshot.runningProviderSubagents,
turn,
createdAt,
updatedAt,
+2
View File
@@ -921,6 +921,8 @@ export const AgentSnapshotPayloadSchema = z.object({
lastUserMessageAt: z.string().nullable(),
status: AgentStatusSchema,
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
/** Provider subagents of this agent still running. Absent when none run or on older daemons. */
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
activeTurn: AgentActiveTurnPayloadSchema.nullable().optional(),
capabilities: AgentCapabilityFlagsSchema,
currentModeId: z.string().nullable(),
@@ -1456,6 +1456,12 @@ export class AgentManager {
return this.backgroundWork.summary(agentId);
}
/** Undefined when none of the agent's provider subagents is running. */
getRunningProviderSubagentSummary(agentId: string): { count: number } | undefined {
const count = this.providerSubagents.countRunning(agentId);
return count > 0 ? { count } : undefined;
}
private clearBackgroundWork(agentId: string): void {
const items = this.backgroundWork.clear(agentId);
if (items) this.dispatch({ type: "background_work", agentId, items });
@@ -2132,7 +2138,7 @@ export class AgentManager {
!this.foregroundMutationTails.has(agent.id) &&
!this.replacementMutationTails.has(agent.id) &&
!this.sessionEventTails.has(agent.id) &&
!this.providerSubagents.list(agent.id).some((child) => child.status === "running")
this.providerSubagents.countRunning(agent.id) === 0
);
}
@@ -137,6 +137,14 @@ export class ProviderSubagentStore {
.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
}
countRunning(parentAgentId: string): number {
let count = 0;
for (const subagent of this.descriptors.values()) {
if (subagent.parentAgentId === parentAgentId && subagent.status === "running") count += 1;
}
return count;
}
listAll(): ProviderSubagentDescriptor[] {
return [...this.descriptors.values()];
}
@@ -0,0 +1,45 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, expect, test } from "vitest";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
let ctx: DaemonTestContext;
let cwd: string;
beforeEach(async () => {
ctx = await createDaemonTestContext();
cwd = mkdtempSync(path.join(tmpdir(), "running-provider-subagents-"));
});
afterEach(async () => {
await ctx.cleanup();
rmSync(cwd, { recursive: true, force: true });
}, 30_000);
test("an idle agent's snapshot reports the provider subagent it left running until it finishes", async () => {
const updates: AgentSnapshotPayload[] = [];
ctx.client.subscribeRawMessages((message) => {
if (message.type === "agent_update" && message.payload.kind === "upsert") {
updates.push(message.payload.agent);
}
});
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
await ctx.client.sendMessage(agent.id, "Emit a provider child that outlives the turn");
expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
const idle = await ctx.client.fetchAgent({ agentId: agent.id });
expect(idle?.agent).toMatchObject({ status: "idle", runningProviderSubagents: { count: 1 } });
// The child finishes after the turn: subscribers get a snapshot without the count.
await expect
.poll(() => {
const latest = updates.findLast((update) => update.id === agent.id);
return latest ? { status: latest.status, running: latest.runningProviderSubagents } : null;
})
.toEqual({ status: "idle", running: undefined });
const finished = await ctx.client.fetchAgent({ agentId: agent.id });
expect(finished?.agent.runningProviderSubagents).toBeUndefined();
}, 60_000);
@@ -412,6 +412,7 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session {
listAgents: vi.fn(() => []),
listProviderSubagentActivity: vi.fn(() => []),
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
subscribe: vi.fn(() => () => {}),
...options.agentManager,
}),
+8 -20
View File
@@ -2258,8 +2258,11 @@ export class Session {
private forwardProviderSubagent(event: ProviderSubagentManagerEvent): void {
const parentAgentId =
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
if (this.agentManager.getAgent(parentAgentId)?.internal) return;
this.emitProviderSubagentWorkspaceUpdate(event);
const parent = this.agentManager.getAgent(parentAgentId);
if (parent?.internal) return;
// The parent's snapshot carries its running subagent count, and forwarding it also
// refreshes the parent's workspace.
if (event.type !== "timeline" && parent) void this.agentUpdates.forwardLiveAgent(parent);
this.forwardProviderSubagentUpdate(event);
}
@@ -2275,24 +2278,6 @@ export class Session {
if (agent) void this.agentUpdates.forwardLiveAgent(agent);
}
private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void {
if (event.type === "timeline") {
return;
}
const parentAgentId =
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
const parent = this.agentManager.getAgent(parentAgentId);
if (!parent?.workspaceId) {
return;
}
void this.emitWorkspaceUpdateForWorkspaceId(parent.workspaceId).catch((error) => {
this.sessionLogger.error(
{ err: error, parentAgentId, workspaceId: parent.workspaceId },
"Failed to emit provider subagent workspace update",
);
});
}
private buildAgentStreamPayload(
event: Extract<AgentManagerEvent, { type: "agent_stream" }>,
serializedEvent: Extract<SessionOutboundMessage, { type: "agent_stream" }>["payload"]["event"],
@@ -2308,6 +2293,9 @@ export class Session {
private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise<AgentSnapshotPayload> {
payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id);
payload.runningProviderSubagents = this.agentManager.getRunningProviderSubagentSummary(
payload.id,
);
const storedRecord = await this.agentStorage.get(payload.id);
payload.title = storedRecord?.title ?? null;
payload.archivedAt = storedRecord?.archivedAt ?? null;
@@ -589,6 +589,27 @@ class FakeAgentSession implements AgentSession {
});
}
/**
* A provider child that keeps running after the turn completes, then finishes on its own a
* moment later, the way a Claude background subagent does.
*/
private async emitProviderChildOutlivingTurn(): Promise<void> {
const child = (status: "running" | "completed"): AgentStreamEvent => ({
type: "provider_subagent",
provider: this.providerName,
event: { type: "upsert", id: "outliving-child", title: "Outliving child", status },
});
await this.emitEvent(child("running"));
await this.emitEvent({
type: "turn_completed",
provider: this.providerName,
usage: { inputTokens: 1, outputTokens: 1 },
});
setTimeout(() => {
this.emitEvent(child("completed")).catch(() => undefined);
}, 500);
}
private async emitStressTurn(stress: { count: number; coalesced: boolean }): Promise<void> {
for (let index = 0; index < stress.count; index += 1) {
const stressUpdate: AgentStreamEvent = {
@@ -832,6 +853,11 @@ class FakeAgentSession implements AgentSession {
this.notifySubscribers(child);
}
if (textPrompt === "Emit a provider child that outlives the turn") {
await this.emitProviderChildOutlivingTurn();
return;
}
if (textPrompt === "Start background work") {
await this.emitBackgroundWorkTurn();
return;
@@ -39,6 +39,7 @@ export function asAgentManager(stub: {
getRetiredInternalAgent: () => null,
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
...stub,
});
}
@@ -118,6 +118,10 @@ class InMemoryAgentManager {
return undefined;
}
getRunningProviderSubagentSummary() {
return undefined;
}
fetchTimeline(_agentId: string, options?: AgentTimelineFetchOptions) {
return this.timeline.fetch("agent-1", options);
}