Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6183: prevent agent create error flash (#7007)

Jiayuan Zhang46527a1a70cf
diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.ts
index cd44e238db..7cc227f4ba 100644
--- a/packages/core/workspace/queries.ts
+++ b/packages/core/workspace/queries.ts
@@ -1,4 +1,4 @@
-import { queryOptions } from "@tanstack/react-query";
+import { queryOptions, type QueryClient } from "@tanstack/react-query";
import { api } from "../api";
import type { Agent, Squad, Workspace } from "../types";
@@ -9,6 +9,8 @@ export const workspaceKeys = {
invitations: (wsId: string) => ["workspaces", wsId, "invitations"] as const,
myInvitations: () => ["invitations", "mine"] as const,
agents: (wsId: string) => ["workspaces", wsId, "agents"] as const,
+ agent: (wsId: string, agentId: string) =>
+ ["workspaces", wsId, "agents", "detail", agentId] as const,
squads: (wsId: string) => ["workspaces", wsId, "squads"] as const,
// Per-squad member status. Lives under the workspace key tree so
// workspace switches naturally drop the cache, and so a broad
@@ -50,6 +52,39 @@ export function agentListOptions(wsId: string) {
});
}
+export function agentDetailOptions(wsId: string, agentId: string) {
+ return queryOptions({
+ queryKey: workspaceKeys.agent(wsId, agentId),
+ queryFn: () => api.getAgent(agentId),
+ enabled: !!wsId && !!agentId,
+ retry: false,
+ });
+}
+
+/**
+ * Makes an authoritative agent response immediately visible to both agent
+ * detail and list consumers. A cold list stays cold so one agent is never
+ * mistaken for the complete workspace list.
+ */
+export function cacheAgentResponse(
+ queryClient: QueryClient,
+ wsId: string,
+ agent: Agent,
+ options: { insertIntoList?: boolean } = {},
+) {
+ queryClient.setQueryData(workspaceKeys.agent(wsId, agent.id), agent);
+ queryClient.setQueryData<Agent[]>(workspaceKeys.agents(wsId), (current) => {
+ if (!current) return current;
+ const existingIndex = current.findIndex((item) => item.id === agent.id);
+ if (existingIndex === -1) {
+ return options.insertIntoList === false ? current : [...current, agent];
+ }
+ return current.map((item, index) =>
+ index === existingIndex ? agent : item,
+ );
+ });
+}
+
export function squadListOptions(wsId: string) {
return queryOptions<Squad[]>({
queryKey: workspaceKeys.squads(wsId),
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
index 24d3b74cdd..fddaee825d 100644
--- a/packages/views/agents/components/agent-detail-page.test.tsx
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -1,8 +1,15 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { ApiError } from "@multica/core/api";
import type { Agent } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
@@ -18,7 +25,20 @@ const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
// rules (via auth + member fixtures); the tabbed body and avatar/presence
// widgets are irrelevant weight, so they're stubbed.
vi.mock("./agent-overview-pane", () => ({
- AgentOverviewPane: () => <div>agent-overview-pane</div>,
+ AgentOverviewPane: ({
+ agent,
+ onUpdate,
+ }: {
+ agent: Agent;
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+ }) => (
+ <button
+ type="button"
+ onClick={() => void onUpdate(agent.id, { model: "new-model" })}
+ >
+ update model
+ </button>
+ ),
}));
vi.mock("../../common/actor-avatar", () => ({
ActorAvatar: () => <div>actor-avatar</div>,
@@ -37,6 +57,8 @@ const currentUserRef = vi.hoisted(() => ({
}));
const mockToastError = vi.hoisted(() => vi.fn());
const mockModalOpen = vi.hoisted(() => vi.fn());
+const mockGetAgent = vi.hoisted(() => vi.fn());
+const mockUpdateAgent = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
@@ -51,6 +73,29 @@ vi.mock("@multica/core/workspace/queries", () => ({
queryKey: ["agents", wsId],
queryFn: () => Promise.resolve(agentsRef.current),
}),
+ agentDetailOptions: (wsId: string, agentId: string) => ({
+ queryKey: ["agents", wsId, "detail", agentId],
+ queryFn: () => mockGetAgent(agentId),
+ enabled: !!wsId && !!agentId,
+ retry: false,
+ }),
+ cacheAgentResponse: (
+ queryClient: QueryClient,
+ wsId: string,
+ agent: Agent,
+ options: { insertIntoList?: boolean } = {},
+ ) => {
+ queryClient.setQueryData(["agents", wsId, "detail", agent.id], agent);
+ queryClient.setQueryData<Agent[]>(["agents", wsId], (current) =>
+ current?.some((item) => item.id === agent.id)
+ ? current.map((item) => (item.id === agent.id ? agent : item))
+ : current
+ ? options.insertIntoList === false
+ ? current
+ : [...current, agent]
+ : current,
+ );
+ },
memberListOptions: (wsId: string) => ({
queryKey: ["members", wsId],
queryFn: () =>
@@ -58,7 +103,15 @@ vi.mock("@multica/core/workspace/queries", () => ({
? new Promise(() => {})
: Promise.resolve(membersRef.current),
}),
- workspaceKeys: { agents: (wsId: string) => ["agents", wsId] },
+ workspaceKeys: {
+ agents: (wsId: string) => ["agents", wsId],
+ agent: (wsId: string, agentId: string) => [
+ "agents",
+ wsId,
+ "detail",
+ agentId,
+ ],
+ },
}));
vi.mock("@multica/core/runtimes", () => ({
runtimeListOptions: (wsId: string) => ({
@@ -90,13 +143,13 @@ vi.mock("@multica/core/paths", () => ({
vi.mock("@multica/core/api", () => {
class ApiError extends Error {
status: number;
- constructor(status: number, message: string) {
+ constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
return {
- api: { getAgent: vi.fn(() => Promise.reject(new ApiError(404, "not found"))) },
+ api: { getAgent: mockGetAgent, updateAgent: mockUpdateAgent },
ApiError,
};
});
@@ -144,7 +197,7 @@ function renderPage() {
searchParams: new URLSearchParams(),
getShareableUrl: (path) => path,
};
- render(
+ const view = render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
<NavigationProvider value={navigation}>
<QueryClientProvider client={queryClient}>
@@ -153,7 +206,7 @@ function renderPage() {
</NavigationProvider>
</I18nProvider>,
);
- return { push };
+ return { push, queryClient, ...view };
}
beforeEach(() => {
@@ -162,6 +215,163 @@ beforeEach(() => {
membersRef.current = [{ user_id: "user-1", role: "member" }];
membersPendingRef.current = false;
agentsRef.current = [baseAgent];
+ mockGetAgent.mockRejectedValue(new ApiError("not found", 404, "Not Found"));
+ mockUpdateAgent.mockResolvedValue({ ...baseAgent, model: "new-model" });
+});
+
+describe("AgentDetailPage direct-detail fallback", () => {
+ it("does not fetch detail when the workspace list already has the agent", async () => {
+ renderPage();
+
+ expect(
+ await screen.findByRole("button", { name: "Assign work" }),
+ ).toBeInTheDocument();
+ expect(mockGetAgent).not.toHaveBeenCalled();
+ });
+
+ it("keeps the loading skeleton while the detail request is pending", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockImplementation(() => new Promise(() => {}));
+
+ const { container } = renderPage();
+
+ await waitFor(() => expect(mockGetAgent).toHaveBeenCalledWith("agent-1"));
+ expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
+ expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();
+ });
+
+ it("renders an agent returned by the detail endpoint", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockResolvedValue(baseAgent);
+
+ renderPage();
+
+ expect(
+ await screen.findByRole("button", { name: "Assign work" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
+ });
+
+ it("shows not found only after the detail endpoint returns 404", async () => {
+ agentsRef.current = [];
+
+ renderPage();
+
+ expect(await screen.findByText("Agent not found")).toBeInTheDocument();
+ });
+
+ it("keeps 403 distinct from not found", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockRejectedValue(
+ new ApiError("forbidden", 403, "Forbidden"),
+ );
+
+ renderPage();
+
+ expect(
+ await screen.findByText("You don't have access to this agent"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
+ });
+
+ it("shows 404 when a successful detail refetch later reports deletion", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockResolvedValueOnce(baseAgent);
+ const { queryClient } = renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+
+ mockGetAgent.mockRejectedValue(new ApiError("not found", 404, "Not Found"));
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["agents", "ws-1", "detail", "agent-1"],
+ exact: true,
+ });
+ });
+
+ expect(await screen.findByText("Agent not found")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Assign work" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows 403 when a successful detail refetch later loses access", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockResolvedValueOnce(baseAgent);
+ const { queryClient } = renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+
+ mockGetAgent.mockRejectedValue(
+ new ApiError("forbidden", 403, "Forbidden"),
+ );
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["agents", "ws-1", "detail", "agent-1"],
+ exact: true,
+ });
+ });
+
+ expect(
+ await screen.findByText("You don't have access to this agent"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Assign work" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a load failure instead of not found for transient errors", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockRejectedValue(new Error("Network request failed"));
+
+ renderPage();
+
+ expect(
+ await screen.findByText("Couldn't load this agent"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Network request failed")).toBeInTheDocument();
+ expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
+ });
+
+ it("keeps successful detail data visible through a transient refetch error", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockResolvedValueOnce(baseAgent);
+ const { queryClient } = renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+
+ mockGetAgent.mockRejectedValue(new Error("Network request failed"));
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["agents", "ws-1", "detail", "agent-1"],
+ exact: true,
+ });
+ });
+
+ expect(
+ screen.getByRole("button", { name: "Assign work" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Couldn't load this agent"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("optimistically updates a detail-only cache entry", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockResolvedValue(baseAgent);
+ mockUpdateAgent.mockImplementation(() => new Promise(() => {}));
+ const { queryClient } = renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+
+ fireEvent.click(screen.getByRole("button", { name: "update model" }));
+
+ expect(await screen.findByText("new-model")).toBeInTheDocument();
+ expect(
+ queryClient.getQueryData<Agent>([
+ "agents",
+ "ws-1",
+ "detail",
+ "agent-1",
+ ]),
+ ).toMatchObject({ model: "new-model" });
+ });
});
describe("AgentDetailPage DM button", () => {
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index ee50ffe4e7..15531a602a 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -31,7 +31,9 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useModalStore } from "@multica/core/modals";
import { useWorkspacePaths } from "@multica/core/paths";
import {
+ agentDetailOptions,
agentListOptions,
+ cacheAgentResponse,
memberListOptions,
workspaceKeys,
} from "@multica/core/workspace/queries";
@@ -88,22 +90,29 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
// The hook owns the 30s tick so the failed-window auto-clears here too.
const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
- const agent = agents.find((a) => a.id === agentId) ?? null;
- const presence: AgentPresenceDetail | null =
- agent ? presenceMap.get(agent.id) ?? null : null;
+ const listAgent = agents.find((a) => a.id === agentId) ?? null;
- // Fallback fetch: when the agent is missing from the workspace list, hit
- // GET /api/agents/{id} directly to disambiguate "doesn't exist" (404) from
- // "you can't see this private agent" (403). Only fires after the list has
- // settled, so the common path makes zero extra requests.
- const { error: detailError } = useQuery({
- queryKey: ["agent-detail-probe", wsId, agentId],
- queryFn: () => api.getAgent(agentId),
- enabled: !agentsLoading && !agent && !!agentId,
- retry: false,
+ // The list remains the zero-request common path. When it has settled
+ // without the requested agent, use the canonical detail query to resolve
+ // direct links and distinguish 403/404 from transient failures. Creation
+ // hydrates this same key, so a newly-created agent renders immediately.
+ const detailQuery = useQuery({
+ ...agentDetailOptions(wsId, agentId),
+ enabled: !agentsLoading && !listAgent && !!agentId,
});
+ const detailError = detailQuery.error;
const isForbidden =
detailError instanceof ApiError && detailError.status === 403;
+ const isNotFound =
+ detailError instanceof ApiError && detailError.status === 404;
+ // TanStack intentionally keeps successful data when a refetch fails. Do not
+ // let that stale snapshot mask a later 403/404 after access is revoked or the
+ // agent is deleted, but preserve it through transient network failures. A
+ // still-visible list response remains authoritative in either case.
+ const agent =
+ listAgent ?? (isForbidden || isNotFound ? null : detailQuery.data) ?? null;
+ const presence: AgentPresenceDetail | null =
+ agent ? presenceMap.get(agent.id) ?? null : null;
// Permission hook MUST be called unconditionally — its `agent | null`
// signature handles the not-found / loading case internally so the early
@@ -140,32 +149,52 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
? { ...data, runtime_bound: data.runtime_id.trim().length > 0 }
: data;
const queryKey = workspaceKeys.agents(wsId);
+ const detailQueryKey = workspaceKeys.agent(wsId, id);
const prevAgents = qc.getQueryData<Agent[]>(queryKey);
- const prevAgent = prevAgents?.find((a) => a.id === id);
- const prevFields: Record<string, unknown> = {};
- if (prevAgent) {
+ const prevListAgent = prevAgents?.find((a) => a.id === id);
+ const prevDetailAgent = qc.getQueryData<Agent>(detailQueryKey);
+ const previousFields = (previousAgent: Agent | undefined) => {
+ const fields: Record<string, unknown> = {};
+ if (!previousAgent) return fields;
for (const key of Object.keys(optimisticData)) {
- prevFields[key] = (prevAgent as unknown as Record<string, unknown>)[key];
+ fields[key] = (
+ previousAgent as unknown as Record<string, unknown>
+ )[key];
}
- }
+ return fields;
+ };
+ const prevListFields = previousFields(prevListAgent);
+ const prevDetailFields = previousFields(prevDetailAgent);
qc.setQueryData<Agent[]>(queryKey, (old) =>
old?.map((a) =>
a.id === id ? ({ ...a, ...optimisticData } as Agent) : a,
),
);
+ qc.setQueryData<Agent>(detailQueryKey, (old) =>
+ old ? ({ ...old, ...optimisticData } as Agent) : old,
+ );
try {
- await api.updateAgent(id, data as UpdateAgentRequest);
- qc.invalidateQueries({ queryKey });
+ const updatedAgent = await api.updateAgent(
+ id,
+ data as UpdateAgentRequest,
+ );
+ cacheAgentResponse(qc, wsId, updatedAgent, { insertIntoList: false });
+ void qc.invalidateQueries({ queryKey });
toast.success(t(($) => $.detail.agent_updated_toast));
} catch (e) {
- if (prevAgent) {
+ if (prevListAgent) {
qc.setQueryData<Agent[]>(queryKey, (old) =>
old?.map((a) =>
- a.id === id ? ({ ...a, ...prevFields } as Agent) : a,
+ a.id === id ? ({ ...a, ...prevListFields } as Agent) : a,
),
);
}
- qc.invalidateQueries({ queryKey });
+ if (prevDetailAgent) {
+ qc.setQueryData<Agent>(detailQueryKey, (old) =>
+ old ? ({ ...old, ...prevDetailFields } as Agent) : old,
+ );
+ }
+ void qc.invalidateQueries({ queryKey });
toast.error(e instanceof Error ? e.message : t(($) => $.detail.update_failed_toast));
throw e;
}
@@ -192,7 +221,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
};
// --- Loading ---
- if (agentsLoading && !agent) {
+ if (!agent && (agentsLoading || detailQuery.isPending)) {
return <DetailLoadingSkeleton />;
}
@@ -223,17 +252,24 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
// --- Not found / error ---
if (!agent) {
+ const loadError = detailError ?? agentsError;
return (
<div className="flex flex-1 min-h-0 flex-col">
<BackHeader paths={paths.agents()} title={t(($) => $.detail.back_to_agents)} />
<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
<AlertCircle className="h-8 w-8 text-destructive" />
<div>
- <p className="text-body font-medium">{t(($) => $.detail.not_found_title)}</p>
+ <p className="text-body font-medium">
+ {isNotFound
+ ? t(($) => $.detail.not_found_title)
+ : t(($) => $.detail.load_failed_title)}
+ </p>
<p className="mt-1 text-caption text-muted-foreground">
- {agentsError instanceof Error
- ? agentsError.message
- : t(($) => $.detail.not_found_default)}
+ {isNotFound
+ ? t(($) => $.detail.not_found_default)
+ : loadError instanceof Error
+ ? loadError.message
+ : t(($) => $.detail.load_failed_default)}
</p>
</div>
<div className="flex items-center gap-2">
@@ -241,7 +277,9 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
type="button"
variant="outline"
size="sm"
- onClick={() => refetchAgents()}
+ onClick={() => {
+ void Promise.all([refetchAgents(), detailQuery.refetch()]);
+ }}
>
{t(($) => $.detail.try_again)}
</Button>
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
index 5f3acd5c6c..33df182dbc 100644
--- a/packages/views/agents/create/create-agent-ui.test.ts
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -1,7 +1,13 @@
import { createElement } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { ApiError } from "@multica/core/api";
+import type { Agent } from "@multica/core/types";
+import {
+ cacheAgentResponse,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
import { AgentNameField } from "./agent-configuration-panel";
import { CreateMethodChooser } from "./choose-create-method-page";
import { CreateAgentFooter } from "./create-agent-footer";
@@ -170,6 +176,76 @@ describe("Agent creation errors", () => {
});
});
+const CREATED_AGENT: Agent = {
+ id: "agent-new",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Blank agent",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "",
+ owner_id: "user-1",
+ skills: [],
+ created_at: "2026-08-15T00:00:00Z",
+ updated_at: "2026-08-15T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+describe("Agent creation cache handoff", () => {
+ it("hydrates detail and upserts an already-loaded agent list", () => {
+ const queryClient = new QueryClient();
+ const existingAgent = { ...CREATED_AGENT, id: "agent-existing" };
+ queryClient.setQueryData(workspaceKeys.agents("ws-1"), [existingAgent]);
+
+ cacheAgentResponse(queryClient, "ws-1", CREATED_AGENT);
+
+ expect(
+ queryClient.getQueryData(workspaceKeys.agent("ws-1", CREATED_AGENT.id)),
+ ).toEqual(CREATED_AGENT);
+ expect(queryClient.getQueryData(workspaceKeys.agents("ws-1"))).toEqual([
+ existingAgent,
+ CREATED_AGENT,
+ ]);
+ });
+
+ it("does not turn one create response into a partial cold list", () => {
+ const queryClient = new QueryClient();
+
+ cacheAgentResponse(queryClient, "ws-1", CREATED_AGENT);
+
+ expect(
+ queryClient.getQueryData(workspaceKeys.agents("ws-1")),
+ ).toBeUndefined();
+ expect(
+ queryClient.getQueryData(workspaceKeys.agent("ws-1", CREATED_AGENT.id)),
+ ).toEqual(CREATED_AGENT);
+ });
+
+ it("can update detail without inserting a list entry that was not present", () => {
+ const queryClient = new QueryClient();
+ queryClient.setQueryData<Agent[]>(workspaceKeys.agents("ws-1"), []);
+
+ cacheAgentResponse(queryClient, "ws-1", CREATED_AGENT, {
+ insertIntoList: false,
+ });
+
+ expect(queryClient.getQueryData(workspaceKeys.agents("ws-1"))).toEqual([]);
+ expect(
+ queryClient.getQueryData(workspaceKeys.agent("ws-1", CREATED_AGENT.id)),
+ ).toEqual(CREATED_AGENT);
+ });
+});
+
// The list endpoint returns the stored message untouched, still in the builder
// wire format. Rendered raw it is a wall of JSON, which is what the user would
// see on the one screen meant to help them recognise their own draft.
diff --git a/packages/views/agents/create/use-create-agent-submit.test.tsx b/packages/views/agents/create/use-create-agent-submit.test.tsx
new file mode 100644
index 0000000000..e1c7e9ddaa
--- /dev/null
+++ b/packages/views/agents/create/use-create-agent-submit.test.tsx
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { act, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { EMPTY_AGENT_DRAFT } from "@multica/core/agents";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { Agent } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import enAgents from "../../locales/en/agents.json";
+
+const mockCreateAgent = vi.hoisted(() => vi.fn());
+const mockPush = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ agentDetail: (agentId: string) => `/acme/agents/${agentId}`,
+ squadDetail: (squadId: string) => `/acme/squads/${squadId}`,
+ }),
+}));
+
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({ push: mockPush }),
+}));
+
+vi.mock("@multica/core/api", () => {
+ class ApiError extends Error {
+ status: number;
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+ }
+ return {
+ api: {
+ createAgent: mockCreateAgent,
+ addSquadMember: vi.fn(),
+ },
+ ApiError,
+ };
+});
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), warning: vi.fn() },
+}));
+
+import { useCreateAgentSubmit } from "./use-create-agent-submit";
+
+const CREATED_AGENT: Agent = {
+ id: "agent-new",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Blank agent",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "",
+ owner_id: "user-1",
+ skills: [],
+ created_at: "2026-08-15T00:00:00Z",
+ updated_at: "2026-08-15T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+function wrapper(queryClient: QueryClient) {
+ return function TestWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={{ en: { agents: enAgents } }}>
+ <QueryClientProvider client={queryClient}>
+ {children}
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreateAgent.mockResolvedValue(CREATED_AGENT);
+});
+
+describe("useCreateAgentSubmit cache handoff", () => {
+ it("hydrates list and detail before navigating without awaiting reconciliation", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ queryClient.setQueryData<Agent[]>(workspaceKeys.agents("ws-1"), []);
+
+ // A slow list reconciliation must not gate the detail route.
+ vi.spyOn(queryClient, "invalidateQueries").mockReturnValue(
+ new Promise<void>(() => {}),
+ );
+ let navigationSnapshot:
+ | { path: string; list: Agent[] | undefined; detail: Agent | undefined }
+ | undefined;
+ mockPush.mockImplementation((path: string) => {
+ navigationSnapshot = {
+ path,
+ list: queryClient.getQueryData<Agent[]>(
+ workspaceKeys.agents("ws-1"),
+ ),
+ detail: queryClient.getQueryData<Agent>(
+ workspaceKeys.agent("ws-1", CREATED_AGENT.id),
+ ),
+ };
+ });
+
+ const { result } = renderHook(
+ () =>
+ useCreateAgentSubmit({
+ draft: {
+ ...EMPTY_AGENT_DRAFT,
+ name: CREATED_AGENT.name,
+ runtimeId: CREATED_AGENT.runtime_id,
+ },
+ runtimeId: CREATED_AGENT.runtime_id,
+ squadId: null,
+ }),
+ { wrapper: wrapper(queryClient) },
+ );
+
+ await act(async () => {
+ await result.current.create();
+ });
+
+ expect(navigationSnapshot).toEqual({
+ path: "/acme/agents/agent-new",
+ list: [CREATED_AGENT],
+ detail: CREATED_AGENT,
+ });
+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: workspaceKeys.agents("ws-1"),
+ });
+ });
+});
diff --git a/packages/views/agents/create/use-create-agent-submit.ts b/packages/views/agents/create/use-create-agent-submit.ts
index c049593d09..2120a9dfe3 100644
--- a/packages/views/agents/create/use-create-agent-submit.ts
+++ b/packages/views/agents/create/use-create-agent-submit.ts
@@ -8,7 +8,10 @@ import { api, ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import type { Agent } from "@multica/core/types";
-import { workspaceKeys } from "@multica/core/workspace/queries";
+import {
+ cacheAgentResponse,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
@@ -101,7 +104,11 @@ export function useCreateAgentSubmit(options: {
}
await onCreated?.(agent);
- await qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ cacheAgentResponse(qc, wsId, agent);
+ // The create response is authoritative enough to open immediately.
+ // Reconcile other list projections in the background instead of making
+ // navigation wait on a second network request.
+ void qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
toast.success(
t(($) => $.creation_studio.created, {
name: agent.name || draft.name.trim(),
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 25dfb6aba6..a795bb3d77 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -136,6 +136,8 @@
"back_to_agents_full": "Back to agents",
"not_found_title": "Agent not found",
"not_found_default": "This agent may have been archived or deleted.",
+ "load_failed_title": "Couldn't load this agent",
+ "load_failed_default": "Something went wrong fetching this agent.",
"no_access_title": "You don't have access to this agent",
"no_access_hint": "Only the agent owner or a workspace admin can view this private agent.",
"try_again": "Try again",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index cd4c95a5fb..978bd68713 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -120,6 +120,8 @@
"back_to_agents_full": "エージェントに戻る",
"not_found_title": "エージェントが見つかりません",
"not_found_default": "このエージェントはアーカイブまたは削除された可能性があります。",
+ "load_failed_title": "エージェントを読み込めませんでした",
+ "load_failed_default": "エージェントの取得中に問題が発生しました。",
"no_access_title": "このエージェントにアクセスできません",
"no_access_hint": "この非公開エージェントは、エージェントのオーナーまたはワークスペースの admin のみが閲覧できます。",
"try_again": "再試行",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 1af11b3077..f743df0df5 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -128,6 +128,8 @@
"back_to_agents_full": "에이전트로 돌아가기",
"not_found_title": "에이전트를 찾을 수 없습니다",
"not_found_default": "이 에이전트가 보관되었거나 삭제되었을 수 있습니다.",
+ "load_failed_title": "이 에이전트를 불러오지 못했습니다",
+ "load_failed_default": "이 에이전트를 가져오는 중 문제가 발생했습니다.",
"no_access_title": "이 에이전트에 접근할 수 없습니다",
"no_access_hint": "비공개 에이전트는 에이전트 소유자 또는 워크스페이스 관리자만 볼 수 있습니다.",
"try_again": "다시 시도",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index ebf58e2a34..b38791497a 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -128,6 +128,8 @@
"back_to_agents_full": "返回智能体列表",
"not_found_title": "未找到该智能体",
"not_found_default": "该智能体可能已被归档或删除。",
+ "load_failed_title": "无法加载该智能体",
+ "load_failed_default": "获取该智能体时出错。",
"no_access_title": "你没有访问该智能体的权限",
"no_access_hint": "只有该私密智能体的拥有者或工作区管理员可以查看。",
"try_again": "重试",