Skip to content

Commit 2ace78d

Browse files
authored
fix(frontend): surface backend detail when agent name check fails (#3048)
* fix(frontend): surface backend detail when agent name check fails The new-agent page caught AgentNameCheckError but only branched on reason === "backend_unreachable". Everything else (notably the 422 "Invalid agent name '...'. Must match ^[A-Za-z0-9-]+$" response from GET /api/agents/check when the user submits a name with disallowed characters — trailing space, dot, Chinese, invisible whitespace from copy-paste) fell through to the generic fallback "Could not verify name availability — please try again", swallowing the detail that already told the user exactly what to fix. Add a request_failed branch that surfaces err.message (which checkAgentName already populates from the backend's detail at core/agents/api.ts). The disabled / backend_unreachable / unknown- error paths are unchanged. Pin the contract with unit tests covering: 200 success, fetch rejection, 502/503/504 network errors, agents_api disabled detail, 422 validation detail carried verbatim, statusText fallback when detail is absent, and a regression guard against misclassifying a 422 as agents_api disabled. Closes #3041 * fix(frontend): localise the error prefix when surfacing backend detail The previous commit surfaced the backend's raw `err.message` on the new-agent page when the name check failed. The detail itself is English (backend's `_validate_agent_name` text, any 5xx business message, etc.) and dropping it bare into a zh-CN page produced a jarring English-among-Chinese line that didn't match neighbouring strings like "已存在同名智能体" / "无法验证名称可用性". Add `nameStepCheckErrorWithDetail` as a templated string ("Name check failed: {detail}" / "名称校验失败:{detail}"), mirroring the existing `nameStepBootstrapMessage` `{name}` template pattern. The page wraps `err.message` in it when present and falls back to the plain `nameStepCheckError` when the detail is empty. Rendered output (verified locally with a Console fetch mock that returns 500 + detail): zh-CN: 名称校验失败:Database connection lost: SQLAlchemy connection pool exhausted (max 5 connections, all in use) en-US: Name check failed: Database connection lost: SQLAlchemy connection pool exhausted (max 5 connections, all in use) The localised prefix tells the user *what operation* failed; the raw detail tells them *why*. Translating the detail itself would be lossy (any unbounded backend string would need a translation table) and would break the debuggability the previous commit delivered. Refs #3041 * fix(frontend): distinguish backend detail from generated fallback in AgentNameCheckError Addresses Copilot's review on #3048: the previous commits keyed off `err.message`, but `checkAgentName` substitutes a generated fallback string ("Failed to check agent name: ${statusText}") when the backend sent no detail. That guaranteed `err.message` was always truthy, made the `nameStepCheckError` fallback branch unreachable in practice, and could surface awkward strings like "名称校验失败:Failed to check agent name: Bad Gateway" in the UI. Add an explicit `detail: string | null` field to AgentNameCheckError. `checkAgentName` populates it only when the backend response actually carried a string `detail` (defensive guard against the dict-shaped detail that other deer-flow endpoints use for typed error codes). The new-agent page now selects on `err.detail` instead of `err.message` so the localised fallback wins when no real detail exists. Also fix the prettier formatting that broke lint-frontend CI on the previous push. Test changes: - The 422 carry-through test now asserts both `detail` and `message` hold the backend string verbatim. - A new "falls back to statusText in message but leaves detail null" test pins the contract that no real detail ⇒ no UI surface leak. - A new "treats non-string detail as null" test guards against future backend schema drift toward dict-shaped detail. Refs #3041 #3048
1 parent 8330b24 commit 2ace78d

6 files changed

Lines changed: 186 additions & 1 deletion

File tree

frontend/src/app/workspace/agents/new/page.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,27 @@ export default function NewAgentPage() {
146146
err.reason === "backend_unreachable"
147147
) {
148148
setNameError(t.agents.nameStepNetworkError);
149+
} else if (
150+
err instanceof AgentNameCheckError &&
151+
err.reason === "request_failed"
152+
) {
153+
// Surface the backend-provided detail (e.g. validation error) when
154+
// one is present, wrapped in a localised prefix so zh-CN users
155+
// don't see a bare English string next to the surrounding Chinese
156+
// UI. Falls back to the generic localised fallback when the backend
157+
// sent no detail — `err.message` is unreliable for this branch
158+
// because `checkAgentName` substitutes a generated fallback string
159+
// ("Failed to check agent name: ${statusText}") when `detail` is
160+
// missing, so testing `err.message` would always be truthy and the
161+
// generated fallback would leak through.
162+
setNameError(
163+
err.detail
164+
? t.agents.nameStepCheckErrorWithDetail.replace(
165+
"{detail}",
166+
err.detail,
167+
)
168+
: t.agents.nameStepCheckError,
169+
);
149170
} else {
150171
setNameError(t.agents.nameStepCheckError);
151172
}
@@ -172,6 +193,7 @@ export default function NewAgentPage() {
172193
t.agents.nameStepNetworkError,
173194
t.agents.nameStepBootstrapMessage,
174195
t.agents.nameStepCheckError,
196+
t.agents.nameStepCheckErrorWithDetail,
175197
t.agents.nameStepInvalidError,
176198
threadId,
177199
]);

frontend/src/core/agents/api.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@ export class AgentNameCheckError extends Error {
99
constructor(
1010
message: string,
1111
public readonly reason: "backend_unreachable" | "request_failed",
12+
/**
13+
* Raw backend `detail` string when the failure came from a backend
14+
* response carrying one. `null` when no detail was provided (e.g.
15+
* network-layer failure, empty response body, unparseable body) — in
16+
* which case `message` is a generated fallback like "Failed to check
17+
* agent name: Bad Gateway" and the UI should prefer its own localized
18+
* fallback instead of surfacing the generated string.
19+
*/
20+
public readonly detail: string | null = null,
1221
) {
1322
super(message);
1423
this.name = "AgentNameCheckError";
@@ -104,9 +113,11 @@ export async function checkAgentName(
104113
"backend_unreachable",
105114
);
106115
}
116+
const backendDetail = typeof err.detail === "string" ? err.detail : null;
107117
throw new AgentNameCheckError(
108-
err.detail ?? `Failed to check agent name: ${res.statusText}`,
118+
backendDetail ?? `Failed to check agent name: ${res.statusText}`,
109119
"request_failed",
120+
backendDetail,
110121
);
111122
}
112123
return res.json() as Promise<{ available: boolean; name: string }>;

frontend/src/core/i18n/locales/en-US.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ export const enUS: Translations = {
204204
nameStepNetworkError:
205205
"Network request failed — check your network or backend connection",
206206
nameStepCheckError: "Could not verify name availability — please try again",
207+
nameStepCheckErrorWithDetail: "Name check failed: {detail}",
207208
nameStepApiDisabledError:
208209
"Custom agent management is not enabled on this server. Please contact your administrator.",
209210
nameStepBootstrapMessage:

frontend/src/core/i18n/locales/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ export interface Translations {
141141
nameStepAlreadyExistsError: string;
142142
nameStepNetworkError: string;
143143
nameStepCheckError: string;
144+
nameStepCheckErrorWithDetail: string;
144145
nameStepApiDisabledError: string;
145146
nameStepBootstrapMessage: string;
146147
save: string;

frontend/src/core/i18n/locales/zh-CN.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ export const zhCN: Translations = {
192192
nameStepAlreadyExistsError: "已存在同名智能体",
193193
nameStepNetworkError: "网络请求失败,请检查网络或后端连接",
194194
nameStepCheckError: "无法验证名称可用性,请稍后重试",
195+
nameStepCheckErrorWithDetail: "名称校验失败:{detail}",
195196
nameStepApiDisabledError:
196197
"服务器未开启自定义智能体管理功能,请联系管理员。",
197198
nameStepBootstrapMessage:
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
/**
2+
* Tests for the error-classification behaviour of `checkAgentName`.
3+
*
4+
* Issue #3041: when the backend returns a non-200 response (e.g. a 500 with
5+
* a database error, a 422 from misbehaving routing, or any other 4xx/5xx
6+
* not in the 502/503/504 set), the UI used to swallow the backend detail
7+
* into a generic "Could not verify name availability" fallback because the
8+
* page-level catch block only handled `reason === "backend_unreachable"`.
9+
*
10+
* The fix carries the raw backend detail as `AgentNameCheckError.detail`
11+
* (distinct from `message`, which always has a non-empty value because
12+
* `checkAgentName` substitutes a generated fallback when the backend sent
13+
* no detail). The UI uses `detail` to decide whether to surface a real
14+
* backend string or fall back to the localised "could not verify" copy.
15+
*
16+
* These tests pin both halves of the contract so a future refactor doesn't
17+
* silently drop the detail or leak the generated fallback into the UI.
18+
*/
19+
import { beforeEach, describe, expect, test, vi } from "vitest";
20+
21+
vi.mock("@/core/api/fetcher", () => ({
22+
fetch: vi.fn(),
23+
}));
24+
25+
vi.mock("@/core/config", () => ({
26+
getBackendBaseURL: () => "",
27+
}));
28+
29+
import { AgentsApiDisabledError, checkAgentName } from "@/core/agents/api";
30+
import { fetch as fetcher } from "@/core/api/fetcher";
31+
32+
const mockedFetch = vi.mocked(fetcher);
33+
34+
function jsonResponse(status: number, body: unknown): Response {
35+
return new Response(JSON.stringify(body), {
36+
status,
37+
headers: { "Content-Type": "application/json" },
38+
});
39+
}
40+
41+
beforeEach(() => {
42+
mockedFetch.mockReset();
43+
});
44+
45+
describe("checkAgentName", () => {
46+
test("returns availability payload on 200", async () => {
47+
mockedFetch.mockResolvedValueOnce(
48+
jsonResponse(200, { available: true, name: "dealagent" }),
49+
);
50+
const result = await checkAgentName("dealagent");
51+
expect(result).toEqual({ available: true, name: "dealagent" });
52+
});
53+
54+
test("treats network-layer fetch rejection as backend_unreachable", async () => {
55+
mockedFetch.mockRejectedValueOnce(new TypeError("Failed to fetch"));
56+
await expect(checkAgentName("dealagent")).rejects.toMatchObject({
57+
name: "AgentNameCheckError",
58+
reason: "backend_unreachable",
59+
});
60+
});
61+
62+
test.each([502, 503, 504])(
63+
"treats HTTP %i as backend_unreachable",
64+
async (status) => {
65+
mockedFetch.mockResolvedValueOnce(
66+
jsonResponse(status, { detail: "Bad Gateway" }),
67+
);
68+
await expect(checkAgentName("dealagent")).rejects.toMatchObject({
69+
name: "AgentNameCheckError",
70+
reason: "backend_unreachable",
71+
});
72+
},
73+
);
74+
75+
test("recognises agents_api disabled detail and throws AgentsApiDisabledError", async () => {
76+
const detail =
77+
"Custom-agent management API is disabled. Set agents_api.enabled=true to expose agent and user-profile routes over HTTP.";
78+
mockedFetch.mockResolvedValueOnce(jsonResponse(403, { detail }));
79+
await expect(checkAgentName("dealagent")).rejects.toBeInstanceOf(
80+
AgentsApiDisabledError,
81+
);
82+
});
83+
84+
test("carries backend 422 detail through AgentNameCheckError.detail (issue #3041)", async () => {
85+
// This is the exact response shape produced by `_validate_agent_name`
86+
// when the user submits a name with disallowed characters — e.g. a
87+
// trailing space, a dot, a Chinese character, or invisible whitespace
88+
// pasted in from another window.
89+
const detail =
90+
"Invalid agent name 'deal agent'. Must match ^[A-Za-z0-9-]+$ (letters, digits, and hyphens only).";
91+
mockedFetch.mockResolvedValueOnce(jsonResponse(422, { detail }));
92+
93+
await expect(checkAgentName("deal agent")).rejects.toMatchObject({
94+
name: "AgentNameCheckError",
95+
reason: "request_failed",
96+
// The full detail is preserved on both `detail` (for the UI to
97+
// recognise "real backend detail vs generated fallback") and
98+
// `message` (for stack traces / logs).
99+
detail,
100+
message: detail,
101+
});
102+
});
103+
104+
test("falls back to statusText in message but leaves detail null when backend returns no detail", async () => {
105+
// The fallback message must NOT mask the absence of a real backend
106+
// detail — the page-level catch relies on `detail === null` to choose
107+
// the localised generic fallback rather than rendering the bare
108+
// "Failed to check agent name: Internal Server Error" string.
109+
mockedFetch.mockResolvedValueOnce(
110+
new Response("", { status: 500, statusText: "Internal Server Error" }),
111+
);
112+
await expect(checkAgentName("dealagent")).rejects.toMatchObject({
113+
name: "AgentNameCheckError",
114+
reason: "request_failed",
115+
detail: null,
116+
message: expect.stringContaining("Internal Server Error"),
117+
});
118+
});
119+
120+
test("treats non-string detail as null (defence against future schema drift)", async () => {
121+
// If the backend ever returns `{detail: {code, message}}` (the shape
122+
// used by auth errors today) on this endpoint, we must not surface a
123+
// `[object Object]` string. `detail` should fall back to null so the
124+
// page uses its localised fallback.
125+
mockedFetch.mockResolvedValueOnce(
126+
jsonResponse(500, { detail: { code: "x", message: "y" } }),
127+
);
128+
await expect(checkAgentName("dealagent")).rejects.toMatchObject({
129+
name: "AgentNameCheckError",
130+
reason: "request_failed",
131+
detail: null,
132+
});
133+
});
134+
135+
test("does not misclassify a 422 with unrelated detail as agents_api disabled", async () => {
136+
// Defence-in-depth: the disabled detector matches on the substring
137+
// "agents_api.enabled", so a 422 whose detail accidentally contains
138+
// the same substring would be misclassified. The validation detail
139+
// produced by `_validate_agent_name` never contains it; this test
140+
// simply asserts that "Invalid agent name ..." stays in the
141+
// request_failed branch, which is where the page now surfaces it.
142+
const detail =
143+
"Invalid agent name 'deal.agent'. Must match ^[A-Za-z0-9-]+$ (letters, digits, and hyphens only).";
144+
mockedFetch.mockResolvedValueOnce(jsonResponse(422, { detail }));
145+
await expect(checkAgentName("deal.agent")).rejects.not.toBeInstanceOf(
146+
AgentsApiDisabledError,
147+
);
148+
});
149+
});

0 commit comments

Comments
 (0)