Skip to content

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

30.6 KB
Raw Blame
import { verifyReasoningEffort } from "./provider-reasoning-effort";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { catalogs } from "@pi-desktop/i18n";
import type { ProviderPublic, ProviderCreateInput, ProviderUpdateInput } from "@pi-desktop/shared";
import { ProviderSetupDialog, type ProviderSetupDialogProps } from "../../apps/desktop/src/components/settings/ProviderSetupDialog";
import { VendorAccountDialog, type VendorAccountForm } from "../../apps/desktop/src/components/settings/VendorAccountDialog";
import { defaultModelOptions, providerServesChatModels } from "../../apps/desktop/src/components/settings/default-model";
import { subagentModelChoices } from "../../apps/desktop/src/components/settings/subagent-models";
import { API_STYLE_LABEL_KEYS, CUSTOM_PROVIDER_API_STYLES } from "../../apps/desktop/src/components/settings/provider-api-style";
import { copyProviderConfiguration } from "../../apps/desktop/src/components/settings/provider-copy";
import { CUSTOM_SERVICE } from "../../apps/desktop/src/components/settings/service-catalog";
import { api } from "../../apps/desktop/src/lib/api";

declare global { var providerApiStyleProbe: (reasoningOnly?: boolean) => Promise<unknown>; }
const assert = (value: unknown, message: string) => { if (!value) throw new Error(message); };
const pause = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
/* Anchored menus mount, position and reveal on animation frames, so wait for a
   frame instead of guessing a duration; the timeout keeps a throttled window
   from hanging the probe. */
const frame = () => new Promise<void>((resolve) => {
  const timeout = setTimeout(resolve, 50);
  requestAnimationFrame(() => { clearTimeout(timeout); resolve(); });
});
const ACCOUNT_ONLY_STYLES = ["openai_codex_responses", "pi_messages"] as const;
type AccountOnlyStyle = (typeof ACCOUNT_ONLY_STYLES)[number];
const fixture = (apiStyle: string): ProviderPublic => ({
  id: "legacy", name: "Legacy custom", vendorKey: "custom", type: "openai_compatible",
  protocol: "openai_compatible", enabled: true, authKind: "api_key_and_base_url",
  apiStyle, baseUrl: "https://api.openai.com/v1", hasSecret: true,
  supportsReasoning: false, supportedThinkingLevels: ["off"], createdAt: "", updatedAt: "",
  models: [{ id: "fixture", alias: "Fixture alias", contextWindow: 32000, maxTokens: 4000,
    thinkingLevels: ["off"], defaultThinkingLevel: "off" }],
});

globalThis.providerApiStyleProbe = async (reasoningOnly = false) => {
  const i18n = createInstance();
  await i18n.init({ lng: "en", resources: {
    en: { translation: catalogs.en }, "zh-CN": { translation: catalogs["zh-CN"] }, de: { translation: catalogs.de },
  }, interpolation: { escapeValue: false } });
  const creates: ProviderCreateInput[] = [];
  const updates: ProviderUpdateInput[] = [];
  const discoveries: Parameters<typeof api.listProviderModels>[0][] = [];
  let savedProvider: ProviderPublic | undefined;
  // Only the API boundary is faked: render the production form/hooks and inspect
  // exact save payloads. This does not validate Host persistence or live OAuth.
  api.createProvider = async (input) => {
    creates.push(structuredClone(input));
    const saved: ProviderPublic = {
      ...fixture(input.apiStyle ?? "chat_completions"),
      id: `created-${creates.length}`,
      name: input.name,
      vendorKey: input.vendorKey ?? "custom",
      type: input.type ?? "openai_compatible",
      protocol: input.protocol ?? "openai_compatible",
      baseUrl: input.baseUrl,
      authKind: input.authKind ?? "api_key_and_base_url",
      hasSecret: Boolean(input.secretValue),
      hasOauth: false,
      models: input.models ?? [],
    };
    return { provider: saved };
  };
  api.updateProvider = async (input) => {
    updates.push(structuredClone(input));
    return { provider: {
      ...fixture(input.apiStyle ?? "chat_completions"),
      ...input,
      authKind: input.authKind ?? "api_key_and_base_url",
      hasSecret: input.authKind === "none" ? false : true,
    } };
  };
  api.listProviderModels = async (input) => {
    discoveries.push(structuredClone(input));
    if (input.baseUrl === "https://api.stepfun.com/step_plan/v1") {
      return { models: [{
        modelId: "step-5-preview", displayName: "Step 5 Preview", providerId: "stepfun-fixture",
        source: "discovered", capabilities: ["text", "tools", "vision", "reasoning"],
        supportedThinkingLevels: ["low", "medium", "high"], contextWindow: 1000000, maxTokens: 65536,
      }], source: "remote" };
    }
    if (input.baseUrl === "http://127.0.0.1:11434/v1") {
      return { models: [{
        modelId: "local-chat", displayName: "Local Chat", providerId: "",
        source: "discovered", capabilities: ["text", "tools"],
        contextWindow: 32768, maxTokens: 4096,
      }], source: "remote" };
    }
    return { models: [], source: "remote" };
  };
  /* The root container only mounts React; every production surface under test
     renders itself through a portal, so all queries below are document-rooted. */
  const host = document.createElement("div");
  document.body.append(host);
  const root = createRoot(host);
  let key = 0;
  let closes = 0;
  const render = (props: Partial<ProviderSetupDialogProps> = {}) => {
    flushSync(() => root.render(<I18nextProvider i18n={i18n}>
      <ProviderSetupDialog
        key={++key}
        onClose={() => { closes++; }}
        onSaved={(provider) => { savedProvider = structuredClone(provider); }}
        {...props}
      />
    </I18nextProvider>));
    const advanced = document.querySelector<HTMLButtonElement>(".provider-chosen-advanced-toggle");
    if (advanced?.getAttribute("aria-expanded") === "false") flushSync(() => advanced.click());
  };
  const click = (element: HTMLElement | null | undefined) => {
    assert(element, "missing click target");
    flushSync(() => element!.click());
  };
  const button = (key: string) => [...document.querySelectorAll<HTMLButtonElement>("button")]
    .find((element) => element.getAttribute("aria-label") === i18n.t(key)
      || element.textContent?.trim() === i18n.t(key));
  const control = (key: string) => {
    const element = button(key);
    assert(element, `missing control ${key}`);
    return element;
  };
  const setValue = (input: HTMLInputElement, value: string) => {
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
    input.dispatchEvent(new Event("input", { bubbles: true }));
  };
  /* 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>(
    ".provider-setup-custom-auth-row .ui-help-icon")]
    .map((element) => element.getAttribute("aria-label") ?? "");
  const apiStyleLabel = (style: string) =>
    i18n.t(API_STYLE_LABEL_KEYS[style as keyof typeof API_STYLE_LABEL_KEYS]);
  const customLabels = () => CUSTOM_PROVIDER_API_STYLES.map(apiStyleLabel);

  /*
    The API format row is a SettingsMenuSelect: a trigger button that reports the
    current label, and options rendered by AnchoredMenu through a portal into
    document.body. Open the real control, read the real option list, and click
    the real option button.
  */
  const apiStyleTrigger = () => document.querySelector<HTMLButtonElement>(
    ".provider-setup-custom-auth-row .settings-menu-select-trigger");
  const apiStyleMenu = () => document.querySelector<HTMLElement>(".settings-menu-select-menu");
  const apiStyleOptions = () => [...(apiStyleMenu()?.querySelectorAll<HTMLButtonElement>(
    ".settings-menu-select-option") ?? [])];
  const optionLabel = (option: HTMLElement) =>
    option.querySelector(".settings-menu-select-option-label")?.textContent?.trim()
    ?? option.textContent?.trim() ?? "";
  const optionSnapshot = () => apiStyleOptions().map((option) => ({
    label: optionLabel(option),
    current: option.getAttribute("aria-selected") === "true",
    disabled: option.disabled,
  }));
  const openApiStyleMenu = async () => {
    const trigger = apiStyleTrigger();
    assert(trigger, "api style control missing");
    assert(trigger.getAttribute("aria-haspopup") === "listbox", "api style control is not a menu select");
    assert(!apiStyleMenu(), "api style menu was already open");
    // AnchoredMenu closes a menu whose anchor sits outside the viewport.
    trigger.scrollIntoView({ block: "center" });
    await frame();
    click(trigger);
    await frame();
    assert(apiStyleMenu(), "api style menu did not open");
    assert(trigger.getAttribute("aria-expanded") === "true", "api style menu did not report aria-expanded");
    return trigger;
  };
  const closeApiStyleMenu = async () => {
    const trigger = apiStyleTrigger();
    assert(trigger, "api style control missing");
    assert(apiStyleMenu(), "api style menu is not open");
    click(trigger);
    await frame();
    assert(!apiStyleMenu(), "api style menu stayed open");
  };
  const chooseApiStyle = async (style: string) => {
    await openApiStyleMenu();
    const option = apiStyleOptions().find((item) => optionLabel(item) === apiStyleLabel(style));
    assert(option, `${style}: api style option missing`);
    assert(!option.disabled, `${style}: api style option is disabled`);
    click(option);
    await frame();
    assert(!apiStyleMenu(), `${style}: api style menu stayed open after choosing`);
    assert(apiStyleTrigger()?.getAttribute("aria-expanded") === "false", `${style}: menu did not collapse`);
    assert(apiStyleTrigger()?.textContent?.trim() === apiStyleLabel(style), `${style}: choice did not reach the control`);
  };
  /* The legacy protocol stays listed, selected and unusable as a new choice. */
  const assertAccountOnlyOption = async (style: AccountOnlyStyle, context: string) => {
    assert(apiStyleTrigger()?.textContent?.trim() === apiStyleLabel(style), `${context}: shows the wrong format`);
    await openApiStyleMenu();
    const options = optionSnapshot();
    assert(options.length === CUSTOM_PROVIDER_API_STYLES.length + 1, `${context}: option list length`);
    assert(options[0]!.label === apiStyleLabel(style), `${context}: account format is not the first option`);
    assert(options[0]!.current, `${context}: account format is not the current selection`);
    assert(options[0]!.disabled, `${context}: account format must remain visible without being a new choice`);
    assert(JSON.stringify(options.slice(1).map((option) => option.label)) === JSON.stringify(customLabels()),
      `${context}: custom formats changed`);
    await closeApiStyleMenu();
  };

  const results: string[] = [];
  const until = async (condition: () => boolean, label: string) => {
    const deadline = performance.now() + 5000;
    while (!condition()) {
      assert(performance.now() < deadline, `timed out: ${label}`);
      await frame();
    }
  };
  const searchInput = () => [...document.querySelectorAll<HTMLInputElement>("input[type=checkbox]")]
    .find((input) => input.closest("label")?.textContent?.trim() === i18n.t("settings.nativeWebSearch"));
  const openModelManager = async () => {
    // The model panel is on screen when the editor opens (D625): no Manage
    // models step, only the per-model controls the scenario waits for.
    await until(() => Boolean(searchInput()), "model capability settings");
  };
  try {
    for (const locale of (reasoningOnly ? ["en", "zh-CN", "de"] : ["en", "zh-CN"])) {
      await i18n.changeLanguage(locale);
      if (reasoningOnly) {
        await verifyReasoningEffort({ render, fixture, i18n, updates, click, control, until, frame });
        results.push(`${locale}:reasoning-effort-auto-send-omit-save-reopen-protocol-switch`);
        continue;
      }
      render();
      const beforeStepfunCreate = creates.length;
      const beforeStepfunDiscovery = discoveries.length;
      const stepfunTile = document.querySelector<HTMLElement>('[data-service-id="stepfun-plan"]');
      assert(stepfunTile?.textContent?.includes("api.stepfun.com/step_plan/v1"),
        `${locale}: StepFun chooser hides the subscription path`);
      click(stepfunTile);
      await frame();
      assert(document.querySelector(".provider-service-chip-host")?.textContent === "api.stepfun.com/step_plan/v1",
        `${locale}: StepFun connection summary hides the subscription path`);
      const keyInput = document.querySelector<HTMLInputElement>('input[type="password"]');
      assert(keyInput, `${locale}: StepFun key input missing`);
      flushSync(() => {
        Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!
          .call(keyInput, "stepfun-fixture-key");
        keyInput!.dispatchEvent(new Event("input", { bubbles: true }));
      });
      await until(() => discoveries.length > beforeStepfunDiscovery, "StepFun discovery");
      const discovery = discoveries.at(-1)!;
      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>('.provider-models-row input[type="checkbox"]')]
        .find((input) => input.closest("label")?.textContent?.includes("step-5-preview"));
      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());
      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)!;
      assert(savedStepfun.vendorKey === "stepfun-step-plan" &&
        savedStepfun.baseUrl === "https://api.stepfun.com/step_plan/v1" &&
        savedStepfun.apiStyle === "anthropic_messages", `${locale}: StepFun saved the wrong preset`);
      assert(savedStepfun.models?.length === 1 && savedStepfun.models[0].id === "step-5-preview",
        `${locale}: StepFun saved the wrong model selection`);
      results.push(`${locale}:stepfun-plan-choose-key-discover-select-save`);
      render();
      // A new service opens on the chooser (D625, D626); the custom endpoint
      // leads the API-key tiles, and picking it moves to the form.
      const tiles = [...document.querySelectorAll<HTMLButtonElement>("[data-service-id]")];
      assert(tiles.length > 1, `${locale}: service chooser tiles missing`);
      assert(tiles.at(0)?.dataset.serviceId === CUSTOM_SERVICE, `${locale}: custom endpoint is not first`);
      assert(!apiStyleTrigger(), `${locale}: form rendered before a service was chosen`);
      click(tiles.at(0));
      await frame();
      assert(!document.querySelector("[data-service-id]"), `${locale}: chooser stayed open after a pick`);
      await openApiStyleMenu();
      const newCustomOptions = optionSnapshot();
      assert(JSON.stringify(newCustomOptions.map((option) => option.label)) === JSON.stringify(customLabels()),
        `${locale}: new custom form exposes an account format`);
      for (const style of ACCOUNT_ONLY_STYLES) {
        assert(!newCustomOptions.some((option) => option.label === apiStyleLabel(style)),
          `${locale}: new custom form offers the account format ${style}`);
      }
      await closeApiStyleMenu();
      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");
      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)!;
      assert(localProbe.baseUrl === "http://127.0.0.1:11434/v1" && !localProbe.apiKey,
        `${locale}: local model discovery included an API key`);
      await until(
        () => Boolean(document.querySelector<HTMLInputElement>(".provider-models-row input")),
        "local model discovery result",
      );
      const localModel = document.querySelector<HTMLInputElement>(".provider-models-row input");
      assert(localModel, `${locale}: the local service model was not selectable`);
      if (!localModel.checked) click(localModel);
      await until(() => !control("settings.saveProvider").disabled, "no-auth provider save enabled");
      const beforeLocalCreate = creates.length;
      savedProvider = undefined;
      click(control("settings.saveProvider"));
      await until(() => creates.length === beforeLocalCreate + 1 && Boolean(savedProvider),
        "no-auth provider saved");
      const savedNoAuth = creates.at(-1)!;
      assert(savedNoAuth.authKind === "none" && !("secretValue" in savedNoAuth),
        `${locale}: no-auth selection did not persist without a secret`);
      assert(savedProvider?.authKind === "none" && savedProvider.hasSecret === false,
        `${locale}: saved provider is still marked as credentialed`);
      assert(providerServesChatModels(savedProvider!),
        `${locale}: saved no-auth provider is not eligible for the default model`);
      assert(defaultModelOptions([savedProvider!]).some((option) => option.modelId === "local-chat"),
        `${locale}: no-auth provider is missing from default-model options`);
      assert(subagentModelChoices([savedProvider!]).some((option) => option.modelId === "local-chat"),
        `${locale}: no-auth provider is missing from subagent model options`);
      results.push(`${locale}:custom-endpoint-no-api-key-save-and-selection`);

      const editableKeyProvider = {
        ...fixture("chat_completions"),
        id: `key-provider-${locale}`,
        name: "Key-backed gateway",
        baseUrl: "http://127.0.0.1:9000/v1",
      };
      render({ provider: editableKeyProvider });
      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");
      const noAuthUpdate = updates.at(-1)!;
      assert(noAuthUpdate.authKind === "none" && !("secretValue" in noAuthUpdate),
        `${locale}: edit did not persist the no-auth mode without a replacement key`);
      results.push(`${locale}:edit-provider-switches-to-no-api-key`);

      results.push(`${locale}:new-custom-options`);

      for (const style of ACCOUNT_ONLY_STYLES) {
        const original = fixture(style);
        const before = JSON.stringify(original);
        render({ provider: original });
        await assertAccountOnlyOption(style, `${locale}:${style}:edit`);
        assert(rowHints().includes(i18n.t("settings.apiStyleLegacyAccount")), "legacy explanation missing");
        assert(!control("settings.saveProvider").disabled, "legacy unchanged save blocked");
        click(control("settings.saveProvider")); await pause();
        const update = updates.at(-1)!;
        assert(update.apiStyle === style && update.name === original.name && update.baseUrl === original.baseUrl,
          "legacy edit changed protocol/name/URL through preset matching");
        assert(!("authKind" in update) && !("secretValue" in update), "legacy edit changed authentication");
        assert(update.models?.[0].alias === "Fixture alias", "legacy bindings changed");

        render({ provider: original });
        await chooseApiStyle("responses");
        click(control("settings.saveProvider")); await pause();
        assert(updates.at(-1)?.apiStyle === "responses", "explicit legacy protocol change not saved");

        const draft = copyProviderConfiguration(original, "Copy fixture");
        render({ initialDraft: draft });
        await assertAccountOnlyOption(style, `${locale}:${style}:copy`);
        assert(control("settings.saveProvider").disabled, "copy accepts account-only protocol");
        assert(rowHints().includes(i18n.t("settings.apiStyleChooseCustom")), "copy choice explanation missing");
        const discoveryCount = discoveries.length;
        await pause(650);
        assert(discoveries.length === discoveryCount, "unsupported copy triggered discovery");
        const createCount = creates.length;
        click(control("settings.saveProvider")); await pause();
        assert(creates.length === createCount, "blocked copy was saved");
        click(control("settings.cancel"));
        assert(closes > 0 && creates.length === createCount, "cancel saved a copy");

        render({ initialDraft: draft });
        await chooseApiStyle("anthropic_messages");
        await pause(650);
        const discovery = discoveries.at(-1)!;
        assert(discovery.apiStyle === "anthropic_messages" && !discovery.providerId && !discovery.apiKey,
          "copy discovery reused source protocol or credentials");
        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 === "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`);
      }
      await verifyReasoningEffort({ render, fixture, i18n, updates, click, control, until, frame });
      results.push(`${locale}:reasoning-effort-auto-send-omit-save-reopen-protocol-switch`);
      for (const [vendorKey, baseUrl, modelId] of [
        ["deepseek", "https://api.deepseek.com", "deepseek-v4-flash"],
        ["xai", "https://api.x.ai/v1", "grok-4.7"],
        ["openai", "https://api.openai.com/v1", "gpt-6-sol"],
      ]) {
        const original = { ...fixture("chat_completions"), name: "My service", vendorKey, baseUrl,
          models: [{ ...fixture("chat_completions").models[0], id: modelId }] };
        render({ provider: original });
        await openModelManager();
        await until(() => Boolean(searchInput()), "official model settings");
        assert(!searchInput()?.disabled && !searchInput()?.checked, `${vendorKey}: search must be directly selectable and default off`);
        assert(!document.querySelector(".provider-endpoint-guidance"), "official search requires an extra interface action");
        const count = updates.length;
        click(searchInput());
        click(control("settings.cancel"));
        assert(updates.length === count, "cancel persisted the search opt-in");
        render({ provider: original });
        await openModelManager();
        click(searchInput());
        click(control("settings.saveProvider"));
        await until(() => updates.length === count + 1, "save search opt-in");
        const update = updates.at(-1)!;
        assert(update.apiStyle === original.apiStyle && update.baseUrl === original.baseUrl,
          "search opt-in rewrote the saved service transport");
        assert(update.name === original.name && !("secretValue" in update), "search opt-in replaced name or key");
        assert(update.models?.[0].nativeWebSearch === true && update.models[0].alias === "Fixture alias", "model settings lost");
        render({ provider: { ...original, ...update } });
        await openModelManager();
        assert(searchInput()?.checked && !searchInput()?.disabled, "search opt-in was lost on reopen");
        click(searchInput());
        click(control("settings.saveProvider"));
        await until(() => updates.length === count + 2, "save search off");
        assert(!updates.at(-1)?.models?.[0].nativeWebSearch, "search opt-out was not saved");
        assert(updates.at(-1)?.apiStyle === original.apiStyle && updates.at(-1)?.baseUrl === original.baseUrl,
          "search opt-out changed the stored route");
        results.push(`${locale}:${vendorKey}:single-entry-search-cancel-save-reopen-off`);
      }

      for (const [operation, style] of [["responses", "responses"], ["messages", "anthropic_messages"]] as const) {
        const relay = { ...fixture("chat_completions"), baseUrl: `https://relay.example/v1/${operation}` };
        render({ provider: relay });
        assert(apiStyleTrigger()?.textContent?.includes(apiStyleLabel("chat_completions")), "URL advice silently changed protocol");
        click(control("settings.applyEndpointFormat"));
        assert(apiStyleTrigger()?.textContent?.includes(apiStyleLabel(style)), "suggested format not applied");
        const count = updates.length;
        click(control("settings.saveProvider"));
        await until(() => updates.length === count + 1, "save suggested format");
        assert(updates.at(-1)?.baseUrl === "https://relay.example/v1" && updates.at(-1)?.apiStyle === style,
          "suggestion changed destination or retained the operation suffix");
        render({ provider: { ...relay, ...updates.at(-1)! } });
        assert(!button("settings.applyEndpointFormat"), "suggestion reappeared after save");
      }
      results.push(`${locale}:relay-explicit-format-suggestion-save-reopen`);

      const manual = { ...fixture("chat_completions"), vendorKey: "openai" };
      render({ provider: manual });
      assert(apiStyleTrigger()?.textContent?.includes(apiStyleLabel("chat_completions")), "named host overwrote manual format");
      const beforeManualSave = updates.length;
      click(control("settings.saveProvider"));
      await until(() => updates.length === beforeManualSave + 1, "save manual format provider");
      assert(updates.at(-1)?.vendorKey === manual.vendorKey,
        "a stored format differing from the preset dropped the row's vendor identity");
      results.push(`${locale}:saved-protocol-wins-over-preset`);

      const legacyUnknown = { ...fixture("future_api_format"),
        baseUrl: "https://relay.example/v1/chat/completions" };
      render({ provider: legacyUnknown });
      assert(apiStyleTrigger()?.textContent?.includes(apiStyleLabel("chat_completions")),
        "unknown stored API format did not render with the compatible fallback");
      const beforeUnknownSave = updates.length;
      click(control("settings.saveProvider"));
      await until(() => updates.length === beforeUnknownSave + 1, "save legacy unknown API format");
      assert(updates.at(-1)?.apiStyle === "chat_completions" &&
        updates.at(-1)?.baseUrl === "https://relay.example/v1",
        "unknown stored format did not save the normalized compatible endpoint");
      results.push(`${locale}:unknown-stored-api-format-open-save`);

      const codexAccount = { ...fixture("openai_codex_responses"), id: "codex-account", name: "OpenAI OAuth", vendorKey: "openai-codex", type: "native", protocol: "openai", authKind: "oauth" } satisfies ProviderPublic;
      let savedCodexAccount: VendorAccountForm | undefined;
      flushSync(() => root.render(<I18nextProvider i18n={i18n}><VendorAccountDialog provider={codexAccount} initialName={codexAccount.name} onClose={() => { closes++; }} onSave={(form) => { savedCodexAccount = structuredClone(form); }} saving={false} /></I18nextProvider>));
      await pause(650);
      // The account editor opens straight on the model panel (D625): the
      // per-model controls sit behind the row's own Advanced disclosure.
      assert(!document.querySelector(".provider-models-summary"), `${locale}: the chosen-models summary is gone from the account dialog`);
      await frame();
      const advancedToggle = document.querySelector<HTMLButtonElement>(".provider-chosen-advanced-toggle");
      assert(advancedToggle?.getAttribute("aria-expanded") === "false", `${locale}: a model opened its advanced settings on its own`);
      click(advancedToggle);
      await frame();
      const findWebSearch = () => [...document.querySelectorAll<HTMLInputElement>("input[type=checkbox]")].find((input) => input.closest("label")?.textContent?.trim() === i18n.t("settings.nativeWebSearch"));
      const searchCheckbox = findWebSearch();
      assert(searchCheckbox, `${locale}: Codex web search checkbox missing`);
      assert(!searchCheckbox!.disabled, `${locale}: Codex web search checkbox stayed disabled`);
      assert(!searchCheckbox!.checked, `${locale}: native search must default off`);
      click(searchCheckbox);
      await frame();
      assert(findWebSearch()?.checked, `${locale}: Codex web search opt-in did not update`);
      click(control("settings.save"));
      await pause();
      assert(savedCodexAccount?.models[0]?.nativeWebSearch === true, `${locale}: Codex web search opt-in was not saved`);
      results.push(`${locale}:codex-native-search-opt-in`);
    }
    return { ok: true, scenarios: results, creates: creates.length, updates: updates.length,
      apiBoundary: "stubbed", hostPersistence: "not exercised", liveModel: "not exercised" };
  } finally { flushSync(() => root.unmount()); host.remove(); }
};