From a98cf7e00daee428ff48e57f68f3906d7791fecc Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+oldbettie@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:00:38 +0800 Subject: [PATCH] fix(agents): agent and skill edits always apply (last write wins) Per-item agent library writes no longer check a base revision. An upsert overwrites or recreates its item, a delete always removes it, and the server still bumps revision and updatedAt so devices converge on the latest write. Older clients that still send baseRevision decode fine; newer clients use per-item writes only on servers advertising agentLibraryLastWriteWins. A case-insensitive name clash now gets a numbered suffix on the server, and the editor flags it inline before save. Co-Authored-By: Claude Opus 5.5 --- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/serverSettings.test.ts | 152 +++++++------ apps/server/src/serverSettings.ts | 212 +++++++----------- .../web/src/components/agents/AgentEditor.tsx | 28 +-- apps/web/src/hooks/useAgentLibrary.ts | 12 +- .../client-runtime/src/gateway/runtimePort.ts | 4 +- .../src/gateway/runtimeProfiles.test.ts | 1 + .../src/operations/agentLibrary.test.ts | 16 +- .../src/operations/agentLibrary.ts | 27 +-- packages/contracts/src/agentLibrary.ts | 42 +--- packages/contracts/src/environment.ts | 4 +- packages/contracts/src/rpc.ts | 7 +- packages/contracts/src/settings.ts | 19 +- 13 files changed, 216 insertions(+), 309 deletions(-) diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b7fbf2224f9fc..513003da96eab 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -235,6 +235,7 @@ export const make = Effect.gen(function* () { agentSkillResources: true, agentSkillBodiesOnDemand: true, agentLibraryMutations: true, + agentLibraryLastWriteWins: true, storageCleanup: true, storageCleanupRun: true, databaseStorage: true, diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 6e7257c43331e..63e49a4a9376e 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -4,6 +4,7 @@ import { agentSkillDigest, DEFAULT_SERVER_SETTINGS, globalIdleCompaction, + mergeAgentLibraries, toAgentSkillStub, type ManagedPolicyDocument, ModelSelection, @@ -526,7 +527,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("rejects duplicate gateway profile names at the server boundary", () => + it.effect("suffixes duplicate gateway profile names instead of rejecting them", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsModule.ServerSettingsService; const base = { @@ -539,22 +540,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" updatedAt: "2000-01-01T00:00:00.000Z", }; - const error = yield* serverSettings - .updateSettings({ - mcpGatewayProfiles: [ - { ...base, profileId: "profile-andy-1" }, - { ...base, profileId: "profile-andy-2" }, - ], - }) - .pipe(Effect.flip); + const saved = yield* serverSettings.updateSettings({ + mcpGatewayProfiles: [ + { ...base, profileId: "profile-andy-1" }, + { ...base, profileId: "profile-andy-2" }, + ], + }); - assert.equal(error.operation, "normalize"); - assert.match(String(error.cause), /Duplicate MCP gateway profile name: Andy/); - assert.deepEqual((yield* serverSettings.getSettings).mcpGatewayProfiles, []); + assert.deepEqual( + saved.mcpGatewayProfiles.map((profile) => profile.name), + ["Andy", "Andy (2)"], + ); }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("rejects a new or renamed agent whose name clashes ignoring case", () => + it.effect("suffixes a new or renamed agent whose name clashes ignoring case", () => Effect.gen(function* () { const settings = yield* ServerSettingsModule.ServerSettingsService; const doug = { @@ -567,30 +567,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" updatedAt: "2026-01-01", }; const saved = yield* settings.updateSettings({ mcpGatewayProfiles: [doug] }); - const error = yield* settings - .updateSettings({ - mcpGatewayProfiles: [ - ...saved.mcpGatewayProfiles, - { ...doug, profileId: "other", name: "doug" }, - ], - }) - .pipe(Effect.flip); - assert.match(String(error.cause), /An agent named "doug" already exists/); - const conflict = yield* settings - .mutateAgentLibrary([ - { - type: "profile.upsert", - profile: { ...doug, profileId: "other", name: "DOUG" }, - baseRevision: null, - }, - ]) - .pipe(Effect.flip); - assert.deepInclude(conflict, { - _tag: "AgentLibraryConflictError", - reason: "name", - itemId: "other", + const patched = yield* settings.updateSettings({ + mcpGatewayProfiles: [ + ...saved.mcpGatewayProfiles, + { ...doug, profileId: "other", name: "doug" }, + ], }); - assert.match(conflict.message, /names ignore case/); + assert.deepEqual( + patched.mcpGatewayProfiles.map((profile) => profile.name), + ["Doug", "doug (2)"], + ); + const mutated = yield* settings.mutateAgentLibrary([ + { type: "profile.upsert", profile: { ...doug, profileId: "third", name: "DOUG" } }, + ]); + assert.equal(mutated.mcpGatewayProfiles[0]?.name, "DOUG (3)"); + // A stored clash stays editable without being renamed again. + const kept = yield* settings.mutateAgentLibrary([ + { + type: "profile.upsert", + profile: { ...doug, profileId: "third", name: "DOUG (3)", description: "Edited" }, + }, + ]); + assert.deepInclude(kept.mcpGatewayProfiles[0], { name: "DOUG (3)", description: "Edited" }); }).pipe(Effect.provide(layerServerSettings())), ); @@ -702,7 +700,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("applies per-item edits against base revisions and unassigns deleted skills", () => + it.effect("applies every per-item edit, last write wins, and unassigns deleted skills", () => Effect.gen(function* () { const settings = yield* ServerSettingsModule.ServerSettingsService; const skill = { @@ -732,67 +730,85 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" true, ); - const stale = yield* settings - .mutateAgentLibrary([ - { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea" }, baseRevision: 1 }, - { - type: "profile.upsert", - profile: { ...agent("randy"), name: "Randy" }, - baseRevision: 0, - }, - ]) - .pipe(Effect.flip); - assert.deepInclude(stale, { - _tag: "AgentLibraryConflictError", - itemKind: "agent", - itemId: "randy", - reason: "revision", - expectedRevision: 0, - actualRevision: 1, - }); + // Clients from before last-write-wins still send baseRevision; a stale one still applies, + // whole, so Randy's skill assignment goes with it. + const stale = yield* settings.mutateAgentLibrary([ + { type: "profile.upsert", profile: { ...agent("randy"), name: "Randy" }, baseRevision: 0 }, + ]); + assert.deepEqual( + stale.mcpGatewayProfiles.map((p) => [p.name, p.revision]), + [["Randy", 2]], + ); + + // Two clients edit from the same copy; every device converges on the later write. + const fromA = yield* settings.mutateAgentLibrary([ + { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea from A" } }, + ]); + const fromB = yield* settings.mutateAgentLibrary([ + { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea from B" } }, + ]); + assert.deepEqual( + fromB.mcpGatewayProfiles.map((p) => [p.name, p.revision]), + [["Bea from B", 3]], + ); assert.equal( - (yield* settings.getSettings).mcpGatewayProfiles.find((p) => p.profileId === "bea")?.name, - "bea", + mergeAgentLibraries([fromA, yield* settings.getSettings]).mcpGatewayProfiles.find( + (p) => p.profileId === "bea", + )?.name, + "Bea from B", ); const result = yield* settings.mutateAgentLibrary([ - { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea" }, baseRevision: 1 }, - { type: "skill.delete", skillId: "review", baseRevision: 1 }, + { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea" } }, + { type: "skill.delete", skillId: "review" }, ]); assert.deepEqual( result.mcpGatewayProfiles.map((p) => [p.profileId, p.name, p.revision, p.skillIds]), [ - ["bea", "Bea", 2, undefined], + ["bea", "Bea", 4, undefined], ["cal", "cal", 2, []], - ["randy", "randy", 2, []], ], ); assert.deepEqual(result.agentSkills, []); assert.isString(result.agentSkillDeletedAt.review); const after = yield* settings.getSettings; assert.deepEqual(after.agentSkills, []); - assert.deepEqual(after.mcpGatewayProfiles, result.mcpGatewayProfiles); + assert.includeDeepMembers([...after.mcpGatewayProfiles], [...result.mcpGatewayProfiles]); // Per-item edits carry the whole agent, so leaving out icon and tags clears them. const iconed = yield* settings.mutateAgentLibrary([ { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea", iconId: "rocket", tags: ["Dev"] }, - baseRevision: 2, }, ]); // Older builds only read the legacy literal, so an iconId alone gains its nearest one. assert.equal(iconed.mcpGatewayProfiles[0]?.icon, "sparkles"); const cleared = yield* settings.mutateAgentLibrary([ - { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea" }, baseRevision: 3 }, + { type: "profile.upsert", profile: { ...agent("bea"), name: "Bea" } }, ]); assert.notProperty(cleared.mcpGatewayProfiles[0], "iconId"); assert.notProperty(cleared.mcpGatewayProfiles[0], "tags"); - const gone = yield* settings - .mutateAgentLibrary([{ type: "skill.delete", skillId: "review", baseRevision: 1 }]) - .pipe(Effect.flip); - assert.deepInclude(gone, { reason: "missing", itemKind: "skill", itemId: "review" }); + // Deleted elsewhere: a delete still succeeds and an upsert recreates the item. + const deleted = yield* settings.mutateAgentLibrary([ + { type: "profile.delete", profileId: "cal" }, + { type: "skill.delete", skillId: "review", baseRevision: 1 }, + ]); + assert.isString(deleted.mcpGatewayProfileDeletedAt.cal); + const recreated = yield* settings.mutateAgentLibrary([ + { type: "profile.upsert", profile: { ...agent("cal"), name: "Cal", revision: 2 } }, + { type: "skill.upsert", skill: { ...skill, content: "Rules v2" } }, + ]); + assert.deepEqual( + recreated.mcpGatewayProfiles.map((p) => [p.name, p.revision]), + [["Cal", 3]], + ); + assert.equal(recreated.agentSkills[0]?.content, "Rules v2"); + assert.sameMembers( + mergeAgentLibraries([yield* settings.getSettings]).mcpGatewayProfiles.map((p) => p.name), + ["Bea", "Cal", "Randy"], + ); }).pipe(Effect.provide(layerServerSettings())), ); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 0bafab47fc0b6..6b8be9303b4cf 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -3,7 +3,7 @@ import { agentNameKey, agentSkillDigest, agentSkillDigestOf, - AgentLibraryConflictError, + claimAgentName, isAgentSkillStub, mergeAgentLibraries, toAgentSkillStub, @@ -334,10 +334,10 @@ export class ServerSettingsService extends Context.Service< patch?: ServerSettingsPatch, ) => Effect.Effect; - /** Per-item agent and skill edits checked against the revision each writer saw. */ + /** Per-item agent and skill edits; the latest write wins. */ readonly mutateAgentLibrary: ( operations: ReadonlyArray, - ) => Effect.Effect; + ) => Effect.Effect; readonly withSettingsSnapshot: ( use: (settings: ServerSettings) => Effect.Effect, @@ -395,16 +395,15 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( updateSettings: (patch, replicateProfiles = false) => updateTestSettings((currentSettings) => Effect.gen(function* () { - yield* validateMcpGatewayProfileNames( - currentSettings, - patch, - "", - replicateProfiles, - ); const now = DateTime.formatIso(yield* DateTime.now); return applyServerSettingsPatch( currentSettings, - withServerOwnedMcpGatewayProfiles(currentSettings, patch, now, replicateProfiles), + withServerOwnedMcpGatewayProfiles( + currentSettings, + withUniqueMcpGatewayProfileNames(currentSettings, patch), + now, + replicateProfiles, + ), ); }), ), @@ -417,7 +416,12 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( Effect.flatMap((current) => DateTime.now.pipe( Effect.flatMap((now) => - applyAgentLibraryOperations(current, operations, DateTime.formatIso(now)), + applyAgentLibraryOperations( + current, + operations, + DateTime.formatIso(now), + "", + ), ), Effect.map((applied) => { touched = applied.touched; @@ -607,36 +611,24 @@ function selectionSupportsTextGeneration( return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER; } -function validateMcpGatewayProfileNames( +/** A new or renamed agent whose name clashes, ignoring case, gets a numbered suffix instead of failing. */ +function withUniqueMcpGatewayProfileNames( current: ServerSettings, patch: ServerSettingsPatch, - settingsPath: string, - replicateProfiles: boolean, -): Effect.Effect { - if (patch.mcpGatewayProfiles === undefined) return Effect.void; - const fail = (message: string) => - Effect.fail( - new ServerSettingsError({ settingsPath, operation: "normalize", cause: new Error(message) }), - ); - const names = new Set(); - const keys = new Map(); - for (const profile of patch.mcpGatewayProfiles) { - if (names.has(profile.name)) return fail(`Duplicate MCP gateway profile name: ${profile.name}`); - names.add(profile.name); - const key = agentNameKey(profile.name); - keys.set(key, (keys.get(key) ?? 0) + 1); - } - // Replication renames clashes deterministically; stored clashes stay editable until renamed. - if (replicateProfiles) return Effect.void; - for (const profile of patch.mcpGatewayProfiles) { - const existing = current.mcpGatewayProfiles.find( - (stored) => stored.profileId === profile.profileId, +): ServerSettingsPatch { + if (patch.mcpGatewayProfiles === undefined) return patch; + const kept = (profile: McpGatewayProfile) => + current.mcpGatewayProfiles.some( + (stored) => stored.profileId === profile.profileId && stored.name === profile.name, ); - if (existing?.name === profile.name) continue; - if ((keys.get(agentNameKey(profile.name)) ?? 0) > 1) - return fail(`An agent named "${profile.name}" already exists (names ignore case).`); - } - return Effect.void; + // Stored names keep theirs, so existing clashes stay editable until renamed. + const taken = new Set(patch.mcpGatewayProfiles.filter(kept).map((p) => agentNameKey(p.name))); + return { + ...patch, + mcpGatewayProfiles: patch.mcpGatewayProfiles.map((profile) => + kept(profile) ? profile : { ...profile, name: claimAgentName(profile.name, taken) }, + ), + }; } /** Later than every stored library timestamp, so a write always wins its own merge. */ @@ -802,44 +794,18 @@ interface AgentLibraryTouched { } const emptyTouched: AgentLibraryTouched = { profileIds: new Set(), skillIds: new Set() }; -function checkBaseRevision( - itemKind: "agent" | "skill", - itemId: string, - itemName: string | undefined, - existing: { readonly revision: number } | undefined, - baseRevision: number | null, -): AgentLibraryConflictError | undefined { - if (baseRevision === null) { - return existing === undefined - ? undefined - : new AgentLibraryConflictError({ - itemKind, - itemId, - ...(itemName === undefined ? {} : { itemName }), - reason: "exists", - expectedRevision: null, - actualRevision: existing.revision, - }); - } - if (existing?.revision === baseRevision) return undefined; - return new AgentLibraryConflictError({ - itemKind, - itemId, - ...(itemName === undefined ? {} : { itemName }), - reason: existing === undefined ? "missing" : "revision", - expectedRevision: baseRevision, - actualRevision: existing?.revision ?? null, - }); -} - -/** Applies every operation or none; deleting a skill also unassigns it from agents. */ +/** + * Applies every operation or none, last write wins: an upsert overwrites or recreates its item + * and a delete always removes it. Deleting a skill also unassigns it from agents. + */ function applyAgentLibraryOperations( current: ServerSettings, operations: ReadonlyArray, now: string, + settingsPath: string, ): Effect.Effect< { readonly patch: ServerSettingsPatch; readonly touched: AgentLibraryTouched }, - AgentLibraryConflictError + ServerSettingsError > { const mutationTime = agentLibraryMutationTime(current, now); const profiles = new Map( @@ -850,13 +816,15 @@ function applyAgentLibraryOperations( const skillDeletedAt = { ...current.agentSkillDeletedAt }; const profileIds = new Set(); const skillIds = new Set(); + // Never below the writer's copy or the stored item; convergence itself follows updatedAt. const bump = ( existing: T | undefined, + incomingRevision: number, content: Omit, ) => ({ ...content, - revision: (existing?.revision ?? 0) + 1, + revision: Math.max(existing?.revision ?? 0, incomingRevision) + 1, createdAt: existing?.createdAt ?? now, updatedAt: mutationTime, }) as T; @@ -865,48 +833,31 @@ function applyAgentLibraryOperations( case "skill.upsert": { const id = operation.skill.skillId; const existing = skills.get(id); - const conflict = checkBaseRevision( - "skill", - id, - operation.skill.name, - existing, - operation.baseRevision, - ); - if (conflict) return Effect.fail(conflict); const raw = withoutAgentSkillTransportFields(operation.skill); - if (isAgentSkillStub(operation.skill) && existing === undefined) + const stub = isAgentSkillStub(operation.skill); + if (stub && existing === undefined) return Effect.fail( - new AgentLibraryConflictError({ - itemKind: "skill", - itemId: id, - itemName: raw.name, - reason: "missing", + new ServerSettingsError({ + settingsPath, + operation: "normalize", + cause: new Error( + `Skill "${raw.name}" was deleted on this machine and its instructions aren't loaded. Open the skill, then save again.`, + ), }), ); const { resources: rawResources, ...rawContent } = withoutServerOwnedFields(raw); - const resources = isAgentSkillStub(operation.skill) - ? existing?.resources - : (rawResources ?? existing?.resources); + const resources = stub ? existing?.resources : (rawResources ?? existing?.resources); const content = { ...rawContent, - content: isAgentSkillStub(operation.skill) ? existing!.content : raw.content, + content: stub ? existing!.content : raw.content, ...(resources === undefined ? {} : { resources }), }; skillIds.add(id); if (existing && Equal.equals(content, withoutServerOwnedFields(existing))) break; - skills.set(id, bump(existing, content)); + skills.set(id, bump(existing, operation.skill.revision, content)); break; } case "skill.delete": { - const existing = skills.get(operation.skillId); - const conflict = checkBaseRevision( - "skill", - operation.skillId, - existing?.name, - existing, - operation.baseRevision, - ); - if (conflict) return Effect.fail(conflict); skills.delete(operation.skillId); skillDeletedAt[operation.skillId] = mutationTime; skillIds.add(operation.skillId); @@ -914,7 +865,7 @@ function applyAgentLibraryOperations( if (!profile.skillIds?.includes(operation.skillId)) continue; profiles.set( profile.profileId, - bump(profile, { + bump(profile, 0, { ...withoutServerOwnedFields(profile), skillIds: profile.skillIds.filter((skillId) => skillId !== operation.skillId), }), @@ -926,45 +877,23 @@ function applyAgentLibraryOperations( case "profile.upsert": { const id = operation.profile.profileId; const existing = profiles.get(id); - const conflict = checkBaseRevision( - "agent", - id, - operation.profile.name, - existing, - operation.baseRevision, + const { name, ...rest } = withLegacyAgentIcon(withoutServerOwnedFields(operation.profile)); + // A new or renamed agent whose name clashes ignoring case takes a suffix, as sync does. + const taken = new Set( + [...profiles.values()] + .filter((profile) => profile.profileId !== id) + .map((profile) => agentNameKey(profile.name)), ); - if (conflict) return Effect.fail(conflict); - const key = agentNameKey(operation.profile.name); - if ( - existing?.name !== operation.profile.name && - [...profiles.values()].some( - (profile) => profile.profileId !== id && agentNameKey(profile.name) === key, - ) - ) - return Effect.fail( - new AgentLibraryConflictError({ - itemKind: "agent", - itemId: id, - itemName: operation.profile.name, - reason: "name", - }), - ); - const content = withLegacyAgentIcon(withoutServerOwnedFields(operation.profile)); + const content = { + ...rest, + name: existing?.name === name ? name : claimAgentName(name, taken), + }; profileIds.add(id); if (existing && Equal.equals(content, withoutServerOwnedFields(existing))) break; - profiles.set(id, bump(existing, content)); + profiles.set(id, bump(existing, operation.profile.revision, content)); break; } case "profile.delete": { - const existing = profiles.get(operation.profileId); - const conflict = checkBaseRevision( - "agent", - operation.profileId, - existing?.name, - existing, - operation.baseRevision, - ); - if (conflict) return Effect.fail(conflict); profiles.delete(operation.profileId); profileDeletedAt[operation.profileId] = mutationTime; profileIds.add(operation.profileId); @@ -1866,11 +1795,15 @@ const make = Effect.gen(function* () { updateAndPersistSettings(patch, (current) => Effect.gen(function* () { yield* ensureSecretProviderWritesAllowed(patch, settingsPath); - yield* validateMcpGatewayProfileNames(current, patch, settingsPath, replicateProfiles); const now = DateTime.formatIso(yield* DateTime.now); return applyServerSettingsPatch( current, - withServerOwnedMcpGatewayProfiles(current, patch, now, replicateProfiles), + withServerOwnedMcpGatewayProfiles( + current, + withUniqueMcpGatewayProfileNames(current, patch), + now, + replicateProfiles, + ), ); }), ), @@ -1878,10 +1811,15 @@ const make = Effect.gen(function* () { operations: ReadonlyArray, ) { let touched: AgentLibraryTouched = emptyTouched; - const settings = yield* updateAndPersistSettings({}, (current) => + const settings = yield* updateAndPersistSettings({}, (current) => Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); - const applied = yield* applyAgentLibraryOperations(current, operations, now); + const applied = yield* applyAgentLibraryOperations( + current, + operations, + now, + settingsPath, + ); touched = applied.touched; return applyServerSettingsPatch(current, applied.patch); }), diff --git a/apps/web/src/components/agents/AgentEditor.tsx b/apps/web/src/components/agents/AgentEditor.tsx index 7348279f00ecd..b0207edc3614e 100644 --- a/apps/web/src/components/agents/AgentEditor.tsx +++ b/apps/web/src/components/agents/AgentEditor.tsx @@ -12,7 +12,7 @@ import { SelectButton } from "../ui/select"; import { Switch } from "../ui/switch"; import { agentModelOptions, presetProviderLabel } from "./agentModelCatalog"; import type { AgentSkill, McpGatewayProfile, ServerProvider } from "@t3tools/contracts"; -import { MCP_GATEWAY_RUNTIME_MODE_LABELS } from "@t3tools/contracts"; +import { agentNameKey, MCP_GATEWAY_RUNTIME_MODE_LABELS } from "@t3tools/contracts"; import { agentColors, agentHasAdvancedSettings, @@ -137,6 +137,12 @@ export function AgentEditor({ ); const [error, setError] = useState(""); const [saving, setSaving] = useState(false); + // Kept names stay editable, as the server keeps a stored clash until it is renamed. + const nameTaken = + name.trim() !== profile?.name && + profiles.some( + (p) => p.profileId !== profile?.profileId && agentNameKey(p.name) === agentNameKey(name), + ); const availableProviders = providers.filter( (provider) => environmentIds.length === 0 || environmentIds.includes(provider.environmentId), ); @@ -188,17 +194,7 @@ export function AgentEditor({ className="agent-form" onSubmit={async (event) => { event.preventDefault(); - const nameKey = name.trim().toLocaleLowerCase(); - if ( - profiles.some( - (p) => - p.profileId !== profile?.profileId && - p.name.trim().toLocaleLowerCase() === nameKey, - ) - ) { - setError("An agent with this name already exists."); - return; - } + if (nameTaken) return; setSaving(true); setError(""); const normalizedTags = normalizeAgentTags(tags); @@ -252,9 +248,15 @@ export function AgentEditor({ placeholder="Write, Review, Research…" value={name} onChange={(e) => setName(e.target.value)} + aria-invalid={nameTaken || undefined} /> + {nameTaken && ( +

+ Another agent is already called “{name.trim()}”. Names ignore case. +

+ )}