Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 34 additions & 16 deletions src/app/AppShell.navigation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4350,38 +4350,56 @@ describe("AppShell global navigation", () => {
).not.toBeInTheDocument();
});

it("returns to agent builder mode after going back then forward", async () => {
it("discards an untouched agent draft when navigating back, without prompting", async () => {
const user = userEvent.setup();
// The placeholder really exists on disk: the backend lists it and it
// reads back unchanged.
const placeholder = {
type: "agent",
path: "/Users/test/.agents/agents/untitled-agent-created-session.md",
name: "Untitled agent created-sess",
description: "Draft",
content: "Draft in progress.",
global: true,
writable: true,
properties: { draft: true, builderSessionId: "created-session" },
};
mockListPersonaSources.mockResolvedValue([placeholder]);
mockReadAgentSourceFile.mockResolvedValue(placeholder);
// Once deleted, the file is no longer listed or readable.
mockDeletePersonaSource.mockImplementation(async () => {
mockListPersonaSources.mockResolvedValue([]);
mockReadAgentSourceFile.mockRejectedValue(new Error("not found"));
});
renderAppShell();

await user.click(screen.getByRole("button", { name: "Sidebar agents" }));
await user.click(screen.getByRole("button", { name: "Create agent" }));
await waitFor(() => {
expect(screen.getByTestId("active-view")).toHaveTextContent("chat");
});
await waitFor(() => {
expect(useChatSessionStore.getState().getActiveSession()).toMatchObject({
id: "created-session",
intent: "build-agent",
});
});
await waitForCreatedAgentBuilderTarget();

// Nothing was typed or edited, so leaving is silent: no "save this
// draft?" prompt, and the placeholder file and its builder state are
// gone rather than lingering as an untitled draft.
await user.click(screen.getByRole("button", { name: "Back" }));
await waitFor(() => {
expect(screen.getByTestId("active-view")).toHaveTextContent("agents");
});

await user.click(screen.getByRole("button", { name: "Forward" }));
expect(
screen.queryByText("Save this agent draft?"),
).not.toBeInTheDocument();
await waitFor(() => {
expect(screen.getByTestId("active-view")).toHaveTextContent("chat");
expect(mockDeletePersonaSource).toHaveBeenCalledWith(
"/Users/test/.agents/agents/untitled-agent-created-session.md",
);
});
await waitFor(() => {
expect(useChatSessionStore.getState().getActiveSession()).toMatchObject({
id: "created-session",
intent: "build-agent",
targetAgentPath:
"/Users/test/.agents/agents/untitled-agent-created-session.md",
});
const session = useChatSessionStore
.getState()
.getSession("created-session");
expect(session?.intent ?? null).toBeNull();
});
});

Expand Down
49 changes: 30 additions & 19 deletions src/features/agents/capabilities/AgentBuilderCapability.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import type { ChatSession } from "@/features/chat/stores/chatSessionStore";
import { useChatSessionStore } from "@/features/chat/stores/chatSessionStore";
import {
agentSourceToPersona,
listPersonas,
listAgentGallery,
type AgentSourceEntry,
} from "@/shared/api/agents";

Expand Down Expand Up @@ -51,37 +51,48 @@ export function AgentBuilderCapability({
const { t } = useTranslation("agents");
const patchSession = useChatSessionStore((state) => state.patchSession);

const refreshPersonas = useCallback(async () => {
const personas = await listPersonas();
useAgentStore.getState().setPersonas(personas);
}, []);

const completeBuilder = useCallback(
(source: AgentSourceEntry, refreshErrorMessage: string) => {
clearBuilderSessionState(session.id);

// Promotion is the durable source of truth. Seed the store immediately
// so the destination profile exists even if the follow-up disk refresh
// fails or has not observed the promoted source yet.
// fails or has not observed the promoted source yet. Running the writes
// as a gallery mutation fences out any disk refresh that started before
// the promotion and would otherwise repaint the draft card.
const promotedPersona = agentSourceToPersona(source);
const agentStore = useAgentStore.getState();
const existingPersona = agentStore.personas.find(
(persona) => persona.id === promotedPersona.id,
);
if (existingPersona) {
agentStore.updatePersona(promotedPersona.id, promotedPersona);
} else {
agentStore.addPersona(promotedPersona);
}
const seeded = agentStore.mutateGallery(() => {
const current = useAgentStore.getState();
const existingPersona = current.personas.find(
(persona) => persona.id === promotedPersona.id,
);
if (existingPersona) {
current.updatePersona(promotedPersona.id, promotedPersona);
} else {
current.addPersona(promotedPersona);
}
// The draft just became this agent; drop its card without waiting
// for the disk refresh so the gallery never shows both at once.
for (const draft of current.draftSources) {
if (draft.properties?.builderSessionId === session.id) {

@johnmatthewtennant johnmatthewtennant Aug 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 An orphan draft reopened without its original chat gets a new session ID while its frontmatter can retain the vanished ID. Promotion then misses the original draft in this loop, so the store temporarily retains both it and the promoted persona—and retains it indefinitely if refresh fails. The optimistic removal is keyed only by the current session ID rather than the promoted draft path.

current.removeDraftSource(draft.path);
}
}
});

onDraftPromoted?.(source);
onAgentBuilderCompleted?.(promotedPersona.id);

void refreshPersonas().catch((error) => {
console.error(refreshErrorMessage, error);
});
// The refresh must start after the mutation releases the fence, or the
// fence would (correctly) reject it as having begun mid-mutation.
void seeded
.then(() => agentStore.refreshGallery(listAgentGallery))

@johnmatthewtennant johnmatthewtennant Aug 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 promotePersonaSource can create the destination while failing to remove the original draft. This immediate refresh then lists and re-adds that orphan beside the promoted agent, restoring the duplicate card after the optimistic mutation removed it.

.catch((error) => {
console.error(refreshErrorMessage, error);
});
},
[onAgentBuilderCompleted, onDraftPromoted, refreshPersonas, session.id],
[onAgentBuilderCompleted, onDraftPromoted, session.id],
);

const handleDraftPromoted = useCallback(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { act, fireEvent, screen } from "@testing-library/react";
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "@/test/render";

Expand All @@ -15,7 +15,7 @@ const apiMocks = vi.hoisted(() => ({
listPersonaSources: vi.fn(),
readAgentSourceFile: vi.fn(),
updatePersonaSource: vi.fn(),
listPersonas: vi.fn(),
listAgentGallery: vi.fn(),
hasRealAgentDescription: (description: string | null | undefined) => {
const normalized = description?.trim().toLowerCase();
return Boolean(
Expand All @@ -24,7 +24,13 @@ const apiMocks = vi.hoisted(() => ({
},
}));

vi.mock("@/shared/api/agents", () => apiMocks);
vi.mock("@/shared/api/agents", async (importOriginal) => ({
...apiMocks,
// Pure mapper; the real one keeps the promotion path honest.
agentSourceToPersona: (
await importOriginal<typeof import("@/shared/api/agents")>()
).agentSourceToPersona,
}));

vi.mock("@/features/agents/lib/agentTelemetry", () => telemetryMocks);

Expand Down Expand Up @@ -62,6 +68,7 @@ import {
type ChatSession,
} from "@/features/chat/stores/chatSessionStore";
import type { AgentSourceEntry } from "@/shared/api/agents";
import type { Persona } from "@/shared/types/agents";

const existingAgentSource: AgentSourceEntry = {
type: "agent",
Expand Down Expand Up @@ -103,7 +110,7 @@ describe("AgentBuilderCapability keep-save telemetry", () => {
apiMocks.listPersonaSources.mockReset();
apiMocks.readAgentSourceFile.mockReset();
apiMocks.updatePersonaSource.mockReset();
apiMocks.listPersonas.mockReset();
apiMocks.listAgentGallery.mockReset();
apiMocks.listPersonaSources.mockResolvedValue([existingAgentSource]);
apiMocks.readAgentSourceFile.mockImplementation(
async (_path: string, fallback?: AgentSourceEntry) =>
Expand All @@ -121,11 +128,14 @@ describe("AgentBuilderCapability keep-save telemetry", () => {
},
}),
);
apiMocks.listPersonas.mockResolvedValue([]);
apiMocks.listAgentGallery.mockResolvedValue({ personas: [], drafts: [] });
resetAgentBuilderSourceLifecycleForTests();
useAgentStore.setState({
personas: [],
personasLoading: false,
draftSources: [],
galleryRevision: 0,
galleryMutationsInFlight: 0,
providers: [],
});
useChatSessionStore.setState({
Expand Down Expand Up @@ -173,4 +183,40 @@ describe("AgentBuilderCapability keep-save telemetry", () => {
expect(telemetryMocks.trackAgentEditCompleted).not.toHaveBeenCalled();
expect(telemetryMocks.trackAgentCreateCompleted).not.toHaveBeenCalled();
});

it("applies the disk refresh that follows a save, through the real gallery fence", async () => {
// The optimistic store seed runs as a gallery mutation; the follow-up
// listing must start after that mutation releases the fence, or the fence
// would reject it and the gallery would stay on the optimistic copy.
const fromDisk: Persona = {
id: existingAgentSource.path,
displayName: "Code Reviewer (as listed on disk)",
systemPrompt: existingAgentSource.content,
isBuiltin: false,
writable: true,
createdAt: "2026-06-09T00:00:00.000Z",
updatedAt: "2026-06-09T00:00:00.000Z",
};
apiMocks.listAgentGallery.mockResolvedValue({
personas: [fromDisk],
drafts: [],
});

renderWithProviders(
<AgentBuilderCapability
session={builderSession}
onAgentBuilderCompleted={vi.fn()}
/>,
);
await screen.findByLabelText(/agent name/i);
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));

await waitFor(() => {
expect(apiMocks.listAgentGallery).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(useAgentStore.getState().personas).toEqual([fromDisk]);
});
expect(useAgentStore.getState().galleryMutationsInFlight).toBe(0);
});
});
Loading