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
51 changes: 34 additions & 17 deletions src/app/AppShell.navigation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import type { Message } from "@/shared/types/messages";
import type { GitState } from "@/shared/types/git";
import { setMultiWorkspaceEnabled } from "@/features/workspaces/multiWorkspacePreference";
import { OPEN_SETTINGS_EVENT } from "@/features/settings/lib/settingsEvents";
import { useVoiceConversationStore } from "@/features/voice-conversation/stores/voiceConversationStore";
import { SHORTCUT_PREFERENCES_STORAGE_KEY } from "@/features/shortcuts/lib/shortcutRegistry";
import { useShortcutsDialogStore } from "@/features/shortcuts/stores/shortcutsDialogStore";
import { useProjectStore } from "@/features/projects/stores/projectStore";
Expand Down Expand Up @@ -4341,38 +4340,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) {
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))
.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 @@ -64,6 +70,7 @@ import {
import { setExperimentEnabled } from "@/features/experiments/experimentPreferences";
import { AVATAR_COLLECTION_PAGE_EXPERIMENT_ID } from "@/features/experiments/experimentDefinitions";
import type { AgentSourceEntry } from "@/shared/api/agents";
import type { Persona } from "@/shared/types/agents";

const existingAgentSource: AgentSourceEntry = {
type: "agent",
Expand Down Expand Up @@ -105,7 +112,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 @@ -123,12 +130,15 @@ describe("AgentBuilderCapability keep-save telemetry", () => {
},
}),
);
apiMocks.listPersonas.mockResolvedValue([]);
apiMocks.listAgentGallery.mockResolvedValue({ personas: [], drafts: [] });
resetAgentBuilderSourceLifecycleForTests();
setExperimentEnabled(AVATAR_COLLECTION_PAGE_EXPERIMENT_ID, false);
useAgentStore.setState({
personas: [],
personasLoading: false,
draftSources: [],
galleryRevision: 0,
galleryMutationsInFlight: 0,
providers: [],
});
useChatSessionStore.setState({
Expand Down Expand Up @@ -176,4 +186,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