Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(models): infer custom endpoint auth from optional API keys

vastsa96fafc8545cc
diff --git a/apps/desktop/src/components/settings/PluginProviderKeySetupForm.tsx b/apps/desktop/src/components/settings/PluginProviderKeySetupForm.tsx
index b5866cc8a..38eb47443 100644
--- a/apps/desktop/src/components/settings/PluginProviderKeySetupForm.tsx
+++ b/apps/desktop/src/components/settings/PluginProviderKeySetupForm.tsx
@@ -106,8 +106,6 @@ export function PluginProviderKeySetupForm({
nameRef={nameRef}
apiKey={apiKey}
onApiKeyChange={setApiKey}
- noApiKeyRequired={false}
- onNoApiKeyRequiredChange={() => {}}
name={provider.name}
onNameChange={() => {}}
baseUrl={provider.baseUrl ?? ""}
diff --git a/apps/desktop/src/components/settings/ProviderConnectionFields.tsx b/apps/desktop/src/components/settings/ProviderConnectionFields.tsx
index c5bc210de..cdb2e67ce 100644
--- a/apps/desktop/src/components/settings/ProviderConnectionFields.tsx
+++ b/apps/desktop/src/components/settings/ProviderConnectionFields.tsx
@@ -10,7 +10,7 @@
import type { RefObject } from "react";
import { useTranslation } from "react-i18next";
import type { CatalogApiStyle } from "@pi-desktop/shared";
-import { Field, Input, SettingsToggle } from "../ui";
+import { Button, Field, Input } from "../ui";
import { SettingsMenuSelect } from "./SettingsMenuSelect";
import { ServiceMonogram } from "./ServiceMonogram";
import { endpointLabel } from "./service-catalog";
@@ -33,8 +33,8 @@ export type ProviderConnectionFieldsProps = {
nameRef: RefObject<HTMLInputElement | null>;
apiKey: string;
onApiKeyChange: (value: string) => void;
- noApiKeyRequired: boolean;
- onNoApiKeyRequiredChange: (required: boolean) => void;
+ hasSavedApiKey?: boolean;
+ onClearApiKey?: () => void;
name: string;
onNameChange: (value: string) => void;
baseUrl: string;
@@ -63,8 +63,8 @@ export function ProviderConnectionFields({
nameRef,
apiKey,
onApiKeyChange,
- noApiKeyRequired,
- onNoApiKeyRequiredChange,
+ hasSavedApiKey = false,
+ onClearApiKey,
name,
onNameChange,
baseUrl,
@@ -78,7 +78,9 @@ export function ProviderConnectionFields({
requiresApiStyleChoice,
}: ProviderConnectionFieldsProps) {
const { t } = useTranslation();
- const keyHint = editing ? t("settings.apiKeyKeepHint") : undefined;
+ const keyHint = custom && !hasSavedApiKey
+ ? t("settings.apiKeyOptionalHint")
+ : editing ? t("settings.apiKeyKeepHint") : undefined;
return (
<div className={named ? "provider-setup-fields is-named" : "provider-setup-fields is-custom"}>
@@ -178,26 +180,22 @@ export function ProviderConnectionFields({
placeholder="sk-…"
className="font-mono text-sm-plus"
autoComplete="off"
- disabled={saving || noApiKeyRequired}
+ disabled={saving}
onChange={(event) => onApiKeyChange(event.target.value)}
/>
</Field>
- <div className="provider-setup-no-api-key-option">
- <div className="flex items-center justify-between gap-3">
- <span className="text-sm text-text-secondary">
- {t("settings.noApiKeyRequired")}
- </span>
- <SettingsToggle
- checked={noApiKeyRequired}
- label={t("settings.noApiKeyRequired")}
- disabled={saving}
- onChange={() => onNoApiKeyRequiredChange(!noApiKeyRequired)}
- />
- </div>
- <p className="text-xs text-text-muted">
- {t("settings.noApiKeyHint")}
- </p>
- </div>
+ {hasSavedApiKey && onClearApiKey ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="self-start"
+ disabled={saving}
+ onClick={onClearApiKey}
+ >
+ {t("settings.clearApiKey")}
+ </Button>
+ ) : null}
</div>
<Field
label={t("settings.apiStyle")}
diff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
index 5b0b513a3..8c2245ec7 100644
--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
@@ -130,7 +130,7 @@ export function ProviderSetupDialog({
const [name, setName] = useState(() => initialDraft?.name ?? initialName(provider));
const [baseUrl, setBaseUrl] = useState(() => initialDraft?.baseUrl ?? initialBaseUrl(provider));
const [apiKey, setApiKey] = useState("");
- const [noApiKeyRequired, setNoApiKeyRequired] = useState(() => provider?.authKind === "none");
+ const [clearSavedApiKey, setClearSavedApiKey] = useState(false);
const [apiStyle, setApiStyle] = useState<CatalogApiStyle>(() =>
initialDraft?.apiStyle ?? normalizeApiStyle(provider?.apiStyle),
);
@@ -173,6 +173,8 @@ export function ProviderSetupDialog({
const namedPreset = NAMED_ENDPOINT_PRESETS.find((preset) => preset.id === service);
const named = Boolean(namedPreset);
const custom = service === CUSTOM_SERVICE;
+ const hasSavedApiKey = Boolean(provider?.hasSecret && provider.authKind !== "none" && !clearSavedApiKey);
+ const noApiKeyRequired = custom && !apiKey.trim() && !hasSavedApiKey;
/** Jev never becomes a provider row, so it is a view of its own. */
const jevService = service === JEV_SERVICE;
const resolvedName = namedPreset ? name.trim() || namedPreset.name : name;
@@ -216,11 +218,11 @@ export function ProviderSetupDialog({
discoveryActive,
{
baseUrl: requestBaseUrl,
- apiKey,
+ apiKey: custom ? apiKey.trim() : apiKey,
apiStyle: resolvedApiStyle,
headers,
},
- provider,
+ custom && clearSavedApiKey ? null : provider,
);
// The probe's own answer is reported once as a toast instead of a status row
// under the key, which held a line of the dialog open for as long as it stood.
@@ -353,6 +355,7 @@ export function ProviderSetupDialog({
const save = async () => {
const providerName = resolvedName.trim();
const providerBaseUrl = normalizeBaseUrlInput(resolvedBaseUrl, resolvedApiStyle);
+ const secretValue = custom ? apiKey.trim() : apiKey;
if (
requiresApiStyleChoice ||
!providerName ||
@@ -392,7 +395,7 @@ export function ProviderSetupDialog({
...(custom && noApiKeyRequired !== (provider.authKind === "none")
? { authKind: noApiKeyRequired ? "none" : "api_key_and_base_url" }
: {}),
- ...(custom && noApiKeyRequired ? {} : apiKey ? { secretValue: apiKey } : {}),
+ ...(secretValue ? { secretValue } : {}),
});
await onSaved(result.provider ?? provider, persisted, imageModelIdsToSave);
} else {
@@ -405,7 +408,7 @@ export function ProviderSetupDialog({
authKind: custom && noApiKeyRequired ? "none" : "api_key_and_base_url",
defaultModelId: persisted[0]?.id,
models: persisted,
- ...(custom && noApiKeyRequired ? {} : { secretValue: apiKey || undefined }),
+ ...(noApiKeyRequired ? {} : { secretValue: secretValue || undefined }),
apiStyle: resolvedApiStyle,
headers,
});
@@ -511,10 +514,11 @@ export function ProviderSetupDialog({
nameRef={nameRef}
apiKey={apiKey}
onApiKeyChange={setApiKey}
- noApiKeyRequired={noApiKeyRequired}
- onNoApiKeyRequiredChange={(required) => {
- setNoApiKeyRequired(required);
- if (required) setApiKey("");
+ hasSavedApiKey={hasSavedApiKey}
+ onClearApiKey={() => {
+ setClearSavedApiKey(true);
+ setApiKey("");
+ apiKeyRef.current?.focus();
}}
name={name}
onNameChange={setName}
diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.css
index 2a3dc8ec7..2122098b8 100644
--- a/apps/desktop/src/styles/model-config.css
+++ b/apps/desktop/src/styles/model-config.css
@@ -271,12 +271,6 @@
min-width: 0;
}
-.provider-setup-no-api-key-option {
- display: grid;
- gap: 4px;
- margin-top: 2px;
-}
-
.provider-service-anchor {
width: 100%;
min-width: 0;
diff --git a/apps/desktop/test/custom-provider-no-api-key-user-path.test.mjs b/apps/desktop/test/custom-provider-no-api-key-user-path.test.mjs
index b784b2e80..873914d60 100644
--- a/apps/desktop/test/custom-provider-no-api-key-user-path.test.mjs
+++ b/apps/desktop/test/custom-provider-no-api-key-user-path.test.mjs
@@ -63,7 +63,7 @@ window.piDesktop = {
updatedProvider = {
...createdProvider,
...input,
- hasSecret: Boolean(input.secretValue) || createdProvider.hasSecret,
+ hasSecret: input.authKind === "none" ? false : Boolean(input.secretValue) || createdProvider.hasSecret,
};
return { ok: true, data: { provider: updatedProvider } };
}
@@ -101,6 +101,25 @@ const rootNode = createRoot(document.getElementById("root"));
function mount(element) { flushSync(() => rootNode.render(element)); }
window.customProviderNoApiKeyProbe = async () => {
+ const check = (condition, message) => { if (!condition) throw new Error(message); };
+ const button = (label) => [...document.querySelectorAll("button")]
+ .find((item) => item.textContent.trim() === label);
+ const keyField = () => document.querySelector('input[type="password"]');
+ const edit = (provider, key) => {
+ updateInput = null;
+ updatedProvider = null;
+ mount(React.createElement(ProviderSetupDialog, {
+ key,
+ provider,
+ onClose: () => mount(null),
+ onSaved: () => {},
+ }));
+ };
+ const saveEdit = async () => {
+ flushSync(() => button("Save provider").click());
+ await waitFor(() => updateInput && updatedProvider, "the provider edit was not saved");
+ return structuredClone(updateInput);
+ };
mount(React.createElement(ProviderSetupDialog, {
key: "new-provider",
provider: null,
@@ -112,89 +131,123 @@ window.customProviderNoApiKeyProbe = async () => {
"the custom endpoint service was not offered",
);
flushSync(() => customTile.click());
-
- const noApiKeyToggle = await waitFor(
- () => document.querySelector('[role="switch"][aria-label="No API key required"]'),
- "the custom endpoint form did not offer its no-key option",
- );
- const noApiKeyDefaultsOff = noApiKeyToggle.getAttribute("aria-checked") === "false";
+ check(!document.querySelector('[role="switch"][aria-label="No API key required"]'),
+ "the obsolete no-key switch is still present");
+ check(keyField() && !keyField().disabled, "the optional API-key input is not enabled");
const nameField = [...document.querySelectorAll("label")]
- .find((label) => label.textContent.includes("Name"))
- ?.querySelector("input");
+ .find((label) => label.textContent.includes("Name"))?.querySelector("input");
const urlField = document.querySelector('input[type="url"]');
- if (!nameField || !urlField) throw new Error("the custom endpoint identity fields were missing");
+ check(nameField && urlField, "the custom endpoint identity fields were missing");
setValue(nameField, "No Auth Gateway");
setValue(urlField, "https://no-auth.example.org/v1");
-
const discoveryCall = await waitFor(
() => calls.find((call) => call.channel === "pi-desktop/providers/listModels"
&& call.input.baseUrl === "https://no-auth.example.org/v1"),
"the custom endpoint was not probed without an API key",
);
- const keyField = document.querySelector('input[type="password"]');
- setValue(keyField, "temporary-api-key");
- flushSync(() => noApiKeyToggle.click());
- const keyFieldDisabled = keyField?.disabled === true;
- const keyFieldCleared = keyField?.value === "";
-
const modelField = document.querySelector('input[placeholder^="Enter a model ID"]');
- if (!modelField) throw new Error("the custom model input was missing");
+ check(modelField, "the custom model input was missing");
setValue(modelField, "no-auth-chat");
- const addModelButton = [...document.querySelectorAll("button")]
- .find((button) => button.textContent.trim() === "Add custom model");
- if (!addModelButton) throw new Error("the custom model add action was missing");
- flushSync(() => addModelButton.click());
+ flushSync(() => button("Add custom model").click());
await waitFor(
() => document.querySelector(".provider-chosen")?.innerText.includes("no-auth-chat"),
"the model was not added to the custom provider",
);
-
- const saveButton = [...document.querySelectorAll("button")]
- .find((button) => button.textContent.trim() === "Save provider");
- if (!saveButton) throw new Error("the custom provider save action was missing");
- flushSync(() => saveButton.click());
+ // A whitespace-only key has the same meaning as an empty key.
+ flushSync(() => setValue(keyField(), " "));
+ flushSync(() => button("Save provider").click());
await waitFor(() => savedCallback && createdProvider, "the custom provider was not saved");
- const savedAsNoAuth = createdProvider.authKind === "none"
- && !Object.hasOwn(createdProvider, "secretValue")
- && createdProvider.models?.[0]?.id === "no-auth-chat";
+ const noAuthProvider = structuredClone(createdProvider);
+ check(noAuthProvider.authKind === "none" && !Object.hasOwn(noAuthProvider, "secretValue"),
+ "an empty API key did not automatically save as no-auth");
+
+ edit(noAuthProvider, "edit-no-auth-unchanged");
+ const unchangedNoAuth = await saveEdit();
+ check(!Object.hasOwn(unchangedNoAuth, "authKind") && !Object.hasOwn(unchangedNoAuth, "secretValue"),
+ "reopening and saving a no-auth provider changed its authentication");
+
+ edit(noAuthProvider, "edit-no-auth-add-key");
+ check(!keyField().disabled, "a no-auth provider cannot accept an API key");
+ flushSync(() => setValue(keyField(), " saved-api-key "));
+ const keyedUpdate = await saveEdit();
+ check(keyedUpdate.authKind === "api_key_and_base_url" && keyedUpdate.secretValue === "saved-api-key",
+ "typing a key did not switch the no-auth provider to API-key authentication");
+ createdProvider = structuredClone(updatedProvider);
+ const keyedProvider = structuredClone(createdProvider);
+
+ edit(keyedProvider, "edit-keyed-keep-key");
+ const keepKeyUpdate = await saveEdit();
+ check(!Object.hasOwn(keepKeyUpdate, "authKind") && !Object.hasOwn(keepKeyUpdate, "secretValue"),
+ "an untouched empty input overwrote the saved key");
+
+ edit(keyedProvider, "edit-keyed-clear-and-cancel");
+ check(button("Clear saved API key"), "the saved-key removal action was missing");
+ flushSync(() => button("Clear saved API key").click());
+ check(!updateInput, "clearing a key persisted before Save");
+ check(keyField().value === "" && !keyField().disabled, "clearing a saved key disabled the input");
+ const afterClear = calls.length;
+ const clearProbe = await waitFor(
+ () => calls.slice(afterClear).find((call) => call.channel === "pi-desktop/providers/listModels"
+ && call.input.baseUrl === keyedProvider.baseUrl && call.input.source !== "cache"),
+ "clearing the saved key did not refresh model discovery",
+ );
+ check(!Object.hasOwn(clearProbe.input, "providerId") && !Object.hasOwn(clearProbe.input, "apiKey"),
+ "model discovery reused a saved key after it was cleared");
+ mount(null);
+ check(!updateInput, "closing the form after Clear changed the saved key");
+
+ edit(keyedProvider, "edit-keyed-clear-and-replace");
+ flushSync(() => button("Clear saved API key").click());
+ flushSync(() => setValue(keyField(), "replacement-api-key"));
+ const replacementUpdate = await saveEdit();
+ check(replacementUpdate.authKind !== "none" && replacementUpdate.secretValue === "replacement-api-key",
+ "a replacement key was discarded after Clear");
+
+ edit(keyedProvider, "edit-keyed-clear-and-save");
+ flushSync(() => button("Clear saved API key").click());
+ const clearedUpdate = await saveEdit();
+ check(clearedUpdate.authKind === "none" && !Object.hasOwn(clearedUpdate, "secretValue"),
+ "clearing and saving did not switch to no-auth");
+ check(updatedProvider.hasSecret === false, "the cleared provider is still marked as credentialed");
+
+ const missingKeyProvider = { ...keyedProvider, hasSecret: false };
+ edit(missingKeyProvider, "edit-keyed-missing-key");
+ const missingKeyUpdate = await saveEdit();
+ check(missingKeyUpdate.authKind === "none" && !Object.hasOwn(missingKeyUpdate, "secretValue"),
+ "an existing custom provider without a stored key did not become no-auth");
- let updateSavedCallback = false;
mount(React.createElement(ProviderSetupDialog, {
- key: "edit-provider",
- provider: createdProvider,
- onClose: () => mount(null),
- onSaved: (provider) => {
- updatedProvider = provider;
- updateSavedCallback = true;
+ key: "new-keyed-provider",
+ provider: null,
+ initialDraft: {
+ name: "Key Gateway",
+ baseUrl: keyedProvider.baseUrl,
+ apiStyle: "chat_completions",
+ models: keyedProvider.models,
},
+ onClose: () => mount(null),
+ onSaved: () => {},
}));
- const editNoApiKeyToggle = await waitFor(
- () => document.querySelector('[role="switch"][aria-label="No API key required"]'),
- "the saved no-key setting did not reopen",
- );
- const editOpenedAsNoAuth = editNoApiKeyToggle.getAttribute("aria-checked") === "true";
- flushSync(() => editNoApiKeyToggle.click());
- const editKeyField = document.querySelector('input[type="password"]');
- const editKeyEnabled = editKeyField?.disabled === false;
- setValue(editKeyField, "saved-api-key");
- const updateButton = [...document.querySelectorAll("button")]
- .find((button) => button.textContent.trim() === "Save provider");
- if (!updateButton) throw new Error("the edited custom provider save action was missing");
- flushSync(() => updateButton.click());
- await waitFor(() => updateSavedCallback && updateInput, "the custom provider auth update was not saved");
+ flushSync(() => setValue(keyField(), "new-api-key"));
+ createdProvider = null;
+ flushSync(() => button("Save provider").click());
+ await waitFor(() => createdProvider, "the new keyed provider was not saved");
+ check(createdProvider.authKind === "api_key_and_base_url" && createdProvider.secretValue === "new-api-key",
+ "a new custom provider with an API key did not retain API-key authentication");
return {
discoveryOmittedApiKey: !Object.hasOwn(discoveryCall.input, "apiKey"),
- noApiKeyDefaultsOff,
- keyFieldDisabled: keyFieldDisabled,
- keyFieldCleared: keyFieldCleared,
- savedAuthKind: savedAsNoAuth ? "none" : createdProvider.authKind,
- secretValueOmitted: savedAsNoAuth,
- selectedModel: createdProvider.models?.[0]?.id,
- editOpenedAsNoAuth,
- editKeyEnabled,
- updateAuthKind: updateInput.authKind,
- updateStoredKey: updateInput.secretValue === "saved-api-key",
+ savedAuthKind: noAuthProvider.authKind,
+ selectedModel: noAuthProvider.models?.[0]?.id,
+ noAuthReopenPreserved: true,
+ typedKeyEnablesAuth: true,
+ blankEditPreservesKey: true,
+ clearDiscoveryOmitsStoredKey: true,
+ cancelledClearPreservesKey: true,
+ clearThenReplaceSavesKey: true,
+ clearThenSaveRemovesKey: true,
+ missingKeyBecomesNoAuth: true,
+ newKeyedProviderPreserved: true,
};
};
`;
@@ -281,16 +334,17 @@ app.whenReady().then(async () => {
assert(line, output.slice(-6000));
assert.deepEqual(JSON.parse(line.slice("CUSTOM_PROVIDER_NO_API_KEY_PROBE ".length)), {
discoveryOmittedApiKey: true,
- noApiKeyDefaultsOff: true,
- keyFieldDisabled: true,
- keyFieldCleared: true,
savedAuthKind: "none",
- secretValueOmitted: true,
selectedModel: "no-auth-chat",
- editOpenedAsNoAuth: true,
- editKeyEnabled: true,
- updateAuthKind: "api_key_and_base_url",
- updateStoredKey: true,
+ noAuthReopenPreserved: true,
+ typedKeyEnablesAuth: true,
+ blankEditPreservesKey: true,
+ clearDiscoveryOmitsStoredKey: true,
+ cancelledClearPreservesKey: true,
+ clearThenReplaceSavesKey: true,
+ clearThenSaveRemovesKey: true,
+ missingKeyBecomesNoAuth: true,
+ newKeyedProviderPreserved: true,
});
} finally {
await rm(temp, { recursive: true, force: true });
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 68bb7fb1c..7cbd481c0 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -393,11 +393,14 @@ Presets only prefill form defaults; they are not a closed world.
| bedrock | bedrock | aws_sdk_default | no |
| ollama | openai_compatible | none | yes |
| lmstudio | openai_compatible | none | yes |
-| custom | openai_compatible | api_key_and_base_url by default; `none` when the endpoint needs no authentication | yes |
-
-The custom endpoint form keeps API-key authentication as its default and lets
-the user explicitly select `authKind: "none"` for endpoints that accept
-unauthenticated requests. Named cloud presets retain their declared auth kind.
+| custom | openai_compatible | `api_key_and_base_url` with a supplied/saved key; `none` without a key | yes |
+
+The custom endpoint form derives authentication from the effective API key,
+without a mode switch. An empty or whitespace-only input on a row without a
+saved key uses `authKind: "none"`; a supplied key uses API-key authentication.
+Editing with a blank input keeps the stored key. **Clear saved API key** stages
+its removal until Save; typing a replacement key instead keeps API-key auth.
+Named cloud presets retain their declared auth kind.
### Fixed API-style presets
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index 1678ab13d..3aebd75ef 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -24,12 +24,15 @@ entitled to it.
`ProviderSetupDialog` is a single form, not a wizard:
-- **Name**, **Base URL** and **API Key** are all on screen at once. An empty key
- when editing means “keep the stored one”; `secretValue` is only sent when the
- user typed something. Custom endpoints also offer an explicit **No API key
- required** switch, defaulting off for new rows. When enabled, the key field is
- disabled and cleared, and the row saves with `authKind: "none"` and no
- secret. Named cloud services keep their existing authentication defaults.
+- **Name**, **Base URL** and **API Key** are all on screen at once. Custom
+ endpoint keys are optional, with no authentication-mode switch. An empty or
+ whitespace-only key on a row without a stored key saves `authKind: "none"`
+ without `secretValue`; a supplied key uses API-key authentication. Editing
+ with an empty key preserves the stored key. **Clear saved API key** stages
+ removal, keeps the input enabled, and stops discovery from reusing that key;
+ Save applies the removal and no-auth mode unless a replacement key is typed.
+ Closing without saving changes no stored credential. Named cloud services
+ keep their existing authentication defaults.
- The models section lists what the service returned. `useProviderModels`
debounces edits by 600 ms, guards against out-of-order replies with a
monotonic request sequence, and needs no API key so local and no-auth
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d7cbfb81c..93ad86b71 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1255,7 +1255,7 @@ identify the platform validation still needed.
#### E2E-005: Add a provider and save API key
- **Preconditions**: App running; no provider configured; the models.dev snapshot ships with the build.
-- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the searchable service chooser opens. Filter and select a built-in API-key service or **Custom endpoint**; the selection must open its matching form, never the plugin-only “selected service unavailable” state. Confirm the form has no stepper or Next/Back buttons. For **Custom endpoint**, Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. The custom form's **No API key required** switch starts off; enabling it clears and disables the key field. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. Confirm the models section fills with the models THAT SERVICE returned without requiring a key for discovery; confirm a model the deployment does not host is absent. Also exercise the no-auth path with a custom endpoint: leave the key empty, enable **No API key required**, select a discovered model, and save. 4) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 5) Confirm each row shows the models.dev-derived context/output for models the catalog knows, that its compact text tracks the published value instead of a coarser rounded one (a 1,050,000 window reads `1.05M`, never `1.1M`), and that a model with no catalog match still lists with generic defaults. 6) Select two models with the checkboxes. 7) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Set max output to 8,192 while its context window still follows the catalog. On a model whose published image input is enabled, toggle image input off and then back on before saving, so the explicit choice equals the current catalog value. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 8) Open the form-level Advanced and confirm the API format is present but pre-derived. 9) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 10) Save.
+- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the searchable service chooser opens. Filter and select a built-in API-key service or **Custom endpoint**; the selection must open its matching form, never the plugin-only “selected service unavailable” state. Confirm the form has no stepper or Next/Back buttons. For **Custom endpoint**, Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. The custom form has no authentication-mode switch; the API key is optional and its input stays enabled. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. Confirm the models section fills with the models THAT SERVICE returned without requiring a key for discovery; confirm a model the deployment does not host is absent. Also exercise the no-auth path with a custom endpoint: leave the key empty, select a discovered model, and save. 4) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 5) Confirm each row shows the models.dev-derived context/output for models the catalog knows, that its compact text tracks the published value instead of a coarser rounded one (a 1,050,000 window reads `1.05M`, never `1.1M`), and that a model with no catalog match still lists with generic defaults. 6) Select two models with the checkboxes. 7) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Set max output to 8,192 while its context window still follows the catalog. On a model whose published image input is enabled, toggle image input off and then back on before saving, so the explicit choice equals the current catalog value. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 8) Open the form-level Advanced and confirm the API format is present but pre-derived. 9) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 10) Save.
- **Expected**: The service is asked first and models.dev only enriches the answer and seeds known-model defaults. The no-auth custom path saves `authKind: "none"`, omits `secretValue`, and makes the configured provider available anywhere an enabled no-auth provider is selectable; named cloud preset behavior stays unchanged. Newly fetched or checked model rows stay collapsed until the user opens Advanced, so every selected model ID remains visible in the right pane after a multi-select. The settings picker always offers the seven canonical thinking levels, and the Composer later renders the explicit levels saved in the same model binding; an empty or `off`-only binding resolves to `off`. Discovery is debounced ~600 ms, does not mark loading until that window elapses, and a slow reply from an earlier keystroke never replaces a newer list; named add-path discovery waits for an API key, while an unsaved custom provider is probed with the typed base URL (and key, if any) before it exists. Preset ladders cover common context/output limits while preserving hand-edited values. The explicitly selected 8,192 output remains pinned independently of the catalog-sourced context window, and the image-input choice remains explicitly enabled after it is toggled back to the published value; neither is reinterpreted as "follow catalog" on save/reopen. Later catalog corrections change only values whose own source is `catalog`. Limit text renders through one shared compact formatter, so neighbouring published windows stay distinguishable (`1M` / `1.05M` / `1.1M`) and a compact limit never reads above its published value. Custom endpoint keeps API format beside the key and omits Base URL helper copy; named endpoints do not show format. Point the same custom form at an unreachable or unauthorized URL and confirm one classified sentence reaches the app toast while the left pane keeps its single “no list” label (not a raw JSON/HTML dump and not a second “no models” empty state); with cached rows from a later edit the same reason is toasted while the rows stay. Point a second provider at a base URL with no `/models` route and confirm the list falls back to the catalog, is labelled as coming from models.dev rather than the service, and still saves. The provider appears as a row with its host, model count and secret badge; the key is stored securely (not in plaintext config); `models` contains both bindings and `models[0]` remains the provider default.
- **Specs linked**: `03-runtime/11-provider-model-system.md`, `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`, `03-runtime/14-secrets-storage.md`, `04-ux/06-settings-ia.md`
- **Acceptance**: B (multi-model provider configuration, save key)
@@ -1265,9 +1265,9 @@ identify the platform validation still needed.
#### E2E-PROVIDER-custom-endpoint-no-api-key: Configure a custom service without credentials
- **Preconditions**: Isolated settings profile and a local OpenAI-compatible fixture that lists a model without credentials; no live or paid provider.
-- **Steps**: 1) Open Settings → Model configuration → Add provider → Custom endpoint. 2) Enter a name and the fixture URL; check **No API key required**. 3) Confirm model discovery succeeds without a key, select the returned model, and save. 4) Confirm the provider and model are offered by chat/default-model and subagent selectors. 5) Edit an API-key provider, select **No API key required**, save, and inspect the provider's stored auth kind and credential state. 6) Send a request through the no-auth provider fixture.
-- **Expected**: The custom form remains in API-key mode by default. The explicit no-key selection saves `authKind: "none"` without `secretValue`; editing to this mode removes the provider's existing API key. The enabled provider with `hasSecret: false` remains selectable for chat, defaults, subagents, and image generation where its model supports that operation. Runtime requests contain no API-key or Authorization credentials.
-- **Automation**: `pnpm test:e2e:provider-api-style` renders the production setup form in English and Simplified Chinese with a stubbed model-discovery/API boundary and verifies create/update payloads and chat/default/subagent selector eligibility. `pnpm --filter @pi-desktop/agent-runtime test -- provider-binding.test.ts` verifies request headers; `apps/desktop/test/image-generation-default.test.mjs` covers no-auth image-model availability; `cargo test -p host-core --locked switching_provider_to_no_auth_clears_its_api_key` verifies Host persistence and secret removal.
+- **Steps**: 1) Open Settings → Model configuration → Add provider → Custom endpoint. 2) Enter a name and the fixture URL; leave the optional API key empty, without selecting an authentication mode. 3) Confirm model discovery succeeds without a key, select the returned model, and save. 4) Reopen and save without changes, then type a key and save; confirm API-key authentication is restored. 5) Edit an API-key provider and save with a blank input; confirm its key is retained. Reopen, choose **Clear saved API key**, and confirm subsequent discovery does not reuse the stored key. Close without saving and confirm no credential changed. Repeat Clear followed by Save, and Clear followed by a replacement key and Save. 6) Confirm the no-auth provider and model are offered by chat/default-model and subagent selectors. 7) Send a request through the no-auth provider fixture.
+- **Expected**: The custom form has no no-key switch and keeps the key input enabled. An empty or whitespace-only key with no saved credential automatically saves `authKind: "none"` without `secretValue`; a supplied key uses API-key authentication. A blank edit retains an existing key. Clear is staged until Save and a replacement key takes precedence over removal. The enabled no-auth provider with `hasSecret: false` remains selectable for chat, defaults, subagents, and image generation where its model supports that operation. Named cloud presets remain unchanged. Runtime requests contain no API-key or Authorization credentials.
+- **Automation**: `node --test apps/desktop/test/custom-provider-no-api-key-user-path.test.mjs` covers empty/whitespace keys, keyed creation, save/reopen, preservation, staged removal/cancellation, discovery without the old secret, and replacement. `pnpm test:e2e:provider-api-style` renders the production setup form in English and Simplified Chinese with a stubbed model-discovery/API boundary and verifies create/update payloads and chat/default/subagent selector eligibility. `pnpm --filter @pi-desktop/agent-runtime exec vitest run src/provider-binding.test.ts` verifies request headers; `apps/desktop/test/image-generation-default.test.mjs` covers no-auth image-model availability; `cargo test -p host-core --locked switching_provider_to_no_auth_clears_its_api_key` verifies Host persistence and secret removal.
- **Specs linked**: `03-runtime/11-provider-model-system.md`, `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`, `04-ux/06-settings-ia.md`.
- **Acceptance**: B (model configuration), F (provider persistence), Security.
- **Milestone**: M2.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index e85aa2dc5..9eb27acdf 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1556,8 +1556,8 @@ sklm: {
"copyProviderHint": "Erstellt einen unabhängigen Dienst. API-Schlüssel, Kontoanmeldungen und benutzerdefinierte Header werden nicht kopiert. Das Standardmodell bleibt unverändert.",
"editProviderTitle": "AI-Anbieter bearbeiten",
"apiKeyKeepHint": "Lassen Sie das Feld leer, um den gespeicherten Schlüssel beizubehalten.",
- "noApiKeyRequired": "Kein API-Schlüssel erforderlich",
- "noApiKeyHint": "Aktivieren Sie diese Option nur, wenn der Endpunkt Anfragen ohne Authentifizierung akzeptiert.",
+ "apiKeyOptionalHint": "Optional. Leer lassen, um Anfragen ohne API-Schlüssel zu senden.",
+ "clearApiKey": "Gespeicherten API-Schlüssel löschen",
"apiStyle": "API-Format",
"apiStyleChatCompletions": "OpenAI-Chat-Abschlüsse",
"apiStyleOpenCodeGo": "OpenCode Go",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 7c4dac53b..b27d15093 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1573,8 +1573,8 @@ sklm: {
"copyProviderHint": "Creates an independent service. API keys, account logins and custom headers are not copied. Your default model stays unchanged.",
editProviderTitle: "Edit AI provider",
apiKeyKeepHint: "Leave blank to keep the saved key.",
- noApiKeyRequired: "No API key required",
- noApiKeyHint: "Enable this only when the endpoint accepts requests without authentication.",
+ apiKeyOptionalHint: "Optional. Leave blank to send requests without an API key.",
+ clearApiKey: "Clear saved API key",
apiStyle: "API format",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 93504ab9f..afd7088c5 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1556,8 +1556,8 @@ sklm: {
"copyProviderHint": "Crea un servicio independiente. No se copian las claves API, los inicios de sesión ni las cabeceras personalizadas. El modelo predeterminado no cambia.",
"editProviderTitle": "Editar proveedor de IA",
"apiKeyKeepHint": "Déjelo en blanco para conservar la clave guardada.",
- "noApiKeyRequired": "No se requiere API key",
- "noApiKeyHint": "Actívalo solo si el endpoint acepta solicitudes sin autenticación.",
+ "apiKeyOptionalHint": "Opcional. Déjelo en blanco para enviar solicitudes sin clave de API.",
+ "clearApiKey": "Borrar la clave de API guardada",
"apiStyle": "Formato API",
"apiStyleChatCompletions": "Finalizaciones de OpenAI Chat",
"apiStyleOpenCodeGo": "OpenCode Go",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 1fd1a173c..29029a20d 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1556,8 +1556,8 @@ sklm: {
"copyProviderHint": "Crée un service indépendant. Les clés API, connexions aux comptes et en-têtes personnalisés ne sont pas copiés. Le modèle par défaut reste inchangé.",
"editProviderTitle": "Modifier le fournisseur d'IA",
"apiKeyKeepHint": "Laissez vide pour conserver la clé enregistrée.",
- "noApiKeyRequired": "Aucune clé API requise",
- "noApiKeyHint": "Activez cette option uniquement si le point de terminaison accepte les requêtes sans authentification.",
+ "apiKeyOptionalHint": "Facultatif. Laissez vide pour envoyer des requêtes sans clé API.",
+ "clearApiKey": "Supprimer la clé API enregistrée",
"apiStyle": "Format API",
"apiStyleChatCompletions": "Achèvements de discussion OpenAI",
"apiStyleOpenCodeGo": "OpenCode Go",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 941d06a72..7c2f234c7 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1569,8 +1569,8 @@ sklm: {
"copyProviderHint": "독립적인 서비스를 만듭니다. API 키, 계정 로그인 및 사용자 지정 헤더는 복사하지 않습니다. 기본 모델은 변경되지 않습니다.",
editProviderTitle: "AI 프로바이더 편집",
apiKeyKeepHint: "저장된 키를 유지하려면 비워 두세요.",
- noApiKeyRequired: "API 키 필요 없음",
- noApiKeyHint: "인증 없이 요청을 받는 엔드포인트에서만 사용하세요.",
+ apiKeyOptionalHint: "선택 사항입니다. 비워 두면 API 키 없이 요청합니다.",
+ clearApiKey: "저장된 API 키 삭제",
apiStyle: "API 형식",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index e08eb747b..5aab4d996 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1526,8 +1526,8 @@ export const ptBR = {
copyProviderHint: "Cria um serviço independente. Chaves de API, logins de contas e cabeçalhos personalizados não são copiados. O modelo padrão permanece inalterado.",
editProviderTitle: "Editar provedor de IA",
apiKeyKeepHint: "Deixe em branco para manter a chave salva.",
- noApiKeyRequired: "Não requer chave de API",
- noApiKeyHint: "Ative somente se o endpoint aceitar solicitações sem autenticação.",
+ apiKeyOptionalHint: "Opcional. Deixe em branco para enviar solicitações sem chave de API.",
+ clearApiKey: "Limpar chave de API salva",
apiStyle: "Formato API",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 974628e3a..50667358f 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1563,8 +1563,8 @@ sklm: {
"copyProviderHint": "Bağımsız bir hizmet oluşturur. API anahtarları, hesap girişleri ve özel başlıklar kopyalanmaz. Varsayılan model değişmez.",
editProviderTitle: "AI servisini düzenle",
apiKeyKeepHint: "Kayıtlı anahtarı korumak için boş bırakın.",
- noApiKeyRequired: "API anahtarı gerekmiyor",
- noApiKeyHint: "Yalnızca uç nokta kimlik doğrulaması olmadan istek kabul ediyorsa etkinleştirin.",
+ apiKeyOptionalHint: "İsteğe bağlı. API anahtarı olmadan istek göndermek için boş bırakın.",
+ clearApiKey: "Kayıtlı API anahtarını sil",
apiStyle: "API biçimi",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 051fa1d4b..705804666 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1551,8 +1551,8 @@ sklm: {
"copyProviderHint": "创建独立的服务配置,不复制 API 密钥、账号登录信息或自定义请求头。当前默认模型保持不变。",
editProviderTitle: "编辑 AI 服务",
apiKeyKeepHint: "留空则保留已保存的密钥。",
- noApiKeyRequired: "无需 API Key",
- noApiKeyHint: "仅当该接口无需身份验证时启用。",
+ apiKeyOptionalHint: "可选,留空时不发送 API Key。",
+ clearApiKey: "清除已保存的 API Key",
apiStyle: "接口格式",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 0fb614546..f10c09338 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1551,8 +1551,8 @@ sklm: {
"copyProviderHint": "建立獨立的服務設定,不複製 API 金鑰、帳號登入資訊或自訂請求標頭。目前的預設模型保持不變。",
editProviderTitle: "編輯 AI 服務",
apiKeyKeepHint: "留空則保留已儲存的金鑰。",
- noApiKeyRequired: "不需要 API 金鑰",
- noApiKeyHint: "僅在此介面無需驗證時啟用。",
+ apiKeyOptionalHint: "選填,留空時不傳送 API 金鑰。",
+ clearApiKey: "清除已儲存的 API 金鑰",
apiStyle: "介面格式",
apiStyleChatCompletions: "OpenAI Chat Completions",
apiStyleOpenCodeGo: "OpenCode Go",
diff --git a/scripts/e2e/provider-api-style.tsx b/scripts/e2e/provider-api-style.tsx
index 227535d93..90ca2cac0 100644
--- a/scripts/e2e/provider-api-style.tsx
+++ b/scripts/e2e/provider-api-style.tsx
@@ -124,9 +124,6 @@ globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
};
- const labeledSwitch = (label: string) =>
- [...document.querySelectorAll<HTMLButtonElement>('[role="switch"]')]
- .find((button) => button.getAttribute("aria-label") === label);
/* A Field explains itself through the help icon's accessible name, so read the
row's explanations from the affordance that carries them. */
const rowHints = () => [...document.querySelectorAll<HTMLElement>(
@@ -247,14 +244,19 @@ globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
assert(discovery.baseUrl === "https://api.stepfun.com/step_plan/v1" &&
discovery.apiStyle === "anthropic_messages" && discovery.apiKey === "stepfun-fixture-key",
`${locale}: StepFun discovery used the wrong route or credentials`);
- const stepfunCheckbox = () => [...document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')]
+ const stepfunCheckbox = () => [...document.querySelectorAll<HTMLInputElement>('.provider-models-row input[type="checkbox"]')]
.find((input) => input.closest("label")?.textContent?.includes("step-5-preview"));
- await until(() => Boolean(stepfunCheckbox()), "StepFun discovered model");
- // Exercise explicit selection even when the recommendation preselected it.
- if (stepfunCheckbox()!.checked) click(stepfunCheckbox());
+ await until(() => Boolean(stepfunCheckbox()?.checked && !stepfunCheckbox()!.disabled),
+ "StepFun recommendation selected");
+ // Wait for committed selection state between the two user interactions.
+ await frame();
+ click(stepfunCheckbox());
+ await until(() => !stepfunCheckbox()?.checked && control("settings.saveProvider").disabled,
+ "StepFun model deselected");
+ await frame();
click(stepfunCheckbox());
- assert(stepfunCheckbox()!.checked, `${locale}: StepFun model was not selected`);
- await until(() => !control("settings.saveProvider").disabled, "StepFun save enabled");
+ await until(() => Boolean(stepfunCheckbox()?.checked) && !control("settings.saveProvider").disabled,
+ "StepFun model selected and save enabled");
click(control("settings.saveProvider"));
await until(() => creates.length === beforeStepfunCreate + 1, "StepFun saved");
const savedStepfun = creates.at(-1)!;
@@ -283,23 +285,19 @@ globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
`${locale}: new custom form offers the account format ${style}`);
}
await closeApiStyleMenu();
- const noKeyControl = labeledSwitch(i18n.t("settings.noApiKeyRequired"));
- assert(noKeyControl && noKeyControl.getAttribute("aria-checked") === "false",
- `${locale}: custom endpoint must default to API-key authentication`);
+ assert(!document.querySelector('[role="switch"]'),
+ `${locale}: custom endpoint still exposes a no-key switch`);
const identityInputs = [...document.querySelectorAll<HTMLInputElement>(
".provider-setup-custom-identity-row input",
)];
assert(identityInputs.length === 2, `${locale}: custom identity fields are missing`);
setValue(identityInputs[0]!, "Local Ollama");
setValue(identityInputs[1]!, "http://127.0.0.1:11434/v1");
- click(noKeyControl);
- assert(noKeyControl.getAttribute("aria-checked") === "true",
- `${locale}: no-API-key mode did not turn on`);
- const disabledKeyInput = document.querySelector<HTMLInputElement>('input[type="password"]');
- assert(disabledKeyInput?.disabled && disabledKeyInput.value === "",
- `${locale}: no-API-key mode did not clear and disable the API-key input`);
- assert(document.documentElement.innerText.includes(i18n.t("settings.noApiKeyHint")),
- `${locale}: no-API-key behavior was not explained`);
+ const optionalKeyInput = document.querySelector<HTMLInputElement>('input[type="password"]');
+ assert(optionalKeyInput && !optionalKeyInput.disabled && optionalKeyInput.value === "",
+ `${locale}: optional API-key input is not available`);
+ assert(rowHints().includes(i18n.t("settings.apiKeyOptionalHint")),
+ `${locale}: optional API-key behavior was not explained`);
const beforeLocalDiscovery = discoveries.length;
await until(() => discoveries.length > beforeLocalDiscovery, "local no-auth discovery");
const localProbe = discoveries.at(-1)!;
@@ -338,13 +336,21 @@ globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
baseUrl: "http://127.0.0.1:9000/v1",
};
render({ provider: editableKeyProvider });
- const editNoKeyControl = labeledSwitch(i18n.t("settings.noApiKeyRequired"));
- assert(editNoKeyControl && editNoKeyControl.getAttribute("aria-checked") === "false",
- `${locale}: API-key provider edit opened in the wrong mode`);
- click(editNoKeyControl);
- const disabledEditKeyInput = document.querySelector<HTMLInputElement>('input[type="password"]');
- assert(disabledEditKeyInput?.disabled,
- `${locale}: switched no-auth edit did not disable the API-key field`);
+ assert(rowHints().includes(i18n.t("settings.apiKeyKeepHint")),
+ `${locale}: editing did not explain saved-key preservation`);
+ const beforeKeepUpdate = updates.length;
+ click(control("settings.saveProvider"));
+ await until(() => updates.length === beforeKeepUpdate + 1, "saved key preserved");
+ const keepUpdate = updates.at(-1)!;
+ assert(!("authKind" in keepUpdate) && !("secretValue" in keepUpdate),
+ `${locale}: blank edit changed the stored authentication`);
+ render({ provider: editableKeyProvider });
+ click(control("settings.clearApiKey"));
+ const clearedKeyInput = document.querySelector<HTMLInputElement>('input[type="password"]');
+ assert(clearedKeyInput && !clearedKeyInput.disabled && clearedKeyInput.value === "",
+ `${locale}: clearing a saved key disabled the input`);
+ assert(rowHints().includes(i18n.t("settings.apiKeyOptionalHint")),
+ `${locale}: clearing a saved key did not explain the no-key behavior`);
const beforeNoAuthUpdate = updates.length;
click(control("settings.saveProvider"));
await until(() => updates.length === beforeNoAuthUpdate + 1, "provider changed to no-auth");
@@ -397,8 +403,8 @@ globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
assert(!control("settings.saveProvider").disabled, "supported copy is blocked");
click(control("settings.saveProvider")); await pause();
const created = creates.at(-1)!;
- assert(created.apiStyle === "anthropic_messages" && created.authKind === "api_key_and_base_url",
- "copy did not persist the explicitly chosen protocol");
+ assert(created.apiStyle === "anthropic_messages" && created.authKind === "none",
+ "copy did not persist the chosen protocol and automatic no-key authentication");
assert(!created.secretValue && !("id" in created), "copy retained source identity or credential");
assert(JSON.stringify(original) === before, "edit/copy mutated source object");
results.push(`${locale}:${style}:edit-change-copy-cancel`);