fix(settings): guard profile hydration races
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { createElement, type ReactNode } from "react";
|
||||
import { act, cleanup, renderHook } from "@testing-library/react";
|
||||
import { StateProvider, useAppStore } from "@/components/state-provider";
|
||||
@@ -28,7 +28,8 @@ function useSettingsSnapshot() {
|
||||
const agentsLoaded = useAppStore((state) => state.settingsData.agentsLoaded);
|
||||
const agentProfiles = useAppStore((state) => state.agentProfiles.items);
|
||||
const setAgentProfiles = useAppStore((state) => state.setAgentProfiles);
|
||||
return { agentsLoaded, agentProfiles, setAgentProfiles };
|
||||
const bumpAgentProfilesVersion = useAppStore((state) => state.bumpAgentProfilesVersion);
|
||||
return { agentsLoaded, agentProfiles, setAgentProfiles, bumpAgentProfilesVersion };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -43,92 +44,167 @@ afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("useSettingsData", () => {
|
||||
it("retries an empty agent list before declaring that no profiles exist", async () => {
|
||||
const profile = {
|
||||
id: "profile-1",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Default",
|
||||
cliPassthrough: false,
|
||||
};
|
||||
mocks.listAgents.mockResolvedValueOnce({ agents: [], total: 0 }).mockResolvedValueOnce({
|
||||
agents: [{ id: "agent-1", name: MOCK_AGENT_NAME, profiles: [profile] }],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(mocks.listAgents).toHaveBeenCalledTimes(2);
|
||||
expect(result.current.agentsLoaded).toBe(true);
|
||||
expect(result.current.agentProfiles[0]?.id).toBe("profile-1");
|
||||
it("retries an empty agent list before declaring that no profiles exist", async () => {
|
||||
const profile = {
|
||||
id: "profile-1",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Default",
|
||||
cliPassthrough: false,
|
||||
};
|
||||
mocks.listAgents.mockResolvedValueOnce({ agents: [], total: 0 }).mockResolvedValueOnce({
|
||||
agents: [{ id: "agent-1", name: MOCK_AGENT_NAME, profiles: [profile] }],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
it("uses the final attempt after exhausting every retry delay", async () => {
|
||||
mocks.listAgents.mockResolvedValue({ agents: [], total: 0 });
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
expect(mocks.listAgents).toHaveBeenCalledTimes(5);
|
||||
expect(result.current.agentsLoaded).toBe(true);
|
||||
expect(result.current.agentProfiles).toEqual([]);
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
it("keeps a profile created by WebSocket while the initial list request is pending", async () => {
|
||||
let resolveAgents: (response: { agents: unknown[]; total: number }) => void;
|
||||
mocks.listAgents.mockReturnValue(
|
||||
expect(mocks.listAgents).toHaveBeenCalledTimes(2);
|
||||
expect(result.current.agentsLoaded).toBe(true);
|
||||
expect(result.current.agentProfiles[0]?.id).toBe("profile-1");
|
||||
});
|
||||
|
||||
it("uses the final attempt after exhausting every retry delay", async () => {
|
||||
mocks.listAgents.mockResolvedValue({ agents: [], total: 0 });
|
||||
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
expect(mocks.listAgents).toHaveBeenCalledTimes(5);
|
||||
expect(result.current.agentsLoaded).toBe(true);
|
||||
expect(result.current.agentProfiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a profile created by WebSocket while the initial list request is pending", async () => {
|
||||
let resolveAgents: (response: { agents: unknown[]; total: number }) => void;
|
||||
mocks.listAgents
|
||||
.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
resolveAgents = resolve;
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
act(() => {
|
||||
result.current.setAgentProfiles([
|
||||
)
|
||||
.mockResolvedValue({
|
||||
agents: [
|
||||
{
|
||||
id: "profile-live",
|
||||
label: `${MOCK_AGENT_NAME} • Live profile`,
|
||||
agent_id: "agent-1",
|
||||
agent_name: MOCK_AGENT_NAME,
|
||||
cli_passthrough: false,
|
||||
inference_capable: true,
|
||||
updatedAt: "2026-08-26T18:00:01Z",
|
||||
id: "agent-1",
|
||||
name: MOCK_AGENT_NAME,
|
||||
profiles: [
|
||||
{
|
||||
id: "profile-live",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Live profile",
|
||||
cliPassthrough: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
await act(async () => {
|
||||
resolveAgents!({
|
||||
agents: [
|
||||
{
|
||||
id: "agent-1",
|
||||
name: MOCK_AGENT_NAME,
|
||||
profiles: [
|
||||
{
|
||||
id: "profile-stale",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Stale profile",
|
||||
cliPassthrough: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
await Promise.resolve();
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
expect(result.current.agentProfiles.map((profile) => profile.id)).toContain("profile-live");
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
act(() => {
|
||||
result.current.setAgentProfiles([
|
||||
{
|
||||
id: "profile-live",
|
||||
label: `${MOCK_AGENT_NAME} • Live profile`,
|
||||
agent_id: "agent-1",
|
||||
agent_name: MOCK_AGENT_NAME,
|
||||
cli_passthrough: false,
|
||||
inference_capable: true,
|
||||
updatedAt: "2026-08-26T18:00:01Z",
|
||||
},
|
||||
]);
|
||||
result.current.bumpAgentProfilesVersion();
|
||||
});
|
||||
await act(async () => {
|
||||
resolveAgents!({
|
||||
agents: [
|
||||
{
|
||||
id: "agent-1",
|
||||
name: MOCK_AGENT_NAME,
|
||||
profiles: [
|
||||
{
|
||||
id: "profile-stale",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Stale profile",
|
||||
cliPassthrough: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.agentProfiles.map((profile) => profile.id)).toEqual(["profile-live"]);
|
||||
});
|
||||
|
||||
it("drops a profile deleted by WebSocket while the initial list request is pending", async () => {
|
||||
let resolveAgents: (response: { agents: unknown[]; total: number }) => void;
|
||||
mocks.listAgents
|
||||
.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
resolveAgents = resolve;
|
||||
}),
|
||||
)
|
||||
.mockResolvedValue({
|
||||
agents: [
|
||||
{
|
||||
id: "agent-1",
|
||||
name: MOCK_AGENT_NAME,
|
||||
profiles: [
|
||||
{
|
||||
id: "profile-current",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Current profile",
|
||||
cliPassthrough: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
const { result } = renderHook(() => useSettingsSnapshot(), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
act(() => {
|
||||
result.current.setAgentProfiles([]);
|
||||
result.current.bumpAgentProfilesVersion();
|
||||
});
|
||||
await act(async () => {
|
||||
resolveAgents!({
|
||||
agents: [
|
||||
{
|
||||
id: "agent-1",
|
||||
name: MOCK_AGENT_NAME,
|
||||
profiles: [
|
||||
{
|
||||
id: "profile-deleted",
|
||||
agentDisplayName: MOCK_AGENT_NAME,
|
||||
name: "Deleted profile",
|
||||
cliPassthrough: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.agentProfiles.map((profile) => profile.id)).toEqual(["profile-current"]);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { StoreApi } from "zustand";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { listAgents, listAvailableAgents, listExecutors } from "@/lib/api";
|
||||
import {
|
||||
mergeOptionsByNewest,
|
||||
toAgentProfileOption,
|
||||
type AgentProfileOption,
|
||||
} from "@/lib/state/slices/settings/types";
|
||||
import { toAgentProfileOption, type AgentProfileOption } from "@/lib/state/slices/settings/types";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
|
||||
const AGENT_LIST_RETRY_DELAYS_MS = [100, 250, 500, 1_000] as const;
|
||||
|
||||
@@ -45,13 +43,25 @@ function applyAgentList(
|
||||
response: AgentListResponse,
|
||||
setSettingsAgents: (agents: AgentListResponse["agents"]) => void,
|
||||
setAgentProfiles: (profiles: AgentProfileOption[]) => void,
|
||||
previousProfiles: AgentProfileOption[],
|
||||
): void {
|
||||
setSettingsAgents(response.agents);
|
||||
const rebuiltProfiles = response.agents.flatMap((agent) =>
|
||||
agent.profiles.map((profile) => toAgentProfileOption(agent, profile)),
|
||||
);
|
||||
setAgentProfiles(mergeOptionsByNewest(previousProfiles, rebuiltProfiles));
|
||||
setAgentProfiles(rebuiltProfiles);
|
||||
}
|
||||
|
||||
async function refreshAgentList(
|
||||
storeApi: StoreApi<AppState>,
|
||||
setSettingsAgents: (agents: AgentListResponse["agents"]) => void,
|
||||
setAgentProfiles: (profiles: AgentProfileOption[]) => void,
|
||||
): Promise<void> {
|
||||
const profileVersion = storeApi.getState().agentProfiles.version;
|
||||
const response = await listAgentsUntilSettled();
|
||||
if (storeApi.getState().agentProfiles.version !== profileVersion) {
|
||||
return refreshAgentList(storeApi, setSettingsAgents, setAgentProfiles);
|
||||
}
|
||||
applyAgentList(response, setSettingsAgents, setAgentProfiles);
|
||||
}
|
||||
|
||||
export function useSettingsData(enabled = true) {
|
||||
@@ -84,15 +94,7 @@ export function useSettingsData(enabled = true) {
|
||||
if (!enabled) return;
|
||||
if (settingsData.agentsLoaded) return;
|
||||
if (settingsAgents.length === 0) {
|
||||
listAgentsUntilSettled()
|
||||
.then((response) =>
|
||||
applyAgentList(
|
||||
response,
|
||||
setSettingsAgents,
|
||||
setAgentProfiles,
|
||||
storeApi.getState().agentProfiles.items,
|
||||
),
|
||||
)
|
||||
refreshAgentList(storeApi, setSettingsAgents, setAgentProfiles)
|
||||
.catch(() => {
|
||||
setSettingsAgents([]);
|
||||
setAgentProfiles([]);
|
||||
@@ -142,19 +144,10 @@ export function useSettingsData(enabled = true) {
|
||||
if (!settingsData.agentsLoaded) return; // Wait for the initial agents fetch first.
|
||||
if (reconciledRef.current) return;
|
||||
reconciledRef.current = true;
|
||||
listAgentsUntilSettled()
|
||||
.then((response) =>
|
||||
applyAgentList(
|
||||
response,
|
||||
setSettingsAgents,
|
||||
setAgentProfiles,
|
||||
storeApi.getState().agentProfiles.items,
|
||||
),
|
||||
)
|
||||
.catch(() => {
|
||||
// Best-effort reconcile; keep prior (possibly stale) profiles rather
|
||||
// than wiping the dialog state on a transient error.
|
||||
});
|
||||
refreshAgentList(storeApi, setSettingsAgents, setAgentProfiles).catch(() => {
|
||||
// Best-effort reconcile; keep prior (possibly stale) profiles rather
|
||||
// than wiping the dialog state on a transient error.
|
||||
});
|
||||
}, [
|
||||
enabled,
|
||||
availableAgents.loaded,
|
||||
|
||||
@@ -201,6 +201,7 @@ describe("agent profile events", () => {
|
||||
|
||||
expect(store.getState().settingsAgents.items).toHaveLength(0);
|
||||
expect(store.getState().agentProfiles.items[0]?.inference_capable).toBe(true);
|
||||
expect(store.getState().agentProfiles.version).toBe(1);
|
||||
});
|
||||
|
||||
it("does not resurrect a deleted profile from a delayed create event", () => {
|
||||
|
||||
@@ -133,7 +133,11 @@ function handleProfileCreated(
|
||||
: item,
|
||||
);
|
||||
return {
|
||||
agentProfiles: { ...state.agentProfiles, items: nextProfiles },
|
||||
agentProfiles: {
|
||||
...state.agentProfiles,
|
||||
items: nextProfiles,
|
||||
version: state.agentProfiles.version + 1,
|
||||
},
|
||||
settingsAgents: { items: nextAgents },
|
||||
};
|
||||
}
|
||||
@@ -165,7 +169,11 @@ function handleProfileUpdated(
|
||||
: item,
|
||||
);
|
||||
return {
|
||||
agentProfiles: { ...state.agentProfiles, items: nextProfiles },
|
||||
agentProfiles: {
|
||||
...state.agentProfiles,
|
||||
items: nextProfiles,
|
||||
version: state.agentProfiles.version + 1,
|
||||
},
|
||||
settingsAgents: { items: nextAgents },
|
||||
};
|
||||
}
|
||||
@@ -200,6 +208,7 @@ function handleProfileDeleted(
|
||||
agentProfiles: {
|
||||
...state.agentProfiles,
|
||||
items: state.agentProfiles.items.filter((p) => p.id !== normalized.id),
|
||||
version: state.agentProfiles.version + 1,
|
||||
},
|
||||
settingsAgents: { items: nextAgents },
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user