Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 25011369e1 Overlap the workspace rebuilds again in the provider subagent test
Both events in "overlapping workspace rebuilds publish the newest
provider subagent status" went through the parent's agent update queue
after the snapshot gating, so the rebuilds ran in order and the test no
longer exercised the per-workspace ordering. The first event is now a
progress update, which takes the direct workspace update path, as it
does in production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:32:49 +00:00
paseo-bot[bot]andClaude Opus 5.5 bab16c6d09 Keep the running subagent count across app relaunches
The app's offline directory cache stored backgroundWork but not
runningProviderSubagents, so after a relaunch a restored agent had no
count until its directory entry changed, and closing its tab archived it
without asking. The cache now stores the field.

The daemon re-sent the parent snapshot on every provider subagent update,
including progress subtitles. The subagent store now marks whether an
upsert or remove started or stopped a running child, and the session
re-sends the parent snapshot only then. Other updates send the workspace
update as before.

The e2e test drives the child's completion from the test through a fake
provider hook instead of a 500 ms timer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:24:14 +00:00
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
19 changed files with 371 additions and 41 deletions
@@ -578,6 +578,30 @@ describe("ReplicaCache", () => {
expect(restored.agents.get("visible")?.background).toBe(false);
});
it("keeps an agent's background work and running provider subagents across cache reopen", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const parent = {
...agent("parent"),
backgroundWork: { count: 2 },
runningProviderSubagents: { count: 1 },
};
const quiet = agent("quiet");
writer.commitDirectoryMutations(SERVER_ID, [
{ kind: "agent", type: "upsert", id: parent.id, value: parent },
{ kind: "agent", type: "upsert", id: quiet.id, value: quiet },
]);
await writer.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.agents.get("parent")).toMatchObject({
backgroundWork: { count: 2 },
runningProviderSubagents: { count: 1 },
});
expect(restored.agents.get("quiet")?.runningProviderSubagents).toBeUndefined();
});
it("round-trips identified and anonymous open turns without changing protocol status", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -237,6 +237,7 @@ const StoredAgentSnapshotSchema = z.strictObject({
lastUserMessageAt: IsoDateSchema.nullable(),
status: AgentStatusSchema,
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
activeTurn: z
.strictObject({
turnId: z.string(),
@@ -693,6 +694,7 @@ function serializeAgent(agent: Agent): StoredAgent {
...(agent.background ? { background: true } : {}),
requiresAttention: agent.requiresAttention ?? false,
backgroundWork: agent.backgroundWork,
runningProviderSubagents: agent.runningProviderSubagents,
attentionReason: agent.attentionReason ?? null,
attentionTimestamp: agent.attentionTimestamp?.toISOString() ?? null,
archivedAt: agent.archivedAt?.toISOString() ?? null,
@@ -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(),
@@ -5694,6 +5694,7 @@ test("hydrateTimelineFromProvider restores and broadcasts provider children from
id: "restored-child",
parentAgentId: snapshot.id,
}),
runningCountChanged: false,
},
});
});
@@ -5738,6 +5739,7 @@ test("force provider hydration removes children absent from current history", as
type: "remove",
parentAgentId: snapshot.id,
subagentId: "removed-by-rewind",
runningCountChanged: false,
},
});
});
@@ -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
);
}
@@ -54,12 +54,61 @@ describe("ProviderSubagentStore", () => {
]);
expect(subagents.list("parent-b")[0]).toMatchObject({ provider: "claude", title: "Review" });
expect(subagents.deleteParent("parent-a")).toEqual([
{ type: "remove", parentAgentId: "parent-a", subagentId: "child-1" },
{
type: "remove",
parentAgentId: "parent-a",
subagentId: "child-1",
runningCountChanged: false,
},
]);
expect(subagents.list("parent-a")).toEqual([]);
expect(subagents.list("parent-b")).toHaveLength(1);
});
test("marks the changes that start or stop one of the parent's running children", () => {
const subagents = new ProviderSubagentStore();
const runningCountChanged = (event: ReturnType<ProviderSubagentStore["apply"]>) =>
event.type === "timeline" ? null : event.runningCountChanged;
const started = subagents.apply("parent-a", "claude", {
type: "upsert",
id: "child-1",
status: "running",
});
const progressed = subagents.apply("parent-a", "claude", {
type: "upsert",
id: "child-1",
subtitle: "Reading files",
});
const finished = subagents.apply("parent-a", "claude", {
type: "upsert",
id: "child-1",
status: "completed",
});
const finishedRemoved = subagents.apply("parent-a", "claude", {
type: "remove",
id: "child-1",
});
subagents.apply("parent-a", "claude", { type: "upsert", id: "child-2", status: "running" });
const runningRemoved = subagents.apply("parent-a", "claude", { type: "remove", id: "child-2" });
const recorded = subagents.apply("parent-a", "claude", {
type: "upsert",
id: "child-3",
status: "completed",
});
subagents.apply("parent-a", "claude", { type: "upsert", id: "child-4", status: "running" });
expect(
[started, progressed, finished, finishedRemoved, runningRemoved, recorded].map(
runningCountChanged,
),
).toEqual([true, false, true, false, true, false]);
expect(subagents.deleteParent("parent-a")).toEqual([
expect.objectContaining({ subagentId: "child-3", runningCountChanged: false }),
expect.objectContaining({ subagentId: "child-4", runningCountChanged: true }),
]);
});
test("limits oversized provider child tool output before storage", () => {
const subagents = new ProviderSubagentStore();
const output = "x".repeat(70 * 1024);
@@ -50,8 +50,12 @@ export type ProviderSubagentInputEvent =
}
| { type: "remove"; id: string };
/**
* `runningCountChanged` says whether the change started or stopped one of the parent's running
* children, which is what the parent agent's snapshot reports.
*/
export type ProviderSubagentStoreEvent =
| { type: "upsert"; subagent: ProviderSubagentDescriptor }
| { type: "upsert"; subagent: ProviderSubagentDescriptor; runningCountChanged: boolean }
| {
type: "timeline";
parentAgentId: string;
@@ -60,7 +64,7 @@ export type ProviderSubagentStoreEvent =
row: AgentTimelineRow;
epoch: string;
}
| { type: "remove"; parentAgentId: string; subagentId: string };
| { type: "remove"; parentAgentId: string; subagentId: string; runningCountChanged: boolean };
function storeKey(parentAgentId: string, subagentId: string): string {
return `${parentAgentId}\0${subagentId}`;
@@ -86,9 +90,15 @@ export class ProviderSubagentStore {
): ProviderSubagentStoreEvent {
const key = storeKey(parentAgentId, event.id);
if (event.type === "remove") {
const removed = this.descriptors.get(key);
this.descriptors.delete(key);
this.timelines.delete(key);
return { type: "remove", parentAgentId, subagentId: event.id };
return {
type: "remove",
parentAgentId,
subagentId: event.id,
runningCountChanged: removed?.status === "running",
};
}
if (event.type === "timeline") {
@@ -128,7 +138,11 @@ export class ProviderSubagentStore {
parentSubagentId: stickyField(event.parentSubagentId, previous?.parentSubagentId),
};
this.descriptors.set(key, subagent);
return { type: "upsert", subagent };
return {
type: "upsert",
subagent,
runningCountChanged: (previous?.status === "running") !== (subagent.status === "running"),
};
}
list(parentAgentId: string): ProviderSubagentDescriptor[] {
@@ -137,6 +151,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()];
}
@@ -159,7 +181,12 @@ export class ProviderSubagentStore {
const key = storeKey(parentAgentId, subagent.id);
this.descriptors.delete(key);
this.timelines.delete(key);
events.push({ type: "remove", parentAgentId, subagentId: subagent.id });
events.push({
type: "remove",
parentAgentId,
subagentId: subagent.id,
runningCountChanged: subagent.status === "running",
});
}
return events;
}
@@ -0,0 +1,64 @@
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 type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
let ctx: DaemonTestContext;
let cwd: string;
let emitProviderEvent: ((event: AgentStreamEvent) => Promise<void>) | null;
beforeEach(async () => {
emitProviderEvent = null;
ctx = await createDaemonTestContext({
agentClients: createTestAgentClients({
onSession: (session) => {
emitProviderEvent = session.emit;
},
}),
});
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");
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.
if (!emitProviderEvent) throw new Error("The fake provider session did not start");
await emitProviderEvent({
type: "provider_subagent",
provider: "codex",
event: { type: "upsert", id: "fixture-child", status: "completed" },
});
await expect
.poll(
() => {
const latest = updates.findLast((update) => update.id === agent.id);
return latest ? { status: latest.status, running: latest.runningProviderSubagents } : null;
},
{ timeout: 10_000 },
)
.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,
}),
+22 -20
View File
@@ -2258,11 +2258,28 @@ 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;
if (event.type !== "timeline" && parent) {
// The parent's snapshot carries its running subagent count, and forwarding it also
// refreshes the parent's workspace.
if (event.runningCountChanged) void this.agentUpdates.forwardLiveAgent(parent);
else this.emitProviderSubagentWorkspaceUpdate(parent);
}
this.forwardProviderSubagentUpdate(event);
}
private emitProviderSubagentWorkspaceUpdate(parent: ManagedAgent): void {
const workspaceId = parent.workspaceId;
if (!workspaceId) return;
void this.emitWorkspaceUpdateForWorkspaceId(workspaceId).catch((error) => {
this.sessionLogger.error(
{ err: error, parentAgentId: parent.id, workspaceId },
"Failed to emit provider subagent workspace update",
);
});
}
private forwardBackgroundWork(
event: Extract<AgentManagerEvent, { type: "background_work" }>,
): void {
@@ -2275,24 +2292,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 +2307,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;
@@ -8766,7 +8766,12 @@ test("overlapping workspace rebuilds publish the newest provider subagent status
subtitle: null,
};
providerSubagents.push(runningSubagent);
listener?.({ type: "provider_subagent", event: { type: "upsert", subagent: runningSubagent } });
listener?.({
type: "provider_subagent",
// A progress update: it goes straight to the workspace update, so the completion's rebuild
// below overlaps it.
event: { type: "upsert", subagent: runningSubagent, runningCountChanged: false },
});
await firstBuildStarted.promise;
const completedSubagent = {
@@ -8775,7 +8780,10 @@ test("overlapping workspace rebuilds publish the newest provider subagent status
updatedAt: "2026-08-01T10:02:00.000Z",
};
providerSubagents[0] = completedSubagent;
listener?.({ type: "provider_subagent", event: { type: "upsert", subagent: completedSubagent } });
listener?.({
type: "provider_subagent",
event: { type: "upsert", subagent: completedSubagent, runningCountChanged: true },
});
await waitForImmediate();
releaseFirstBuild.resolve();
await vi.waitFor(() => expect(buildCount).toBe(2));
@@ -8787,6 +8795,92 @@ test("overlapping workspace rebuilds publish the newest provider subagent status
expect(statuses).toEqual(["running", "done"]);
});
test("a provider subagent update re-sends its parent's snapshot only when the running count changes", async () => {
const emitted: SessionOutboundMessage[] = [];
const parent = makeManagedAgent({
id: "provider-parent",
cwd: REPO_CWD,
workspaceId: "ws-repo-running",
lifecycle: "idle",
updatedAt: "2026-08-01T10:00:00.000Z",
}) as unknown as ManagedAgent;
let listener: ((event: AgentManagerEvent) => void) | null = null;
const session = asTestSession(
createSessionForWorkspaceTests({
onMessage: (message) => emitted.push(message),
agentStorage: { listAll: async () => [] },
agentManager: {
subscribe: (nextListener: (event: AgentManagerEvent) => void) => {
listener = nextListener;
return () => {};
},
listAgents: () => [parent],
listProviderSubagentActivity: () => [],
getAgent: (agentId: string) => (agentId === parent.id ? parent : null),
},
}),
);
const project = createPersistedProjectRecord({
projectId: "proj-1",
rootPath: REPO_CWD,
kind: "git",
displayName: "repo",
createdAt: "2026-03-01T12:00:00.000Z",
updatedAt: "2026-03-01T12:00:00.000Z",
});
const workspace = createPersistedWorkspaceRecord({
workspaceId: "ws-repo-running",
projectId: project.projectId,
cwd: REPO_CWD,
kind: "local_checkout",
displayName: "repo",
createdAt: "2026-03-01T12:00:00.000Z",
updatedAt: "2026-03-01T12:00:00.000Z",
});
session.projectRegistry.get = async (id: string) => (id === project.projectId ? project : null);
session.workspaceRegistry.listAll = session.workspaceRegistry.listActive = async () => [
workspace,
];
session.workspaceRegistry.get = async (id: string) =>
id === workspace.workspaceId ? workspace : null;
await activateAgentUpdatesSubscription(session, "provider-subagent-agents", {});
const subagent: ProviderSubagentDescriptor = {
id: "native-child",
parentAgentId: parent.id,
provider: "claude",
title: "Native child",
description: null,
status: "running",
createdAt: "2026-08-01T10:01:00.000Z",
updatedAt: "2026-08-01T10:01:00.000Z",
toolCallId: null,
cwd: REPO_CWD,
subtitle: "Reading files",
};
const parentUpdates = () =>
filterByType(emitted, "agent_update").filter(
(message) => message.payload.kind === "upsert" && message.payload.agent.id === parent.id,
);
emitted.length = 0;
listener?.({
type: "provider_subagent",
event: { type: "upsert", subagent, runningCountChanged: false },
});
listener?.({
type: "provider_subagent",
event: {
type: "upsert",
subagent: { ...subagent, status: "completed" },
runningCountChanged: true,
},
});
await vi.waitFor(() => expect(parentUpdates()).not.toHaveLength(0));
await waitForImmediate();
// Only the completion changed the count, so it is the only re-sent parent snapshot.
expect(parentUpdates()).toHaveLength(1);
});
test("title-only terminal change does not build workspace descriptors or emit workspace_update", async () => {
const emitted: SessionOutboundMessage[] = [];
const cwd = mkdtempSync(path.join(tmpdir(), "paseo-session-title-"));
@@ -86,6 +86,7 @@ interface FakeAgentSessionOptions {
onInterrupt?: () => void;
beforeSetMode?: (modeId: string) => Promise<void>;
historyEvents?: readonly AgentStreamEvent[];
onSession?: TestAgentClientOptions["onSession"];
}
export interface TestAgentClientOptions {
@@ -99,6 +100,8 @@ export interface TestAgentClientOptions {
beforeSetMode?: (modeId: string) => Promise<void>;
supportsMcpServers?: boolean;
historyEvents?: readonly AgentStreamEvent[];
/** Lets a test emit provider events between turns, such as a background child finishing. */
onSession?: (session: { emit: (event: AgentStreamEvent) => Promise<void> }) => void;
}
function createDeferred<T>(): Deferred<T> {
@@ -399,6 +402,7 @@ class FakeAgentSession implements AgentSession {
this.providerName,
`${this.id}.jsonl`,
);
options.onSession?.({ emit: (event) => this.emitEvent(event) });
}
get provider() {
@@ -1318,6 +1322,7 @@ class FakeAgentClient implements AgentClient {
onInterrupt: this.options.onInterrupt,
beforeSetMode: this.options.beforeSetMode,
historyEvents: this.options.historyEvents,
onSession: this.options.onSession,
});
}
@@ -1349,6 +1354,7 @@ class FakeAgentClient implements AgentClient {
onInterrupt: this.options.onInterrupt,
beforeSetMode: this.options.beforeSetMode,
historyEvents: this.options.historyEvents,
onSession: this.options.onSession,
});
}
@@ -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);
}