am
2026-08-14 14:04:04 -07:00
parent 9c2f05346f
commit 7f5c4f7b59
16 changed files with 540 additions and 199 deletions

View File

@@ -47,6 +47,11 @@ import {
AgentModelField,
} from "@/features/agents/ui/agentConfigControls";
import { PersonaProviderApiKeyField } from "@/features/agents/ui/PersonaProviderApiKeyField";
import {
OPENAI_COMPAT_BASE_URL,
OpenAiCompatibleBaseUrlField,
openAiCompatibleBaseUrlError,
} from "@/features/agents/ui/OpenAiCompatibleBaseUrlField";
import { usePersonaModelDiscovery } from "@/features/agents/ui/usePersonaModelDiscovery";
import { resolveModelLabel } from "@/features/agents/lib/formatAgentModelLabel";
import {
@@ -98,7 +103,6 @@ const autoSelectModelOnProviderChange = true;
const disableModelSelectDuringDiscovery = false;
const preserveCredentialEnvVarsOnProviderChange = true;
const requireProviderForModelAndEffort = true;
/** The canonical behavior contract, exported for the contract test. */
export const CANONICAL_CONFIG_BEHAVIORS = {
autoSelectModelOnProviderChange,
@@ -106,7 +110,6 @@ export const CANONICAL_CONFIG_BEHAVIORS = {
preserveCredentialEnvVarsOnProviderChange,
requireProviderForModelAndEffort,
} as const;
/** Disclosure preset → the eight visibility decisions it owns. Exported for the contract test. */
export function resolveDisclosure(disclosure: AgentConfigDisclosure) {
const full = disclosure !== "onboarding-essential";
@@ -121,7 +124,6 @@ export function resolveDisclosure(disclosure: AgentConfigDisclosure) {
showUnavailableEffortOptions: full,
} as const;
}
export function shouldRevealDependentConfigFields({
disclosure,
providerFieldVisible,
@@ -137,7 +139,6 @@ export function shouldRevealDependentConfigFields({
providerValue.trim().length > 0
);
}
/** Whether the status line under the Model field renders. Discovery warnings bypass onboarding-essential so first-run failures are never invisible. */
export function shouldShowModelStatusMessage(
showDescriptions: boolean,
@@ -145,7 +146,6 @@ export function shouldShowModelStatusMessage(
): boolean {
return showDescriptions || status !== null;
}
/**
* Renders the Model control given discovery state. Optional-model harnesses omit it while
* discovery is loading or after confirmed successful empty; failures keep it for the #2246 UI.
@@ -174,7 +174,6 @@ export function shouldRenderModelControl({
// Omit only on confirmed successful empty — not on failure/unavailable.
return !modelDiscoverySuccessfulEmpty;
}
export type AgentConfigFieldsProps = {
bakedEnv: BakedEnvEntry[];
selectedRuntime: AcpRuntimeCatalogEntry | undefined;
@@ -210,7 +209,6 @@ export type AgentConfigFieldsProps = {
useCustomSelect?: boolean;
useChevronSelectIcon?: boolean;
};
export function AgentConfigFields({
bakedEnv,
selectedRuntime,
@@ -240,7 +238,6 @@ export function AgentConfigFields({
showRequiredIndicators,
showUnavailableEffortOptions,
} = resolveDisclosure(disclosure);
const fieldModel = React.useMemo(
() =>
deriveAgentConfigFieldModel({
@@ -255,7 +252,6 @@ export function AgentConfigFields({
effortField?.currentPersistence.kind === "envVar"
? effortField.currentPersistence.key
: null;
const numericDescriptors = fieldModel.fields.filter(
(d): d is NumericDescriptor =>
(d.kind === "maxOutputTokens" ||
@@ -307,7 +303,6 @@ export function AgentConfigFields({
]),
[bakedEnv, allStructuredKeys],
);
const providerValue = providerFieldVisible ? (config.provider ?? "") : "";
const providerForDiscovery =
providerFieldVisible && !isCustomProvider
@@ -343,6 +338,7 @@ export function AgentConfigFields({
apiKeyEnvVar,
apiKeyFileSatisfied,
apiKeyInherited,
apiKeyRequired,
apiKeyValue,
credentialsValid,
} = getGlobalAgentCredentialState({
@@ -352,12 +348,23 @@ export function AgentConfigFields({
runtimeFileConfig,
runtimeId: credentialRuntimeId,
});
const compatibleBaseUrl = config.env_vars[OPENAI_COMPAT_BASE_URL] ?? "";
const compatibleBaseUrlInherited =
effectiveProvider === "openai-compat" &&
compatibleBaseUrl.trim().length === 0 &&
credentialsValid;
const compatibleBaseUrlValid =
effectiveProvider !== "openai-compat" ||
compatibleBaseUrlInherited ||
openAiCompatibleBaseUrlError(compatibleBaseUrl) === null;
const configIsValid =
selectedRuntimeId.length > 0 && modelIsValid && credentialsValid;
selectedRuntimeId.length > 0 &&
modelIsValid &&
credentialsValid &&
compatibleBaseUrlValid;
React.useEffect(() => {
onValidityChange?.(configIsValid);
}, [configIsValid, onValidityChange]);
const {
discoveredModelOptions,
modelDiscoveryLoading,
@@ -383,7 +390,6 @@ export function AgentConfigFields({
modelIsOptional,
showCustomModelOption,
});
// Mount-time healing policy: onboarding page 4 edits the root config during
// first-run (no higher layers to inherit from), so acting on open is safe
// and intentional there — it heals stale state and picks a valid model.
@@ -401,7 +407,6 @@ export function AgentConfigFields({
const mayMutateDependentFieldsRef = React.useRef(false);
mayMutateDependentFieldsRef.current =
healOnMount || userEditedProviderRef.current;
const autoSelectedModelScopeRef = React.useRef<string | null>(null);
React.useEffect(() => {
if (!autoSelectModelOnProviderChange) return;
@@ -415,12 +420,10 @@ export function AgentConfigFields({
if (modelDiscoveryLoading || discoveredModelOptions === null) return;
const selectionScope = `${selectedRuntimeId}:${trimmedProvider}`;
if (autoSelectedModelScopeRef.current === selectionScope) return;
const firstModel = discoveredModelOptions.find(
(option) => option.id.trim().length > 0,
);
if (!firstModel) return;
autoSelectedModelScopeRef.current = selectionScope;
onCustomModelEditingChange(false);
onConfigChange({ ...config, model: firstModel.id });
@@ -434,11 +437,9 @@ export function AgentConfigFields({
providerForDiscovery,
selectedRuntimeId,
]);
const currentEffortForAutoClear = effortPersistenceKey
? (config.env_vars[effortPersistenceKey] ?? "")
: "";
// When the selected harness changes outside this component (Back → setup
// page → choose a different harness → Next), the saved model can belong to
// the old harness. In onboarding, heal that stale value as soon as the new
@@ -452,7 +453,6 @@ export function AgentConfigFields({
const currentModel = (config.model ?? "").trim();
if (currentModel.length === 0) return;
if (modelDiscoveryLoading) return;
const catalogMiss =
discoveredModelOptions !== null &&
!discoveredModelOptions.some(
@@ -461,7 +461,6 @@ export function AgentConfigFields({
const omittedAfterSuccessfulEmpty =
modelIsOptional && !modelControlVisible && modelDiscoverySuccessfulEmpty;
if (!catalogMiss && !omittedAfterSuccessfulEmpty) return;
const nextEnvVars = { ...config.env_vars };
if (effortPersistenceKey) delete nextEnvVars[effortPersistenceKey];
onCustomModelEditingChange(false);
@@ -478,7 +477,6 @@ export function AgentConfigFields({
healOnMount,
effortPersistenceKey,
]);
// Orphan-model clearing follows the mount-time healing policy above: the
// backend resolves provider and model independently across layers
// (agent → definition → global), so a saved global model WITHOUT a global
@@ -496,7 +494,6 @@ export function AgentConfigFields({
) {
return;
}
const nextEnvVars = { ...config.env_vars };
if (effortPersistenceKey) delete nextEnvVars[effortPersistenceKey];
onCustomModelEditingChange(false);
@@ -522,7 +519,6 @@ export function AgentConfigFields({
onConfigChange({ ...config, env_vars: nextEnvVars });
},
});
function handleProviderChange(value: string) {
userEditedProviderRef.current = true;
const previousApiKey = getProviderApiKeyEnvVar(effectiveProvider);
@@ -549,7 +545,6 @@ export function AgentConfigFields({
delete nextEnvVars[previousApiKey];
}
const providerChanged = nextProvider !== (config.provider ?? null);
onIsCustomProviderChange(false);
onConfigChange({
...config,
@@ -563,28 +558,23 @@ export function AgentConfigFields({
: config.model,
});
}
function handleCustomProviderInput(value: string) {
onConfigChange({ ...config, provider: value || null });
}
function handleModelChange(value: string) {
onConfigChange({
...config,
model: config.provider === "relay-mesh" ? value || "auto" : value || null,
});
}
function handleEnvVarsChange(next: Record<string, string>) {
onConfigChange({ ...config, env_vars: next });
}
const handleNumericEnvVarChange = (key: string, value: string) => {
const next = { ...config.env_vars, [key]: value };
if (value === "") delete next[key];
onConfigChange({ ...config, env_vars: next });
};
// On internal Block builds, BUZZ_AGENT_PROVIDER is baked in and a boot
// migration rewrites v1→v2. Hide the legacy v1 option so it is not offered
// for new selections; OSS builds show it.
@@ -609,7 +599,6 @@ export function AgentConfigFields({
const providerSelectValue = isCustomProvider
? CUSTOM_PROVIDER_DROPDOWN_VALUE
: providerValue || AUTO_PROVIDER_DROPDOWN_VALUE;
const providerZeroLabel = React.useMemo(() => {
if (!bakedProvider) return null;
return getBakedProviderInheritLabel(bakedProvider, providerOptions);
@@ -623,7 +612,6 @@ export function AgentConfigFields({
}
return "Select a provider";
}, [bakedProvider, providerOptions]);
const implicitEffortProvider =
selectedRuntimeId === "claude"
? "anthropic"
@@ -639,7 +627,6 @@ export function AgentConfigFields({
? (config.env_vars[effortPersistenceKey] ?? "")
: "";
const effortFieldVisible = showEffortField && effortField !== undefined;
const progressiveDefaults = disclosure === "progressive-defaults";
const fieldClassName = unstyled
? progressiveDefaults
@@ -708,7 +695,6 @@ export function AgentConfigFields({
))}
</select>
);
const providerContent = providerFieldVisible ? (
<div className={fieldClassName}>
<label
@@ -740,13 +726,15 @@ export function AgentConfigFields({
) : null}
</div>
) : null;
const advancedEditorBlock = (
<>
<EnvVarsEditor
fileSatisfiedKeys={advancedFileSatisfiedEnvKeys}
hiddenKeys={[
...(apiKeyEnvVar ? [apiKeyEnvVar] : []),
...(effectiveProvider === "openai-compat"
? [OPENAI_COMPAT_BASE_URL]
: []),
...allStructuredKeys,
]}
inheritedRows={bakedGenericRows}
@@ -767,9 +755,23 @@ export function AgentConfigFields({
) : null}
</>
);
const dependentContent = (
<>
{providerFieldVisible && effectiveProvider === "openai-compat" ? (
<div className={blockClassName}>
<OpenAiCompatibleBaseUrlField
disabled={false}
inherited={compatibleBaseUrlInherited}
onValueChange={(next) =>
handleEnvVarsChange({
...config.env_vars,
[OPENAI_COMPAT_BASE_URL]: next,
})
}
value={compatibleBaseUrl}
/>
</div>
) : null}
{providerFieldVisible && apiKeyEnvVar ? (
<div className={blockClassName}>
<PersonaProviderApiKeyField
@@ -781,7 +783,9 @@ export function AgentConfigFields({
: "Provided by this build"
}
isInherited={apiKeyInherited}
isRequired={!apiKeyInherited && apiKeyValue.length === 0}
isRequired={
apiKeyRequired && !apiKeyInherited && apiKeyValue.length === 0
}
label={getProviderApiKeyLabel(effectiveProvider) ?? "API Key"}
onValueChange={(value) =>
onConfigChange({
@@ -793,7 +797,6 @@ export function AgentConfigFields({
/>
</div>
) : null}
{/* Model field — omitted only after confirmed successful empty discovery */}
{modelControlVisible ? (
<div className={showDescriptions ? fieldClassName : undefined}>
@@ -846,7 +849,6 @@ export function AgentConfigFields({
/>
</div>
) : null}
{/* Thinking / Effort */}
{effortFieldVisible ? (
<div className={blockClassName}>
@@ -892,7 +894,6 @@ export function AgentConfigFields({
/>
</div>
) : null}
{showAdvancedFields ? (
<div className={cn(blockClassName, "space-y-3")}>
<CardMintKeyCue envVars={config.env_vars} />
@@ -945,7 +946,6 @@ export function AgentConfigFields({
) : null}
</>
);
const content = (
<>
{providerContent}
@@ -977,7 +977,6 @@ export function AgentConfigFields({
)}
</>
);
if (unstyled) {
return (
<div
@@ -988,7 +987,6 @@ export function AgentConfigFields({
</div>
);
}
return (
<SettingsOptionGroup data-testid="global-agent-config-fields">
{content}

View File

@@ -17,6 +17,11 @@ import { PersonaAdvancedFields } from "./PersonaAdvancedFields";
import { PersonaModelField } from "./PersonaModelField";
import { runtimeAvailabilityWarning } from "./runtimeAvailabilityWarning";
import { PersonaProviderApiKeyField } from "./PersonaProviderApiKeyField";
import {
OPENAI_COMPAT_BASE_URL,
OpenAiCompatibleBaseUrlField,
openAiCompatibleBaseUrlError,
} from "./OpenAiCompatibleBaseUrlField";
import {
canSubmitPersonaDialog,
formatPersonaNamePoolText,
@@ -260,7 +265,6 @@ export function AgentDefinitionDialog({
isRuntimeAutoSeededRef.current = true;
}
}, [defaultRuntime, initialValues, open, runtime, runtimesLoading]);
// Keep an inherited Create runtime synced with defaults saved in-place.
React.useEffect(() => {
if (
@@ -275,7 +279,6 @@ export function AgentDefinitionDialog({
) {
return;
}
if (runtime !== defaultRuntime.id) setRuntime(defaultRuntime.id);
isRuntimeAutoSeededRef.current = true;
hasSeededForOpenRef.current = true;
@@ -287,7 +290,6 @@ export function AgentDefinitionDialog({
runtime,
runtimesLoading,
]);
// Keep setup guidance reachable when no available runtime can be inherited.
React.useEffect(() => {
if (
@@ -300,7 +302,6 @@ export function AgentDefinitionDialog({
setAiConfigurationMode("custom");
}
}, [defaultRuntime, isCreateMode, open, runtime, runtimesLoading]);
function handleOpenChange(next: boolean) {
// The catalog may veto embedded close requests; preserve the draft until unmount.
if (!next && !embedded) {
@@ -324,15 +325,12 @@ export function AgentDefinitionDialog({
// isRuntimeAutoSeededRef and hasSeededForOpenRef are NOT reset here — the
// [initialValues, open] effect resets both when the dialog re-opens.
}
onOpenChange(next);
}
async function handleSubmit() {
// D1: the same localModeSatisfied gate as canSubmit prevents form-submit
// (Enter) from bypassing a missing credential.
if (!initialValues || !localModeSatisfied || !canSubmit) return;
const {
runtime: runtimeForSubmit,
model: modelForSubmit,
@@ -370,7 +368,6 @@ export function AgentDefinitionDialog({
"id" in initialValues,
),
};
if ("id" in initialValues) {
await onSubmit(
{
@@ -383,15 +380,12 @@ export function AgentDefinitionDialog({
);
return;
}
await onSubmit(baseInput, { publishCatalogUpdates: false });
}
function handleSubmitForm(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
void handleSubmit();
}
const selectedRuntime = runtimes.find((p) => p.id === runtime);
const blankRuntimeModelProviderEditable =
initialModelProviderEditableWithoutRuntime && runtime.trim().length === 0;
@@ -494,6 +488,14 @@ export function AgentDefinitionDialog({
selectedRuntime?.availability === "available";
// Gate model/provider validity through missingNormalizedFields — single
// source of truth with the readiness gate so display and Save can't drift.
const compatibleBaseUrl = envVars[OPENAI_COMPAT_BASE_URL] ?? "";
const compatibleBaseUrlInherited =
compatibleBaseUrl.trim().length === 0 &&
localModeGate.missingEnvKeys.every((key) => key !== OPENAI_COMPAT_BASE_URL);
const compatibleBaseUrlValid =
effectiveProvider !== "openai-compat" ||
compatibleBaseUrlInherited ||
openAiCompatibleBaseUrlError(compatibleBaseUrl) === null;
const canSubmit =
canSubmitPersonaDialog({ displayName, isPending }) &&
(!isCreateMode || runtime.trim().length > 0) &&
@@ -505,9 +507,9 @@ export function AgentDefinitionDialog({
// D1: localModeSatisfied covers both missingNormalizedFields AND
// missingEnvKeys — credential env keys now block submit, not just display.
localModeSatisfied &&
compatibleBaseUrlValid &&
customAiPairSatisfied &&
!isAvatarUploadPending;
// Merge global env as the base layer so credential keys satisfied via global
// config are available to model discovery — same rationale as in AgentInstanceEditDialog.
const envVarsForDiscovery = React.useMemo(
@@ -623,7 +625,6 @@ export function AgentDefinitionDialog({
const advancedFieldsTransition = shouldReduceMotion
? { duration: 0 }
: ADVANCED_FIELDS_MOTION_TRANSITION;
React.useEffect(() => {
if (
!open ||
@@ -637,7 +638,6 @@ export function AgentDefinitionDialog({
) {
return;
}
setModel("");
setIsCustomModelEditing(false);
}, [
@@ -648,7 +648,6 @@ export function AgentDefinitionDialog({
effectiveProvider,
runtime,
]);
const selection: RuntimeModelProviderSelection = {
provider,
model,
@@ -656,7 +655,6 @@ export function AgentDefinitionDialog({
isCustomModelEditing,
envVars,
};
function applySelection(next: RuntimeModelProviderSelection) {
setProvider(next.provider);
setModel(next.model);
@@ -664,7 +662,6 @@ export function AgentDefinitionDialog({
setIsCustomModelEditing(next.isCustomModelEditing);
setEnvVars(next.envVars);
}
function handleRuntimeDropdownChange(nextValue: string) {
const action = runtimeDropdownAction(nextValue);
if (action.kind === "add-custom-harness") {
@@ -687,7 +684,6 @@ export function AgentDefinitionDialog({
}),
);
}
// Routed through the normal change handler so a harness registered inline
// resets model/provider exactly as a hand-picked one would. Scoped to `open`
// so a pending id can't outlive the dialog that started the registration.
@@ -696,7 +692,6 @@ export function AgentDefinitionDialog({
handleRuntimeDropdownChange,
open,
);
function handleProviderDropdownChange(nextValue: string) {
setHasUserChanges(true);
const nextProvider =
@@ -714,7 +709,6 @@ export function AgentDefinitionDialog({
model: nextProvider === "relay-mesh" ? "auto" : nextSelection.model,
});
}
function handleModelDropdownChange(nextValue: string) {
setHasUserChanges(true);
applySelection(
@@ -725,7 +719,6 @@ export function AgentDefinitionDialog({
}),
);
}
const footer = (
<AgentDefinitionDialogFooter
canSubmit={canSubmit}
@@ -757,7 +750,6 @@ export function AgentDefinitionDialog({
setAvatarUrl(nextAvatarUrl);
}}
/>
<div className="space-y-5">
<div className="space-y-1.5">
<label
@@ -786,7 +778,6 @@ export function AgentDefinitionDialog({
/>
</div>
</div>
<div className="space-y-1.5">
<label
className="text-sm font-medium text-foreground"
@@ -808,7 +799,6 @@ export function AgentDefinitionDialog({
/>
</div>
</div>
{modelFieldVisible ? (
<AgentAiConfigurationModeField
mode={aiConfigurationMode}
@@ -816,7 +806,6 @@ export function AgentDefinitionDialog({
onModeChange={handleAiConfigurationModeChange}
/>
) : null}
<div
className="space-y-5"
data-testid={`agent-${aiConfigurationMode}-configuration-section`}
@@ -831,7 +820,6 @@ export function AgentDefinitionDialog({
warning={runtimeWarning}
/>
) : null}
{llmProviderFieldVisible && aiConfigurationMode === "custom" ? (
<div className="space-y-1.5">
<RequiredFieldLabel
@@ -875,7 +863,21 @@ export function AgentDefinitionDialog({
) : null}
</div>
) : null}
{llmProviderFieldVisible &&
aiConfigurationMode === "custom" &&
effectiveProvider === "openai-compat" ? (
<OpenAiCompatibleBaseUrlField
disabled={isPending}
inherited={compatibleBaseUrlInherited}
onValueChange={(next) =>
setEnvVars((prev) => ({
...prev,
[OPENAI_COMPAT_BASE_URL]: next,
}))
}
value={compatibleBaseUrl}
/>
) : null}
{llmProviderFieldVisible &&
aiConfigurationMode === "custom" &&
topLevelSecretEnvVar ? (
@@ -895,7 +897,6 @@ export function AgentDefinitionDialog({
value={apiKeyValue}
/>
) : null}
<AnimatePresence initial={false}>
{modelFieldVisible && aiConfigurationMode === "custom" ? (
<PersonaModelField
@@ -915,7 +916,6 @@ export function AgentDefinitionDialog({
/>
) : null}
</AnimatePresence>
{aiConfigurationMode === "defaults" ? (
<AgentCreateAiDefaultsSummary
canChooseProvider={runtimeCanChooseLlmProvider}
@@ -929,19 +929,16 @@ export function AgentDefinitionDialog({
/>
) : null}
</div>
<AgentDefaultsDialog
onOpenChange={setAiDefaultsOpen}
open={runtimeCanChooseLlmProvider && aiDefaultsOpen}
returnFocusRef={aiDefaultsTriggerRef}
/>
<AddCustomHarnessDialog
onOpenChange={setIsAddHarnessOpen}
onSaved={selectSavedHarness}
open={isAddHarnessOpen}
/>
<div className="space-y-3">
<button
aria-expanded={showAdvancedFields}
@@ -985,9 +982,12 @@ export function AgentDefinitionDialog({
disabled={isPending}
envVars={envVars}
fileSatisfiedEnvKeys={localModeGate.fileSatisfiedEnvKeys}
hiddenEnvKeys={
topLevelSecretEnvVar ? [topLevelSecretEnvVar] : []
}
hiddenEnvKeys={[
...(topLevelSecretEnvVar ? [topLevelSecretEnvVar] : []),
...(effectiveProvider === "openai-compat"
? [OPENAI_COMPAT_BASE_URL]
: []),
]}
inheritedEnvVars={inheritedEnvVarsForAdvanced}
model={model}
modelTuningRuntimeId={runtime}
@@ -1007,14 +1007,12 @@ export function AgentDefinitionDialog({
) : null}
</AnimatePresence>
</div>
{error ? (
<p className="text-sm text-destructive">{error.message}</p>
) : null}
</div>
</form>
);
return (
<AgentDefinitionDialogShell
description={description}

View File

@@ -75,6 +75,11 @@ import {
usePersonaModelDiscovery,
} from "./usePersonaModelDiscovery";
import { PersonaProviderApiKeyField } from "./PersonaProviderApiKeyField";
import {
OPENAI_COMPAT_BASE_URL,
OpenAiCompatibleBaseUrlField,
openAiCompatibleBaseUrlError,
} from "./OpenAiCompatibleBaseUrlField";
import {
getBakedModelInheritLabel,
getBakedProviderInheritLabel,
@@ -392,12 +397,10 @@ export function AgentInstanceEditDialog({
globalEnvVars: globalConfig.env_vars,
personaEnvVars: inheritHarness ? inheritedEnvVars : undefined,
});
const { data: bakedEnvKeys } = useBakedBuildEnvKeysQuery({ enabled: open });
const { data: agentAccessOwnerOnly } = useAgentAccessOwnerOnlyQuery({
enabled: open,
});
// Merge global env as the base layer so credential keys satisfied via global
// config (e.g. ANTHROPIC_API_KEY) are available to model discovery. Use
// `inheritedSubmission.envVars` (the same snapshot the credential gate
@@ -412,7 +415,6 @@ export function AgentInstanceEditDialog({
(inheritedSubmission.provider ?? "").trim() ||
inheritedProviderDefault.value;
const providerForDiscovery = llmProviderFieldVisible ? effectiveProvider : "";
const {
discoveredModelOptions,
modelDiscoveryLoading,
@@ -426,10 +428,12 @@ export function AgentInstanceEditDialog({
selectedRuntime,
});
// D2/D3: the top-level API key owns display while the readiness gate keeps the
// complete required-key list; advancedRequiredEnvKeys drives EnvVarsEditor
// display only. The effective snapshot covers persona inheritance during an
// instance inherit transition.
const providerApiKeyEnvVar = getProviderApiKeyEnvVar(effectiveProvider);
const personaSatisfied =
providerApiKeyEnvVar != null &&
@@ -466,7 +470,6 @@ export function AgentInstanceEditDialog({
) {
return;
}
setModel("");
setIsCustomModelEditing(false);
}, [
@@ -477,7 +480,6 @@ export function AgentInstanceEditDialog({
selectedRuntime,
selectedRuntimeId,
]);
const selection: RuntimeModelProviderSelection = {
provider,
model,
@@ -485,7 +487,6 @@ export function AgentInstanceEditDialog({
isCustomModelEditing,
envVars,
};
function applySelection(next: RuntimeModelProviderSelection) {
setProvider(next.provider);
setModel(next.model);
@@ -493,7 +494,6 @@ export function AgentInstanceEditDialog({
setIsCustomModelEditing(next.isCustomModelEditing);
setEnvVars(next.envVars);
}
function handleRuntimeDropdownChange(nextValue: string) {
const action = runtimeDropdownAction(nextValue);
if (action.kind === "add-custom-harness") {
@@ -503,16 +503,12 @@ export function AgentInstanceEditDialog({
const nextRuntimeId = action.runtimeId;
const previousRuntimeId = selectedRuntimeId;
const nextRuntime = runtimes.find((r) => r.id === nextRuntimeId);
// Mark that the user has made an explicit runtime choice. The catalog-arrival
// effect will no longer overwrite selectedRuntimeId after this point.
runtimeTouched.current = true;
const resolvedRuntimeId = nextRuntimeId || "custom";
setSelectedRuntimeId(resolvedRuntimeId);
const isCustomCommand = resolvedRuntimeId === "custom";
// Only pin the harness when the selection can actually supply a command:
// - "Custom command": the Advanced command input becomes editable, so the
// user provides the command.
@@ -526,7 +522,6 @@ export function AgentInstanceEditDialog({
if (isCustomCommand || nextRuntime?.command) {
setInheritHarness(false);
}
// When switching to a catalog-known runtime, update the agent command to
// its resolved command so the command field stays consistent.
if (nextRuntime?.command) {
@@ -534,7 +529,6 @@ export function AgentInstanceEditDialog({
const newArgs = nextRuntime.defaultArgs.join(",");
setAgentArgs(newArgs);
}
applySelection(
selectionOnRuntimeChange(selection, {
previousRuntime: previousRuntimeId,
@@ -546,7 +540,6 @@ export function AgentInstanceEditDialog({
}),
);
}
// Routed through the normal change handler so a harness registered inline
// pins its command and resets model/provider like a hand-picked one. Scoped
// to `open` so a pending id can't outlive the dialog that started the
@@ -556,7 +549,6 @@ export function AgentInstanceEditDialog({
handleRuntimeDropdownChange,
open,
);
function handleProviderDropdownChange(nextValue: string) {
const nextProvider =
nextValue === AUTO_PROVIDER_DROPDOWN_VALUE ? "" : nextValue;
@@ -576,7 +568,6 @@ export function AgentInstanceEditDialog({
model: nextProvider === "relay-mesh" ? "auto" : nextSelection.model,
});
}
function handleModelDropdownChange(nextValue: string) {
applySelection(
selectionOnModelDropdownChange(selection, {
@@ -586,11 +577,9 @@ export function AgentInstanceEditDialog({
}),
);
}
function handleOpenChange(next: boolean) {
onOpenChange(next);
}
const providerValid = isEditAgentProviderSaveValid({
llmProviderFieldVisible,
currentProvider: provider,
@@ -598,7 +587,17 @@ export function AgentInstanceEditDialog({
globalProvider: inheritedProviderDefault.value,
originalRuntimeSupportsProvider,
});
const compatibleBaseUrl = envVars[OPENAI_COMPAT_BASE_URL] ?? "";
const compatibleBaseUrlInherited =
!(OPENAI_COMPAT_BASE_URL in envVars) &&
((inheritedSubmission.envVars[OPENAI_COMPAT_BASE_URL] ?? "").trim().length >
0 ||
(globalConfig.env_vars[OPENAI_COMPAT_BASE_URL] ?? "").trim().length > 0 ||
fileSatisfiedEnvKeys.includes(OPENAI_COMPAT_BASE_URL));
const compatibleBaseUrlValid =
effectiveProvider !== "openai-compat" ||
compatibleBaseUrlInherited ||
openAiCompatibleBaseUrlError(compatibleBaseUrl) === null;
const canSubmit =
computeEditAgentFormValidity({
name,
@@ -613,9 +612,9 @@ export function AgentInstanceEditDialog({
requiredEnvKeyMissing,
}) &&
providerValid &&
compatibleBaseUrlValid &&
!updateMutation.isPending &&
!isAvatarUploadPending;
async function handleSubmit() {
try {
const parsedParallelism = Number.parseInt(parallelism, 10);
@@ -627,7 +626,6 @@ export function AgentInstanceEditDialog({
// provider-backed inherit-transition carries the persona model (readiness
// requires one) and a deliberate local model still wins.
const normalizedModel = inheritedSubmission.model;
// Harness pin resolution — see resolveAgentCommandUpdate for the full
// sentinel/pin/no-op contract, including the inherit→pin transition where
// the prefilled command equals the original but must still be pinned.
@@ -637,7 +635,6 @@ export function AgentInstanceEditDialog({
originalAgentCommand: agent.agentCommand,
agentCommandOverride: agent.agentCommandOverride ?? null,
});
// Classify the effective post-submit runtime's provider capability as a
// tri-state: "capable" persists the provider, "locked" clears it (only
// when we KNOW it's provider-locked, e.g. Claude), "unknown" OMITS it so a
@@ -650,7 +647,6 @@ export function AgentInstanceEditDialog({
prospectiveRuntimeId,
runtimeSupportsLlmProviderSelection(prospectiveRuntimeId),
);
// Provider + env to persist — the shared inherited-submission snapshot
// (same values the credential gate validates), so gate ↔ record ↔ spawn
// all agree. See resolveInheritedRuntimeSubmission.
@@ -724,7 +720,6 @@ export function AgentInstanceEditDialog({
? respondToAllowlist
: undefined,
};
const result = await updateMutation.mutateAsync(input);
if (autoRestartOnConfigChange !== agent.autoRestartOnConfigChange) {
// Standalone setter (mirrors start-on-app-launch) — not part of
@@ -764,7 +759,6 @@ export function AgentInstanceEditDialog({
// React Query stores the error; keep dialog open and render it inline.
}
}
// Model and provider field derived state
const normalizedConfig = configSurfaceQuery.data?.normalized;
const modelRequired = isMissingRequiredDropdownField(
@@ -804,7 +798,6 @@ export function AgentInstanceEditDialog({
loading: modelDiscoveryLoading,
status: modelDiscoveryStatus,
});
// Provider field derived state
const trimmedProvider = provider.trim();
const hideProviderIds = React.useMemo(
@@ -838,13 +831,11 @@ export function AgentInstanceEditDialog({
})),
{ label: "Custom provider...", value: CUSTOM_PROVIDER_DROPDOWN_VALUE },
];
const previewLabel = name.trim() || "Agent name";
const previewAvatarUrl = avatarUrl.trim() || null;
const advancedFieldsTransition = shouldReduceMotion
? { duration: 0 }
: ADVANCED_FIELDS_MOTION_TRANSITION;
return (
<Dialog onOpenChange={handleOpenChange} open={open}>
<ChooserDialogContent
@@ -943,7 +934,6 @@ export function AgentInstanceEditDialog({
onModeChange={setRespondTo}
/>
<RunOnSummarySection backend={agent.backend} />
{/* Provider (runtime) */}
<div className="space-y-1.5">
<label
@@ -1055,7 +1045,20 @@ export function AgentInstanceEditDialog({
) : null}
</div>
) : null}
{llmProviderFieldVisible &&
effectiveProvider === "openai-compat" ? (
<OpenAiCompatibleBaseUrlField
disabled={updateMutation.isPending}
inherited={compatibleBaseUrlInherited}
onValueChange={(next) =>
setEnvVars((prev) => ({
...prev,
[OPENAI_COMPAT_BASE_URL]: next,
}))
}
value={compatibleBaseUrl}
/>
) : null}
{llmProviderFieldVisible && topLevelSecretEnvVar ? (
<PersonaProviderApiKeyField
disabled={updateMutation.isPending}
@@ -1073,7 +1076,6 @@ export function AgentInstanceEditDialog({
value={apiKeyValue}
/>
) : null}
{/* Model */}
<div className="space-y-1.5">
<label
@@ -1126,8 +1128,10 @@ export function AgentInstanceEditDialog({
) : null}
</div>
<EffortPickerField agent={agent} config={configSurfaceQuery.data} />
<AgentAiDefaultsNotice
onEditDefaults={() => setAiDefaultsOpen(true)}
triggerRef={aiDefaultsTriggerRef}
@@ -1136,13 +1140,11 @@ export function AgentInstanceEditDialog({
inheritedModel={inheritedModelDefault}
inheritedProvider={inheritedProviderDefault}
/>
<AgentDefaultsDialog
onOpenChange={setAiDefaultsOpen}
open={aiDefaultsOpen}
returnFocusRef={aiDefaultsTriggerRef}
/>
{/* Advanced settings */}
<div className="space-y-3">
<button
@@ -1181,9 +1183,12 @@ export function AgentInstanceEditDialog({
disabled={updateMutation.isPending}
envVars={envVars}
fileSatisfiedEnvKeys={fileSatisfiedEnvKeys}
hiddenEnvKeys={
topLevelSecretEnvVar ? [topLevelSecretEnvVar] : []
}
hiddenEnvKeys={[
...(topLevelSecretEnvVar ? [topLevelSecretEnvVar] : []),
...(effectiveProvider === "openai-compat"
? [OPENAI_COMPAT_BASE_URL]
: []),
]}
focusKey={
initialFocus?.type === "env_key"
? initialFocus.key
@@ -1212,7 +1217,6 @@ export function AgentInstanceEditDialog({
) : null}
</AnimatePresence>
</div>
{/* Error */}
{updateMutation.error instanceof Error ? (
<p className="text-sm text-destructive">

View File

@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import { openAiCompatibleBaseUrlError } from "./OpenAiCompatibleBaseUrlField.tsx";
test("OpenAI-compatible base URL accepts only absolute HTTP(S) URLs", () => {
assert.equal(openAiCompatibleBaseUrlError("http://localhost:11434/v1"), null);
assert.equal(
openAiCompatibleBaseUrlError(" https://models.example/v1/ "),
null,
);
assert.equal(openAiCompatibleBaseUrlError(""), "Base URL is required.");
assert.equal(
openAiCompatibleBaseUrlError("ftp://models.example/v1"),
"Enter a valid HTTP or HTTPS URL.",
);
assert.equal(
openAiCompatibleBaseUrlError("localhost:11434/v1"),
"Enter a valid HTTP or HTTPS URL.",
);
});

View File

@@ -0,0 +1,75 @@
import { Input } from "@/shared/ui/input";
import { cn } from "@/shared/lib/cn";
import { RequiredFieldLabel } from "./agentConfigControls";
import {
PERSONA_FIELD_CONTROL_CLASS,
PERSONA_FIELD_SHELL_CLASS,
} from "./agentConfigOptions";
export const OPENAI_COMPAT_BASE_URL = "OPENAI_COMPAT_BASE_URL";
export function openAiCompatibleBaseUrlError(value: string): string | null {
const trimmed = value.trim();
if (trimmed.length === 0) return "Base URL is required.";
try {
const url = new URL(trimmed);
if ((url.protocol === "http:" || url.protocol === "https:") && url.host) {
return null;
}
} catch {
// Fall through to the actionable validation message.
}
return "Enter a valid HTTP or HTTPS URL.";
}
export function OpenAiCompatibleBaseUrlField({
disabled,
inherited = false,
onValueChange,
value,
}: {
disabled: boolean;
inherited?: boolean;
onValueChange: (next: string) => void;
value: string;
}) {
const error =
inherited && value.trim().length === 0
? null
: openAiCompatibleBaseUrlError(value);
return (
<div className="space-y-1.5">
<RequiredFieldLabel htmlFor="openai-compatible-base-url" isRequired>
Base URL
</RequiredFieldLabel>
<p className="text-xs text-muted-foreground font-mono">
{OPENAI_COMPAT_BASE_URL}
</p>
<div
className={cn(
"flex min-h-11 items-center px-3",
PERSONA_FIELD_SHELL_CLASS,
)}
>
<Input
aria-invalid={error !== null}
autoCapitalize="none"
autoCorrect="off"
className={cn("h-8 px-0 py-0 leading-6", PERSONA_FIELD_CONTROL_CLASS)}
data-testid="openai-compatible-base-url"
disabled={disabled}
id="openai-compatible-base-url"
onBlur={(event) =>
onValueChange(event.target.value.trim().replace(/\/+$/, ""))
}
onChange={(event) => onValueChange(event.target.value)}
placeholder={inherited ? "Inherited" : "http://localhost:11434/v1"}
type="url"
value={value}
/>
</div>
{error ? <p className="text-xs text-destructive">{error}</p> : null}
</div>
);
}

View File

@@ -112,7 +112,7 @@ const PROVIDER_CREDENTIAL_CONFIG: Partial<
apiKeyLabel: "OpenAI Runtime API Key",
},
"openai-compat": {
requiredEnvKeys: ["OPENAI_COMPAT_API_KEY"],
requiredEnvKeys: ["OPENAI_COMPAT_BASE_URL"],
secretEnvVar: "OPENAI_COMPAT_API_KEY",
apiKeyLabel: "OpenAI-compatible Runtime API Key",
},

View File

@@ -58,3 +58,30 @@ test("global defaults accept a provider key set in runtime config", () => {
assert.equal(state.apiKeyInherited, true);
assert.equal(state.credentialsValid, true);
});
test("OpenAI-compatible defaults require the base URL but not an API key", () => {
const missingUrl = getGlobalAgentCredentialState({
bakedEnvKeys: [],
envVars: {},
provider: "openai-compat",
runtimeFileConfig: null,
runtimeId: "buzz-agent",
});
assert.equal(missingUrl.apiKeyRequired, false);
assert.equal(missingUrl.credentialsValid, false);
assert.deepEqual(missingUrl.advancedRequiredEnvKeys, [
"OPENAI_COMPAT_BASE_URL",
]);
const configured = getGlobalAgentCredentialState({
bakedEnvKeys: [],
envVars: { OPENAI_COMPAT_BASE_URL: "http://localhost:11434/v1" },
provider: "openai-compat",
runtimeFileConfig: null,
runtimeId: "buzz-agent",
});
assert.equal(configured.apiKeyRequired, false);
assert.equal(configured.credentialsValid, true);
});

View File

@@ -52,10 +52,10 @@ export function getGlobalAgentCredentialState({
const advancedCredentialMissing = advancedRequiredEnvKeys.some(
(key) => (envVars[key] ?? "").trim().length === 0,
);
const apiKeyRequired =
apiKeyEnvVar !== null && requiredEnvKeys.includes(apiKeyEnvVar);
const apiKeyMissing =
apiKeyEnvVar !== null &&
!apiKeyInherited &&
apiKeyValue.trim().length === 0;
apiKeyRequired && !apiKeyInherited && apiKeyValue.trim().length === 0;
return {
advancedCredentialMissing,
@@ -64,6 +64,7 @@ export function getGlobalAgentCredentialState({
apiKeyEnvVar,
apiKeyFileSatisfied,
apiKeyInherited,
apiKeyRequired,
apiKeyValue,
credentialsValid: !advancedCredentialMissing && !apiKeyMissing,
};

View File

@@ -94,3 +94,18 @@ test("providerApiKeyFieldState_explicitLocalEmptyShadowsRuntimeConfig", () => {
assert.equal(state.isRequired, true);
assert.equal(state.isInherited, false);
});
test("providerApiKeyFieldState_openaiCompatKeyIsOptional", () => {
const state = getProviderApiKeyFieldState({
bakedEnvKeys: [],
effectiveEnvVars: {},
envVars: {},
globalEnvVars: {},
provider: "openai-compat",
requiredEnvKeys: ["OPENAI_COMPAT_BASE_URL"],
});
assert.equal(state.secretEnvVar, "OPENAI_COMPAT_API_KEY");
assert.equal(state.isRequired, false);
assert.deepEqual(state.advancedRequiredEnvKeys, ["OPENAI_COMPAT_BASE_URL"]);
});

View File

@@ -93,7 +93,10 @@ export function getProviderApiKeyFieldState({
advancedRequiredEnvKeys,
inheritedLabel,
isInherited: source !== null,
isRequired: source === null && value.length === 0,
isRequired:
requiredEnvKeys.includes(secretEnvVar) &&
source === null &&
value.length === 0,
secretEnvVar,
value,
};