Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: improve web form validation feedback

Gener5b10ea37204e
diff --git a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx
index 9a508d60d..328b591e9 100644
--- a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx
+++ b/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx
@@ -15,6 +15,11 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
+import {
+ type WorkspaceFormErrors,
+ hasWorkspaceFormErrors,
+ validateWorkspaceForm,
+} from "@/lib/form-validation";
export function GeneralTab() {
const { workspaceId, slug } = useWorkspace();
@@ -29,6 +34,7 @@ export function GeneralTab() {
const [savedWorkspaceName, setSavedWorkspaceName] = useState("");
const [savedWorkspaceSlug, setSavedWorkspaceSlug] = useState("");
const [savingWorkspace, setSavingWorkspace] = useState(false);
+ const [workspaceErrors, setWorkspaceErrors] = useState<WorkspaceFormErrors>({});
const [deleteConfirm, setDeleteConfirm] = useState("");
const [deleting, setDeleting] = useState(false);
@@ -69,11 +75,18 @@ export function GeneralTab() {
workspaceName !== savedWorkspaceName || workspaceSlug !== savedWorkspaceSlug;
const handleSaveWorkspace = async () => {
+ const nextErrors = validateWorkspaceForm({
+ name: workspaceName,
+ slug: workspaceSlug,
+ });
+ setWorkspaceErrors(nextErrors);
+ if (hasWorkspaceFormErrors(nextErrors)) return;
+
setSavingWorkspace(true);
try {
const updated = await updateWorkspace(workspaceId, {
- name: workspaceName,
- slug: workspaceSlug,
+ name: workspaceName.trim(),
+ slug: workspaceSlug.trim(),
});
setSavedWorkspaceName(updated.name);
setSavedWorkspaceSlug(updated.slug);
@@ -130,18 +143,44 @@ export function GeneralTab() {
<Input
id="workspace-name"
value={workspaceName}
- onChange={(e) => setWorkspaceName(e.target.value)}
+ onChange={(e) => {
+ const nextName = e.target.value;
+ setWorkspaceName(nextName);
+ if (workspaceErrors.name && nextName.trim()) {
+ setWorkspaceErrors((prev) => ({ ...prev, name: undefined }));
+ }
+ }}
placeholder="Workspace name"
+ aria-invalid={Boolean(workspaceErrors.name)}
+ aria-describedby={workspaceErrors.name ? "workspace-name-error" : undefined}
/>
+ {workspaceErrors.name && (
+ <p id="workspace-name-error" className="text-xs text-destructive">
+ {workspaceErrors.name}
+ </p>
+ )}
</div>
<div className="space-y-1.5">
<Label htmlFor="workspace-slug">Slug</Label>
<Input
id="workspace-slug"
value={workspaceSlug}
- onChange={(e) => setWorkspaceSlug(e.target.value)}
+ onChange={(e) => {
+ const nextSlug = e.target.value;
+ setWorkspaceSlug(nextSlug);
+ if (workspaceErrors.slug && nextSlug.trim()) {
+ setWorkspaceErrors((prev) => ({ ...prev, slug: undefined }));
+ }
+ }}
placeholder="workspace-slug"
+ aria-invalid={Boolean(workspaceErrors.slug)}
+ aria-describedby={workspaceErrors.slug ? "workspace-slug-error" : undefined}
/>
+ {workspaceErrors.slug && (
+ <p id="workspace-slug-error" className="text-xs text-destructive">
+ {workspaceErrors.slug}
+ </p>
+ )}
<p className="text-xs text-muted-foreground/70">
Used in URLs: /w/{workspaceSlug}/
</p>
diff --git a/src/web/src/app/(app)/workspaces/client.tsx b/src/web/src/app/(app)/workspaces/client.tsx
index 669343504..257085d6b 100644
--- a/src/web/src/app/(app)/workspaces/client.tsx
+++ b/src/web/src/app/(app)/workspaces/client.tsx
@@ -8,6 +8,11 @@ import { Input } from "@/components/ui/input"
import { GradientBackground } from "@/components/gradient-background"
import { Logo } from "@/components/logo"
import { Plus, ArrowRight, Loader2 } from "lucide-react"
+import {
+ type WorkspaceFormErrors,
+ hasWorkspaceFormErrors,
+ validateWorkspaceForm,
+} from "@/lib/form-validation"
interface WorkspaceItem {
id: string
@@ -34,12 +39,15 @@ export function WorkspaceListClient({
const [name, setName] = useState("")
const [creating, setCreating] = useState(false)
const [error, setError] = useState("")
+ const [fieldErrors, setFieldErrors] = useState<WorkspaceFormErrors>({})
const slug = deriveSlug(name)
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
- if (!name.trim() || !slug) return
+ const nextErrors = validateWorkspaceForm({ name, slug })
+ setFieldErrors(nextErrors)
+ if (hasWorkspaceFormErrors(nextErrors)) return
setError("")
setCreating(true)
@@ -100,15 +108,31 @@ export function WorkspaceListClient({
<Input
placeholder="Workspace name"
value={name}
- onChange={(e) => setName(e.target.value)}
+ onChange={(e) => {
+ const nextName = e.target.value
+ setName(nextName)
+ const nextSlug = deriveSlug(nextName)
+ if (fieldErrors.name && nextName.trim()) {
+ setFieldErrors((prev) => ({ ...prev, name: undefined }))
+ }
+ if (fieldErrors.slug && nextSlug) {
+ setFieldErrors((prev) => ({ ...prev, slug: undefined }))
+ }
+ }}
autoFocus
- required
+ aria-invalid={Boolean(fieldErrors.name || fieldErrors.slug)}
+ aria-describedby={fieldErrors.name || fieldErrors.slug ? "workspace-name-error" : undefined}
/>
{slug && (
<p className="text-xs text-muted-foreground pl-1">
Slug: {slug}
</p>
)}
+ {(fieldErrors.name || fieldErrors.slug) && (
+ <p id="workspace-name-error" className="text-xs text-destructive">
+ {fieldErrors.name || fieldErrors.slug}
+ </p>
+ )}
</div>
{error && (
<p className="text-xs text-destructive">{error}</p>
@@ -129,7 +153,7 @@ export function WorkspaceListClient({
<Button
type="submit"
size="sm"
- disabled={creating || !name.trim() || !slug}
+ disabled={creating}
className="flex-1"
>
{creating ? (
diff --git a/src/web/src/components/agent-create-form-validation.test.ts b/src/web/src/components/agent-create-form-validation.test.ts
new file mode 100644
index 000000000..2ccfcd278
--- /dev/null
+++ b/src/web/src/components/agent-create-form-validation.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import {
+ hasAgentCreateFieldErrors,
+ validateAgentCreateRequiredFields,
+} from "./agent-create-form-validation";
+
+describe("validateAgentCreateRequiredFields", () => {
+ it("requires a non-empty name", () => {
+ const errors = validateAgentCreateRequiredFields({
+ name: " ",
+ runtimeId: "rt_1",
+ });
+
+ expect(errors).toEqual({ name: "Name is required" });
+ expect(hasAgentCreateFieldErrors(errors)).toBe(true);
+ });
+
+ it("requires a runtime", () => {
+ const errors = validateAgentCreateRequiredFields({
+ name: "Maddox",
+ runtimeId: "",
+ });
+
+ expect(errors).toEqual({ runtimeId: "Select an online runtime" });
+ expect(hasAgentCreateFieldErrors(errors)).toBe(true);
+ });
+
+ it("passes when required fields are present", () => {
+ const errors = validateAgentCreateRequiredFields({
+ name: "Maddox",
+ runtimeId: "rt_1",
+ });
+
+ expect(errors).toEqual({});
+ expect(hasAgentCreateFieldErrors(errors)).toBe(false);
+ });
+});
diff --git a/src/web/src/components/agent-create-form-validation.ts b/src/web/src/components/agent-create-form-validation.ts
new file mode 100644
index 000000000..45adcc955
--- /dev/null
+++ b/src/web/src/components/agent-create-form-validation.ts
@@ -0,0 +1,32 @@
+export interface AgentCreateRequiredFields {
+ name: string;
+ runtimeId: string;
+}
+
+export interface AgentCreateFieldErrors {
+ name?: string;
+ runtimeId?: string;
+}
+
+export function validateAgentCreateRequiredFields({
+ name,
+ runtimeId,
+}: AgentCreateRequiredFields): AgentCreateFieldErrors {
+ const errors: AgentCreateFieldErrors = {};
+
+ if (!name.trim()) {
+ errors.name = "Name is required";
+ }
+
+ if (!runtimeId) {
+ errors.runtimeId = "Select an online runtime";
+ }
+
+ return errors;
+}
+
+export function hasAgentCreateFieldErrors(
+ errors: AgentCreateFieldErrors,
+): boolean {
+ return Boolean(errors.name || errors.runtimeId);
+}
diff --git a/src/web/src/components/agent-create-form.tsx b/src/web/src/components/agent-create-form.tsx
index 735367e59..1dd2591b8 100644
--- a/src/web/src/components/agent-create-form.tsx
+++ b/src/web/src/components/agent-create-form.tsx
@@ -20,6 +20,11 @@ import {
randomConfig,
serializeAvatarConfig,
} from "@/components/avatar";
+import {
+ type AgentCreateFieldErrors,
+ hasAgentCreateFieldErrors,
+ validateAgentCreateRequiredFields,
+} from "@/components/agent-create-form-validation";
interface AgentCreateFormProps {
runtimes: Runtime[];
@@ -53,6 +58,7 @@ export function AgentCreateForm({
const [instructions, setInstructions] = useState("");
const [runtimeId, setRuntimeId] = useState(defaultRuntimeId);
const [emailHandle, setEmailHandle] = useState("");
+ const [fieldErrors, setFieldErrors] = useState<AgentCreateFieldErrors>({});
const [customEmailData, setCustomEmailData] =
useState<CustomEmailData | null>(null);
const customEmailGetDataRef = useRef<(() => CustomEmailData | null) | null>(
@@ -71,10 +77,31 @@ export function AgentCreateForm({
const effectiveHandle = emailHandle || derivedHandle;
const handleError = getHandleError(effectiveHandle);
+ const updateName = (value: string) => {
+ setName(value);
+ if (fieldErrors.name && value.trim()) {
+ setFieldErrors((prev) => ({ ...prev, name: undefined }));
+ }
+ };
+
+ const updateRuntimeId = (value: string) => {
+ setRuntimeId(value);
+ if (fieldErrors.runtimeId && value) {
+ setFieldErrors((prev) => ({ ...prev, runtimeId: undefined }));
+ }
+ };
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
+ const nextErrors = validateAgentCreateRequiredFields({ name, runtimeId });
+ setFieldErrors(nextErrors);
+
+ if (hasAgentCreateFieldErrors(nextErrors)) {
+ return;
+ }
+
await onSave({
- name,
+ name: name.trim(),
description,
instructions,
runtime_id: runtimeId,
@@ -88,14 +115,14 @@ export function AgentCreateForm({
return (
<div className="flex-1 min-h-0 overflow-y-auto thin-scrollbar px-5 py-6">
- <form onSubmit={handleSubmit} className="mx-auto max-w-md space-y-4">
+ <form onSubmit={handleSubmit} noValidate className="mx-auto max-w-md space-y-4">
<AvatarPickerDialog
config={avatarConfig}
onChange={setAvatarConfig}
/>
<GeneralFields
name={name}
- setName={setName}
+ setName={updateName}
description={description}
setDescription={setDescription}
instructions={instructions}
@@ -103,9 +130,10 @@ export function AgentCreateForm({
model={model}
setModel={setModel}
runtimeId={runtimeId}
- setRuntimeId={setRuntimeId}
+ setRuntimeId={updateRuntimeId}
runtimes={runtimes}
providerModels={providerModels}
+ errors={fieldErrors}
/>
<div className="border-t border-border/50 pt-4 mt-4 space-y-4">
@@ -129,7 +157,7 @@ export function AgentCreateForm({
<Button
type="submit"
size="sm"
- disabled={saving || !name || !!handleError}
+ disabled={saving || !!handleError}
>
{saving ? "Creating..." : "Create"}
</Button>
diff --git a/src/web/src/components/agent-form-fields.tsx b/src/web/src/components/agent-form-fields.tsx
index dc54eee87..56a46a3c8 100644
--- a/src/web/src/components/agent-form-fields.tsx
+++ b/src/web/src/components/agent-form-fields.tsx
@@ -69,6 +69,10 @@ interface GeneralFieldsProps {
setRuntimeId: (v: string) => void;
runtimes: Runtime[];
providerModels: string[];
+ errors?: {
+ name?: string;
+ runtimeId?: string;
+ };
}
export function GeneralFields({
@@ -84,6 +88,7 @@ export function GeneralFields({
setRuntimeId,
runtimes,
providerModels,
+ errors,
}: GeneralFieldsProps) {
return (
<>
@@ -95,7 +100,14 @@ export function GeneralFields({
onChange={(e) => setName(e.target.value)}
placeholder="My Agent"
required
+ aria-invalid={Boolean(errors?.name)}
+ aria-describedby={errors?.name ? "agent-name-error" : undefined}
/>
+ {errors?.name && (
+ <p id="agent-name-error" className="text-xs text-destructive">
+ {errors.name}
+ </p>
+ )}
</div>
<div className="space-y-1.5">
@@ -155,7 +167,18 @@ export function GeneralFields({
}
}}
runtimes={runtimes}
+ triggerProps={{
+ "aria-invalid": Boolean(errors?.runtimeId),
+ "aria-describedby": errors?.runtimeId
+ ? "agent-runtime-error"
+ : undefined,
+ }}
/>
+ {errors?.runtimeId && (
+ <p id="agent-runtime-error" className="text-xs text-destructive">
+ {errors.runtimeId}
+ </p>
+ )}
</div>
</>
);
diff --git a/src/web/src/components/custom-email-form.tsx b/src/web/src/components/custom-email-form.tsx
index 83d38a8bd..9e7e79291 100644
--- a/src/web/src/components/custom-email-form.tsx
+++ b/src/web/src/components/custom-email-form.tsx
@@ -25,6 +25,11 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { useWorkspace } from "@/contexts/workspace-context";
+import {
+ type CustomEmailErrors,
+ hasCustomEmailErrors,
+ validateCustomEmailFields,
+} from "@/lib/form-validation";
const PRESETS: Record<string, { imapHost: string; imapPort: number; smtpHost: string; smtpPort: number }> = {
Gmail: { imapHost: "imap.gmail.com", imapPort: 993, smtpHost: "smtp.gmail.com", smtpPort: 587 },
@@ -89,9 +94,11 @@ function useEmailFields() {
return { fields, applyPreset, buildData };
}
-function EmailFieldsForm({ fields, applyPreset }: {
+function EmailFieldsForm({ fields, applyPreset, errors, onClearError }: {
fields: ReturnType<typeof useEmailFields>["fields"];
applyPreset: (name: string) => void;
+ errors: CustomEmailErrors;
+ onClearError: (field: keyof CustomEmailErrors) => void;
}) {
return (
<>
@@ -108,7 +115,18 @@ function EmailFieldsForm({ fields, applyPreset }: {
<div>
<Label className="text-xs">Email Address *</Label>
<Input placeholder="[email protected]" value={fields.emailAddress}
- onChange={(e) => fields.setEmailAddress(e.target.value)} className="h-8 text-sm" />
+ onChange={(e) => {
+ fields.setEmailAddress(e.target.value);
+ if (e.target.value.trim()) onClearError("emailAddress");
+ }}
+ aria-invalid={Boolean(errors.emailAddress)}
+ aria-describedby={errors.emailAddress ? "custom-email-address-error" : undefined}
+ className="h-8 text-sm" />
+ {errors.emailAddress && (
+ <p id="custom-email-address-error" className="mt-1 text-xs text-destructive">
+ {errors.emailAddress}
+ </p>
+ )}
</div>
<div>
<Label className="text-xs">Display Name</Label>
@@ -121,24 +139,68 @@ function EmailFieldsForm({ fields, applyPreset }: {
<div className="space-y-2">
<Label className="text-xs font-medium">IMAP (Receive)</Label>
<Input placeholder="imap.gmail.com" value={fields.imapHost}
- onChange={(e) => fields.setImapHost(e.target.value)} className="h-8 text-sm" />
+ onChange={(e) => {
+ fields.setImapHost(e.target.value);
+ if (e.target.value.trim()) onClearError("imapHost");
+ }}
+ aria-invalid={Boolean(errors.imapHost)}
+ aria-describedby={errors.imapHost ? "custom-email-imap-host-error" : undefined}
+ className="h-8 text-sm" />
+ {errors.imapHost && (
+ <p id="custom-email-imap-host-error" className="text-xs text-destructive">
+ {errors.imapHost}
+ </p>
+ )}
<Input type="number" placeholder="993" value={fields.imapPort}
onChange={(e) => fields.setImapPort(Number(e.target.value))} className="h-8 text-sm" />
<Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.imapUsername}
onChange={(e) => fields.setImapUsername(e.target.value)} className="h-8 text-sm" />
<Input type="password" placeholder="App Password" value={fields.imapPassword}
- onChange={(e) => fields.setImapPassword(e.target.value)} className="h-8 text-sm" />
+ onChange={(e) => {
+ fields.setImapPassword(e.target.value);
+ if (e.target.value.trim()) onClearError("imapPassword");
+ }}
+ aria-invalid={Boolean(errors.imapPassword)}
+ aria-describedby={errors.imapPassword ? "custom-email-imap-password-error" : undefined}
+ className="h-8 text-sm" />
+ {errors.imapPassword && (
+ <p id="custom-email-imap-password-error" className="text-xs text-destructive">
+ {errors.imapPassword}
+ </p>
+ )}
</div>
<div className="space-y-2">
<Label className="text-xs font-medium">SMTP (Send)</Label>
<Input placeholder="smtp.gmail.com" value={fields.smtpHost}
- onChange={(e) => fields.setSmtpHost(e.target.value)} className="h-8 text-sm" />
+ onChange={(e) => {
+ fields.setSmtpHost(e.target.value);
+ if (e.target.value.trim()) onClearError("smtpHost");
+ }}
+ aria-invalid={Boolean(errors.smtpHost)}
+ aria-describedby={errors.smtpHost ? "custom-email-smtp-host-error" : undefined}
+ className="h-8 text-sm" />
+ {errors.smtpHost && (
+ <p id="custom-email-smtp-host-error" className="text-xs text-destructive">
+ {errors.smtpHost}
+ </p>
+ )}
<Input type="number" placeholder="587" value={fields.smtpPort}
onChange={(e) => fields.setSmtpPort(Number(e.target.value))} className="h-8 text-sm" />
<Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.smtpUsername}
onChange={(e) => fields.setSmtpUsername(e.target.value)} className="h-8 text-sm" />
<Input type="password" placeholder="App Password" value={fields.smtpPassword}
- onChange={(e) => fields.setSmtpPassword(e.target.value)} className="h-8 text-sm" />
+ onChange={(e) => {
+ fields.setSmtpPassword(e.target.value);
+ if (e.target.value.trim()) onClearError("smtpPassword");
+ }}
+ aria-invalid={Boolean(errors.smtpPassword)}
+ aria-describedby={errors.smtpPassword ? "custom-email-smtp-password-error" : undefined}
+ className="h-8 text-sm" />
+ {errors.smtpPassword && (
+ <p id="custom-email-smtp-password-error" className="text-xs text-destructive">
+ {errors.smtpPassword}
+ </p>
+ )}
</div>
</div>
</>
@@ -154,8 +216,15 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
const [saving, setSaving] = useState(false);
const [syncing, setSyncing] = useState(false);
const [deleting, setDeleting] = useState(false);
+ const [fieldErrors, setFieldErrors] = useState<CustomEmailErrors>({});
const { fields, applyPreset, buildData } = useEmailFields();
+ const effectiveImapUsername = fields.imapUsername || fields.emailAddress;
+ const effectiveSmtpUsername = fields.smtpUsername || fields.emailAddress;
+
+ const clearFieldError = useCallback((field: keyof CustomEmailErrors) => {
+ setFieldErrors((prev) => ({ ...prev, [field]: undefined }));
+ }, []);
useEffect(() => {
if (getDataRef) getDataRef.current = buildData;
@@ -188,11 +257,20 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
const existing = accounts[0] ?? null;
async function handleCreate() {
+ const nextErrors = validateCustomEmailFields({
+ emailAddress: fields.emailAddress,
+ imapHost: fields.imapHost,
+ imapUsername: effectiveImapUsername,
+ imapPassword: fields.imapPassword,
+ smtpHost: fields.smtpHost,
+ smtpUsername: effectiveSmtpUsername,
+ smtpPassword: fields.smtpPassword,
+ });
+ setFieldErrors(nextErrors);
+ if (hasCustomEmailErrors(nextErrors)) return;
+
const data = buildData();
- if (!data) {
- toast.error("Please fill in all required fields");
- return;
- }
+ if (!data) return;
if (!agentId) return;
setSaving(true);
try {
@@ -343,7 +421,12 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef
</div>
) : (
<div className="space-y-4">
- <EmailFieldsForm fields={fields} applyPreset={applyPreset} />
+ <EmailFieldsForm
+ fields={fields}
+ applyPreset={applyPreset}
+ errors={fieldErrors}
+ onClearError={clearFieldError}
+ />
{!isCreateMode && (
<Button type="button" size="sm" className="w-full" onClick={handleCreate} disabled={saving}>
{saving && <Loader2 className="size-3 animate-spin mr-1" />}
diff --git a/src/web/src/components/runtime-select.tsx b/src/web/src/components/runtime-select.tsx
index a006f3ea5..0036a3419 100644
--- a/src/web/src/components/runtime-select.tsx
+++ b/src/web/src/components/runtime-select.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { ComponentProps } from "react";
import type { AgentRuntime as Runtime } from "@alook/shared";
import { ProviderLogo } from "@/components/provider-logo";
import {
@@ -17,6 +18,7 @@ interface RuntimeSelectProps {
onValueChange: (value: string) => void;
runtimes: Runtime[];
disabled?: boolean;
+ triggerProps?: Omit<ComponentProps<typeof SelectTrigger>, "children">;
}
function groupRuntimes(runtimes: Runtime[]) {
@@ -47,6 +49,7 @@ export function RuntimeSelect({
onValueChange,
runtimes,
disabled,
+ triggerProps,
}: RuntimeSelectProps) {
const groups = groupRuntimes(runtimes);
const allDisabled =
@@ -69,7 +72,7 @@ export function RuntimeSelect({
return { value: rt.id, label };
})}
>
- <SelectTrigger>
+ <SelectTrigger {...triggerProps}>
<SelectValue placeholder={getPlaceholder(runtimes)} />
</SelectTrigger>
<SelectPopup>
diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.ts
index bb37523d5..3586d3d4e 100644
--- a/src/web/src/lib/api.test.ts
+++ b/src/web/src/lib/api.test.ts
@@ -93,10 +93,31 @@ describe("apiFetch", () => {
await listAgents("w1");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).message).toBe("Name is required");
expect((e as ApiError).details).toEqual(["name: required", "email: invalid"]);
}
});
+ it("turns validation details into a readable error message", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ json: async () => ({
+ error: "validation error",
+ details: ["runtime_id: runtime_id is required"],
+ }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents("w1");
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).message).toBe("Runtime Id is required");
+ expect((e as ApiError).details).toEqual(["runtime_id: runtime_id is required"]);
+ }
+ });
+
it("returns ApiError with status 0 on network TypeError", async () => {
mockFetch.mockRejectedValueOnce(new TypeError("Failed to fetch"));
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index e8792d1e3..65eba89f0 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -29,6 +29,34 @@ import { ApiError } from "@/lib/errors";
const API_BASE = "";
+function humanizeValidationDetail(detail: string): string {
+ const [rawField, ...rest] = detail.split(":");
+ const rawMessage = rest.join(":").trim();
+ if (!rawMessage) return detail;
+
+ const field = rawField.trim();
+ const label = field
+ .trim()
+ .replace(/[_-]+/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+ let message = rawMessage.replace(/^required$/i, "is required");
+
+ const normalizedMessage = message.toLowerCase().replace(/[_-]+/g, " ");
+ const normalizedField = field.toLowerCase().replace(/[_-]+/g, " ");
+ if (normalizedField && normalizedMessage.startsWith(`${normalizedField} `)) {
+ message = message.slice(field.length).trimStart();
+ }
+
+ return label ? `${label} ${message}` : message;
+}
+
+function getReadableErrorMessage(error: string | undefined, details: string[] | undefined) {
+ if (error === "validation error" && details?.length) {
+ return humanizeValidationDetail(details[0]);
+ }
+ return error;
+}
+
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
let res: Response;
try {
@@ -71,14 +99,15 @@ async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
if (res.status >= 500) {
throw new ApiError(
- serverError || "Something went wrong — please try again",
+ getReadableErrorMessage(serverError, details) ||
+ "Something went wrong — please try again",
res.status,
details,
);
}
throw new ApiError(
- serverError || "Something went wrong",
+ getReadableErrorMessage(serverError, details) || "Something went wrong",
res.status,
details,
);
diff --git a/src/web/src/lib/form-validation.test.ts b/src/web/src/lib/form-validation.test.ts
new file mode 100644
index 000000000..3608e8683
--- /dev/null
+++ b/src/web/src/lib/form-validation.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import {
+ hasCustomEmailErrors,
+ hasWorkspaceFormErrors,
+ validateCustomEmailFields,
+ validateWorkspaceForm,
+} from "./form-validation";
+
+describe("validateWorkspaceForm", () => {
+ it("requires workspace name and slug", () => {
+ const errors = validateWorkspaceForm({ name: " ", slug: "" });
+
+ expect(errors).toEqual({
+ name: "Workspace name is required",
+ slug: "Workspace slug is required",
+ });
+ expect(hasWorkspaceFormErrors(errors)).toBe(true);
+ });
+
+ it("passes when name and slug are present", () => {
+ const errors = validateWorkspaceForm({ name: "Alook", slug: "alook" });
+
+ expect(errors).toEqual({});
+ expect(hasWorkspaceFormErrors(errors)).toBe(false);
+ });
+});
+
+describe("validateCustomEmailFields", () => {
+ it("reports specific missing custom email fields", () => {
+ const errors = validateCustomEmailFields({
+ emailAddress: "",
+ imapHost: "",
+ imapUsername: "",
+ imapPassword: "",
+ smtpHost: "",
+ smtpUsername: "",
+ smtpPassword: "",
+ });
+
+ expect(errors).toEqual({
+ emailAddress: "Email address is required",
+ imapHost: "IMAP host is required",
+ imapPassword: "IMAP credentials are required",
+ smtpHost: "SMTP host is required",
+ smtpPassword: "SMTP credentials are required",
+ });
+ expect(hasCustomEmailErrors(errors)).toBe(true);
+ });
+
+ it("uses defaulted usernames when validating credentials", () => {
+ const errors = validateCustomEmailFields({
+ emailAddress: "[email protected]",
+ imapHost: "imap.example.com",
+ imapUsername: "[email protected]",
+ imapPassword: "secret",
+ smtpHost: "smtp.example.com",
+ smtpUsername: "[email protected]",
+ smtpPassword: "secret",
+ });
+
+ expect(errors).toEqual({});
+ expect(hasCustomEmailErrors(errors)).toBe(false);
+ });
+});
diff --git a/src/web/src/lib/form-validation.ts b/src/web/src/lib/form-validation.ts
new file mode 100644
index 000000000..83c4df6f2
--- /dev/null
+++ b/src/web/src/lib/form-validation.ts
@@ -0,0 +1,92 @@
+export interface WorkspaceFormValidationInput {
+ name: string;
+ slug: string;
+}
+
+export interface WorkspaceFormErrors {
+ name?: string;
+ slug?: string;
+}
+
+export function validateWorkspaceForm({
+ name,
+ slug,
+}: WorkspaceFormValidationInput): WorkspaceFormErrors {
+ const errors: WorkspaceFormErrors = {};
+
+ if (!name.trim()) {
+ errors.name = "Workspace name is required";
+ }
+
+ if (!slug.trim()) {
+ errors.slug = "Workspace slug is required";
+ }
+
+ return errors;
+}
+
+export function hasWorkspaceFormErrors(errors: WorkspaceFormErrors): boolean {
+ return Boolean(errors.name || errors.slug);
+}
+
+export interface CustomEmailValidationInput {
+ emailAddress: string;
+ imapHost: string;
+ imapUsername: string;
+ imapPassword: string;
+ smtpHost: string;
+ smtpUsername: string;
+ smtpPassword: string;
+}
+
+export interface CustomEmailErrors {
+ emailAddress?: string;
+ imapHost?: string;
+ imapPassword?: string;
+ smtpHost?: string;
+ smtpPassword?: string;
+}
+
+export function validateCustomEmailFields({
+ emailAddress,
+ imapHost,
+ imapUsername,
+ imapPassword,
+ smtpHost,
+ smtpUsername,
+ smtpPassword,
+}: CustomEmailValidationInput): CustomEmailErrors {
+ const errors: CustomEmailErrors = {};
+
+ if (!emailAddress.trim()) {
+ errors.emailAddress = "Email address is required";
+ }
+
+ if (!imapHost.trim()) {
+ errors.imapHost = "IMAP host is required";
+ }
+
+ if (!imapUsername.trim() || !imapPassword.trim()) {
+ errors.imapPassword = "IMAP credentials are required";
+ }
+
+ if (!smtpHost.trim()) {
+ errors.smtpHost = "SMTP host is required";
+ }
+
+ if (!smtpUsername.trim() || !smtpPassword.trim()) {
+ errors.smtpPassword = "SMTP credentials are required";
+ }
+
+ return errors;
+}
+
+export function hasCustomEmailErrors(errors: CustomEmailErrors): boolean {
+ return Boolean(
+ errors.emailAddress ||
+ errors.imapHost ||
+ errors.imapPassword ||
+ errors.smtpHost ||
+ errors.smtpPassword,
+ );
+}