Skip to content

Commit 4757593

Browse files
authored
fix(admin): detail custom LLM validation errors (#5137)
1 parent 6cec534 commit 4757593

3 files changed

Lines changed: 348 additions & 8 deletions

File tree

‎apps/web/src/app/admin/custom-llms/CustomLlmsContent.tsx‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
import { CustomLlmDefinitionSchema } from '@kilocode/db/schema-types';
2929
import type { CustomLlmDefinition } from '@kilocode/db/schema-types';
3030
import { deepStrict } from '@/lib/zod/deep-strict';
31+
import { formatZodError } from '@/lib/zod/format-zod-error';
3132
import { CUSTOM_LLM_PREFIX } from '@/lib/ai-gateway/model-utils';
3233
import { toast } from 'sonner';
3334
import { Plus, Pencil } from 'lucide-react';
@@ -92,11 +93,20 @@ export function CustomLlmsContent() {
9293
}, []);
9394

9495
const handleSave = useCallback(async () => {
95-
if (!editor.publicId.trim()) {
96+
const trimmedPublicId = editor.publicId.trim();
97+
if (!trimmedPublicId) {
9698
setEditor(prev => ({ ...prev, validationError: 'public_id is required' }));
9799
return;
98100
}
99101

102+
if (!trimmedPublicId.startsWith(CUSTOM_LLM_PREFIX)) {
103+
setEditor(prev => ({
104+
...prev,
105+
validationError: `public_id must start with "${CUSTOM_LLM_PREFIX}"`,
106+
}));
107+
return;
108+
}
109+
100110
let parsed: unknown;
101111
try {
102112
parsed = JSON.parse(editor.definitionJson);
@@ -107,22 +117,19 @@ export function CustomLlmsContent() {
107117

108118
const result = StrictCustomLlmDefinitionSchema.safeParse(parsed);
109119
if (!result.success) {
110-
const messages = result.error.issues
111-
.map(issue => `${issue.path.join('.')}: ${issue.message}`)
112-
.join('\n');
113-
setEditor(prev => ({ ...prev, validationError: messages }));
120+
setEditor(prev => ({ ...prev, validationError: formatZodError(result.error) }));
114121
return;
115122
}
116123

117124
try {
118125
await upsertMutation.mutateAsync({
119-
public_id: editor.publicId,
126+
public_id: trimmedPublicId,
120127
definition: result.data,
121128
});
122129
toast.success(editor.mode === 'create' ? 'Custom LLM created' : 'Custom LLM updated');
123130
closeEditor();
124131
} catch (error) {
125-
toast.error(error instanceof Error ? error.message : 'Failed to save');
132+
toast.error(formatZodError(error));
126133
}
127134
}, [editor, upsertMutation, closeEditor]);
128135

@@ -132,7 +139,7 @@ export function CustomLlmsContent() {
132139
await deleteMutation.mutateAsync({ public_id: publicId });
133140
toast.success('Custom LLM deleted');
134141
} catch (error) {
135-
toast.error(error instanceof Error ? error.message : 'Failed to delete');
142+
toast.error(formatZodError(error));
136143
}
137144
},
138145
[deleteMutation]
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
import { describe, expect, test } from '@jest/globals';
2+
import { z } from 'zod';
3+
import { formatZodIssue, formatZodIssues, formatZodError } from './format-zod-error';
4+
import { deepStrict } from './deep-strict';
5+
import { CustomLlmDefinitionSchema } from '@kilocode/db/schema-types';
6+
7+
describe('formatZodIssue', () => {
8+
test('formats issue with path', () => {
9+
const formatted = formatZodIssue({
10+
code: 'invalid_type',
11+
path: ['internal_id'],
12+
message: 'Too small',
13+
});
14+
expect(formatted).toBe('internal_id: Too small');
15+
});
16+
17+
test('formats issue with empty path without leading colon', () => {
18+
const formatted = formatZodIssue({
19+
code: 'custom',
20+
path: [],
21+
message: 'Invalid configuration',
22+
});
23+
expect(formatted).toBe('Invalid configuration');
24+
});
25+
26+
test('formats unrecognized_keys at top level', () => {
27+
const formatted = formatZodIssue({
28+
code: 'unrecognized_keys',
29+
path: [],
30+
keys: ['dispaly_name'],
31+
});
32+
expect(formatted).toBe('Unrecognized key: "dispaly_name"');
33+
});
34+
35+
test('formats multiple unrecognized_keys with nested path', () => {
36+
const formatted = formatZodIssue({
37+
code: 'unrecognized_keys',
38+
path: ['pricing'],
39+
keys: ['extra1', 'extra2'],
40+
});
41+
expect(formatted).toBe('pricing: Unrecognized keys: "extra1", "extra2"');
42+
});
43+
});
44+
45+
describe('formatZodIssues with unions', () => {
46+
const schema = deepStrict(CustomLlmDefinitionSchema);
47+
48+
test('formats initial definition errors cleanly without ": Invalid input"', () => {
49+
const initialDefinition = {
50+
internal_id: '',
51+
display_name: '',
52+
context_length: 0,
53+
max_completion_tokens: 0,
54+
base_url: '',
55+
api_key: '',
56+
organization_ids: [],
57+
};
58+
59+
const result = schema.safeParse(initialDefinition);
60+
expect(result.success).toBe(false);
61+
if (!result.success) {
62+
const messages = formatZodIssues(result.error.issues);
63+
expect(messages).not.toContain(': Invalid input');
64+
expect(messages).not.toContain('Invalid input');
65+
expect(messages).toEqual(
66+
expect.arrayContaining([
67+
expect.stringContaining('internal_id'),
68+
expect.stringContaining('base_url'),
69+
])
70+
);
71+
}
72+
});
73+
74+
test('picks the API key branch when api_key is present and fields have typos', () => {
75+
const typoInput = {
76+
internal_id: 'model-1',
77+
dispaly_name: 'Typo Name',
78+
context_length: 1000,
79+
max_completion_tokens: 100,
80+
base_url: 'https://example.com',
81+
api_key: 'secret',
82+
organization_ids: [],
83+
};
84+
85+
const result = schema.safeParse(typoInput);
86+
expect(result.success).toBe(false);
87+
if (!result.success) {
88+
const messages = formatZodIssues(result.error.issues);
89+
expect(messages).not.toContain(': Invalid input');
90+
expect(messages).toContain('Unrecognized key: "dispaly_name"');
91+
expect(messages.some(m => m.includes('display_name'))).toBe(true);
92+
expect(messages.some(m => m.includes('google_service_account'))).toBe(false);
93+
}
94+
});
95+
96+
test('picks the Google service account branch when google_service_account is present', () => {
97+
const gsaInput = {
98+
internal_id: 'model-1',
99+
display_name: 'Vertex Gemini',
100+
context_length: 1000,
101+
max_completion_tokens: 100,
102+
base_url: 'https://example.com',
103+
organization_ids: [],
104+
google_service_account: {
105+
type: 'service_account',
106+
project_id: 'proj',
107+
private_key_id: 'key-id',
108+
private_key: 'pk',
109+
client_email: 'invalid-email',
110+
client_id: '123',
111+
auth_uri: 'https://accounts.google.com',
112+
token_uri: 'https://oauth2.googleapis.com',
113+
auth_provider_x509_cert_url: 'https://example.com',
114+
client_x509_cert_url: 'https://example.com',
115+
},
116+
};
117+
118+
const result = schema.safeParse(gsaInput);
119+
expect(result.success).toBe(false);
120+
if (!result.success) {
121+
const messages = formatZodIssues(result.error.issues);
122+
expect(messages).not.toContain(': Invalid input');
123+
expect(messages.some(m => m.includes('google_service_account.client_email'))).toBe(true);
124+
expect(messages.some(m => m.includes('api_key'))).toBe(false);
125+
}
126+
});
127+
128+
test('shows both authentication options when neither is provided', () => {
129+
const noAuthInput = {
130+
internal_id: 'model-1',
131+
display_name: 'Model 1',
132+
context_length: 1000,
133+
max_completion_tokens: 100,
134+
base_url: 'https://example.com',
135+
organization_ids: [],
136+
};
137+
138+
const result = schema.safeParse(noAuthInput);
139+
expect(result.success).toBe(false);
140+
if (!result.success) {
141+
const messages = formatZodIssues(result.error.issues);
142+
expect(messages).not.toContain(': Invalid input');
143+
expect(messages.some(m => m.includes('api_key'))).toBe(true);
144+
expect(messages.some(m => m.includes('google_service_account'))).toBe(true);
145+
}
146+
});
147+
148+
test('handles nested unions with path prefixes', () => {
149+
const nestedSchema = z.object({
150+
config: z.union([
151+
z.object({ mode: z.literal('a'), aValue: z.string() }),
152+
z.object({ mode: z.literal('b'), bValue: z.number() }),
153+
]),
154+
});
155+
156+
const result = nestedSchema.safeParse({ config: { mode: 'a', aValue: 123 } });
157+
expect(result.success).toBe(false);
158+
if (!result.success) {
159+
const messages = formatZodIssues(result.error.issues);
160+
expect(messages).toEqual(['config.aValue: Invalid input: expected string, received number']);
161+
}
162+
});
163+
});
164+
165+
describe('formatZodError', () => {
166+
test('formats ZodError instance', () => {
167+
const schema = z.object({ name: z.string() });
168+
const result = schema.safeParse({ name: 123 });
169+
if (!result.success) {
170+
const formatted = formatZodError(result.error);
171+
expect(formatted).toBe('name: Invalid input: expected string, received number');
172+
}
173+
});
174+
175+
test('formats JSON-encoded TRPC issues string', () => {
176+
const jsonError = JSON.stringify([
177+
{
178+
code: 'custom',
179+
message: 'public_id must start with "custom-llm/"',
180+
path: ['public_id'],
181+
},
182+
]);
183+
const formatted = formatZodError(new Error(jsonError));
184+
expect(formatted).toBe('public_id: public_id must start with "custom-llm/"');
185+
});
186+
187+
test('formats TRPC data.zodError shape', () => {
188+
const trpcError = {
189+
message: 'BAD_REQUEST',
190+
data: {
191+
zodError: {
192+
formErrors: [],
193+
fieldErrors: {
194+
public_id: ['public_id is required'],
195+
},
196+
},
197+
},
198+
};
199+
const formatted = formatZodError(trpcError);
200+
expect(formatted).toBe('public_id: public_id is required');
201+
});
202+
203+
test('falls back to plain Error message', () => {
204+
const formatted = formatZodError(new Error('Network error'));
205+
expect(formatted).toBe('Network error');
206+
});
207+
});
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { z } from 'zod';
2+
3+
export type ZodIssueLike =
4+
| z.core.$ZodIssue
5+
| {
6+
code: string;
7+
message?: string;
8+
path?: readonly PropertyKey[];
9+
keys?: string[];
10+
errors?: readonly (readonly ZodIssueLike[])[];
11+
};
12+
13+
export function formatZodIssue(
14+
issue: ZodIssueLike,
15+
parentPath: readonly (string | number | symbol)[] = []
16+
): string {
17+
const fullPath = [...parentPath, ...(issue.path ?? [])];
18+
const pathStr = fullPath.length > 0 ? fullPath.map(String).join('.') : '';
19+
20+
if (issue.code === 'unrecognized_keys' && Array.isArray(issue.keys) && issue.keys.length > 0) {
21+
const keysStr = issue.keys.map(k => `"${k}"`).join(', ');
22+
const label = issue.keys.length === 1 ? 'Unrecognized key' : 'Unrecognized keys';
23+
return pathStr ? `${pathStr}: ${label}: ${keysStr}` : `${label}: ${keysStr}`;
24+
}
25+
26+
const message = issue.message || 'Invalid input';
27+
return pathStr ? `${pathStr}: ${message}` : message;
28+
}
29+
30+
export function formatZodIssues(
31+
issues: readonly ZodIssueLike[],
32+
parentPath: readonly (string | number | symbol)[] = []
33+
): string[] {
34+
const messages: string[] = [];
35+
36+
for (const issue of issues) {
37+
const currentPath = [...parentPath, ...(issue.path ?? [])];
38+
39+
if (issue.code === 'invalid_union' && Array.isArray(issue.errors) && issue.errors.length > 0) {
40+
const branchIssueLists = issue.errors;
41+
const minErrors = Math.min(...branchIssueLists.map(list => list.length));
42+
const candidateBranches = branchIssueLists.filter(list => list.length === minErrors);
43+
44+
if (candidateBranches.length === 1) {
45+
messages.push(...formatZodIssues(candidateBranches[0], currentPath));
46+
} else {
47+
const branchMessages = new Set<string>();
48+
for (const branch of candidateBranches) {
49+
for (const msg of formatZodIssues(branch, currentPath)) {
50+
branchMessages.add(msg);
51+
}
52+
}
53+
messages.push(...Array.from(branchMessages));
54+
}
55+
continue;
56+
}
57+
58+
messages.push(formatZodIssue(issue, parentPath));
59+
}
60+
61+
return messages;
62+
}
63+
64+
export function formatZodError(error: unknown): string {
65+
if (error instanceof z.ZodError) {
66+
const lines = formatZodIssues(error.issues as ZodIssueLike[]);
67+
return lines.length > 0 ? lines.join('\n') : error.message;
68+
}
69+
70+
if (
71+
typeof error === 'object' &&
72+
error !== null &&
73+
'data' in error &&
74+
typeof (error as { data?: unknown }).data === 'object' &&
75+
(error as { data?: { zodError?: unknown } }).data?.zodError
76+
) {
77+
const zodError = (
78+
error as {
79+
data: {
80+
zodError: { formErrors?: string[]; fieldErrors?: Record<string, string[]> };
81+
};
82+
}
83+
).data.zodError;
84+
85+
const messages: string[] = [];
86+
if (Array.isArray(zodError.formErrors)) {
87+
for (const msg of zodError.formErrors) {
88+
if (msg && msg !== 'Invalid input') messages.push(msg);
89+
}
90+
}
91+
if (zodError.fieldErrors && typeof zodError.fieldErrors === 'object') {
92+
for (const [field, fieldMessages] of Object.entries(zodError.fieldErrors)) {
93+
if (Array.isArray(fieldMessages)) {
94+
for (const msg of fieldMessages) {
95+
messages.push(`${field}: ${msg}`);
96+
}
97+
}
98+
}
99+
}
100+
if (messages.length > 0) {
101+
return messages.join('\n');
102+
}
103+
}
104+
105+
if (typeof error === 'string') {
106+
const trimmed = error.trim();
107+
if (trimmed.startsWith('[')) {
108+
try {
109+
const parsed = JSON.parse(trimmed);
110+
if (Array.isArray(parsed) && parsed.length > 0 && parsed[0]?.code) {
111+
const lines = formatZodIssues(parsed as ZodIssueLike[]);
112+
if (lines.length > 0) return lines.join('\n');
113+
}
114+
} catch {
115+
// Not JSON
116+
}
117+
}
118+
return error;
119+
}
120+
121+
if (error instanceof Error) {
122+
return formatZodError(error.message);
123+
}
124+
125+
return 'Validation failed';
126+
}

0 commit comments

Comments
 (0)