Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

34.0 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { ChevronRight, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Form, FormLabel } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { ImeSafeInput } from "@/components/ui/ime-safe-input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { HelpTip } from "@/components/ui/help-tip";
import { HoverTip } from "@/components/ui/hover-tip";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useLatestRef } from "@/hooks/useLatestRef";
import { useModelMetadataFill } from "@/hooks/useModelMetadataFill";
import { useQoderEdition } from "@/hooks/useQoderEdition";
import {
  fetchModelsForConfig,
  showFetchModelsError,
  type FetchedModel,
} from "@/lib/api/model-fetch";
import type { QoderModel, QoderProvider } from "@/lib/api/qoder";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useProvidersQuery } from "@/lib/query/queries";
import type { ProviderFormData } from "@/lib/schemas/provider";
import type { ProviderCategory } from "@/types";
import {
  qoderAccountPreset,
  qoderProviderPresets,
  QODER_ACCOUNT_PRESET_ID,
} from "@/config/qoderProviderPresets";
import { piPresetModelSources } from "@/config/presetModelMetadata";
import { BasicFormFields, REQUIRED_LABEL } from "./BasicFormFields";
import {
  ApiKeySection,
  EndpointField,
  GptContextWindowHint,
  ModelDropdown,
  NativeConfigEditor,
} from "./shared";
import {
  FetchedModelPicker,
  type FetchedModelSelection,
} from "./FetchedModelPicker";
import { fillQoderModel, metadataFilledAnything } from "./modelMetadataFill";
import { ProviderPresetSelector } from "./ProviderPresetSelector";
import type { ProviderFormProps } from "./ProviderForm";
import { usePresetStep } from "./presetStep";

type Protocol = NonNullable<QoderProvider["protocol"]>;
type AuthType = NonNullable<QoderProvider["authType"]>;
type ThinkingMode = "off" | "enabled" | "adaptive";

// 和 Pi、Kimi 的「接口格式」下拉用同一套叫法。
const PROTOCOL_LABELS: Record<Protocol, string> = {
  openai: "OpenAI Chat Completions",
  "openai-responses": "OpenAI Responses",
  anthropic: "Anthropic Messages",
};
const AUTH_TYPE_LABELS: Record<AuthType, string> = {
  bearer: "Bearer Token",
  "api-key": "API Key (x-api-key)",
};
// 拉模型列表时按协议选认证头:Anthropic 用 x-api-key。
const MODEL_FETCH_API_FORMATS: Partial<Record<Protocol, string>> = {
  anthropic: "anthropic-messages",
};
// 供应商 ID 是 settings.json 里 providers 的键:Qoder 认字母、数字、点、下划线和连字符;
// 官方账号卡的 ID 前缀留给 CC Switch 用
const RESERVED_IDS = new Set(["qoder", "constructor", "prototype"]);
const OFFICIAL_ID_PREFIX = "qoder-official-";
const isValidKey = (key: string) =>
  /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key) &&
  !RESERVED_IDS.has(key) &&
  !key.startsWith(OFFICIAL_ID_PREFIX);
const normalizeKey = (value: string) => value.replace(/[^A-Za-z0-9._-]/g, "");

const PRESETS = qoderProviderPresets.map((preset) => ({
  id: preset.providerKey,
  preset,
}));

const emptyConfig = (): QoderProvider => ({
  type: "openai-compatible",
  protocol: "openai",
  authType: "bearer",
  baseUrl: "",
  apiKey: "",
  models: [],
});

const newModel = (model = ""): QoderModel => ({
  model,
  capabilities: { tools: true, vision: false },
});

/** 表单里的供应商:模型统一放在 models 里,只写了 `model` 的旧写法补成一行。 */
function formConfig(raw: unknown): QoderProvider {
  const initial =
    raw && typeof raw === "object" && !Array.isArray(raw)
      ? (raw as QoderProvider)
      : emptyConfig();
  const models = Array.isArray(initial.models) ? [...initial.models] : [];
  if (initial.model && !models.some((model) => model.model === initial.model))
    models.push({ model: initial.model });
  return {
    ...initial,
    baseUrl: typeof initial.baseUrl === "string" ? initial.baseUrl : "",
    apiKey: typeof initial.apiKey === "string" ? initial.apiKey : "",
    models: structuredClone(models),
  };
}

const thinkingMode = (model: QoderModel): ThinkingMode => {
  const thinking = model.capabilities?.thinking;
  const mode = thinking?.preferredMode ?? thinking?.modes?.[0];
  return mode === "enabled" || mode === "adaptive" ? mode : "off";
};

/** 存盘前:去掉模型 ID 两端的空白,默认模型不在列表里时用第一个。 */
function finalize(config: QoderProvider, name: string): QoderProvider {
  const models = (config.models ?? []).map((model) => ({
    ...model,
    model: model.model.trim(),
  }));
  const model = models.some((entry) => entry.model === config.model)
    ? config.model
    : models[0]?.model;
  return {
    ...config,
    ...(name ? { displayName: name } : {}),
    baseUrl: config.baseUrl.trim(),
    model,
    models,
  };
}

export function QoderProviderForm({
  providerId,
  initialData,
  onSubmit,
  onCancel,
  submitLabel,
  showButtons = true,
  onSubmittingChange,
  onSubmitReadyChange,
  onAccountLoginChange,
  onManageAuthAccounts,
}: ProviderFormProps) {
  const { t } = useTranslation();
  const edition = useQoderEdition() ?? "global";
  const isEdit = Boolean(initialData);
  // 官方账号卡:登录和删除都在授权中心,这里只改名字、备注这些卡片信息
  const isOfficial = isEdit && initialData?.category === "official";
  const [config, setConfig] = useState<QoderProvider>(() =>
    formConfig(initialData?.settingsConfig),
  );
  const [providerKey, setProviderKey] = useState(providerId ?? "");
  const [text, setText] = useState(() =>
    JSON.stringify(formConfig(initialData?.settingsConfig), null, 2),
  );
  const [textError, setTextError] = useState<string | null>(null);
  const [presetId, setPresetId] = useState("custom");
  const [category, setCategory] = useState<ProviderCategory>(
    initialData?.category ?? "custom",
  );
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const { data: existing } = useProvidersQuery("qoder");
  const step = usePresetStep();
  const isAccountLogin = !isEdit && presetId === QODER_ACCOUNT_PRESET_ID;
  const showAccountLogin = isAccountLogin && (!step || step.step === "form");
  useEffect(() => {
    onAccountLoginChange?.(showAccountLogin);
    return () => onAccountLoginChange?.(false);
  }, [showAccountLogin, onAccountLoginChange]);
  const duplicate =
    !isEdit &&
    Object.prototype.hasOwnProperty.call(
      existing?.providers ?? {},
      providerKey,
    );
  const keyValid = isEdit || isValidKey(providerKey);
  const preset = PRESETS.find((entry) => entry.id === presetId)?.preset;
  const form = useForm<ProviderFormData>({
    defaultValues: {
      name: initialData?.name ?? "",
      notes: initialData?.notes ?? "",
      websiteUrl: initialData?.websiteUrl ?? "",
      icon: initialData?.icon ?? "",
      iconColor: initialData?.iconColor ?? "",
      settingsConfig: text,
    },
  });
  const name = form.watch("name");
  const models = config.models ?? [];
  const modelsValid =
    models.length > 0 &&
    models.every((model) => model.model.trim()) &&
    new Set(models.map((model) => model.model.trim())).size === models.length &&
    models.every((model) =>
      [model.contextWindow, model.maxOutputTokens].every(
        (value) =>
          value === undefined || (Number.isSafeInteger(value) && value > 0),
      ),
    );
  const ready = isOfficial
    ? Boolean(name.trim())
    : Boolean(
        !isAccountLogin &&
          !textError &&
          name.trim() &&
          keyValid &&
          !duplicate &&
          /^https?:\/\//.test(config.baseUrl.trim()) &&
          modelsValid,
      );
  useEffect(() => {
    onSubmitReadyChange?.(ready);
  }, [ready, onSubmitReadyChange]);
  const configRef = useLatestRef(config);
  const update = (next: QoderProvider) => {
    configRef.current = next;
    setConfig(next);
    setText(JSON.stringify(next, null, 2));
    setTextError(null);
  };
  const updateProvider = (patch: Partial<QoderProvider>) =>
    update({ ...configRef.current, ...patch });
  const updateModel = (index: number, patch: Partial<QoderModel>) =>
    update({
      ...configRef.current,
      models: (configRef.current.models ?? []).map((model, position) =>
        position === index ? { ...model, ...patch } : model,
      ),
    });
  const updateCapabilities = (
    index: number,
    patch: NonNullable<QoderModel["capabilities"]>,
  ) => {
    const model = configRef.current.models?.[index];
    if (model)
      updateModel(index, { capabilities: { ...model.capabilities, ...patch } });
  };
  const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
  const toggleExpanded = (index: number) =>
    setExpanded((current) => {
      const next = new Set(current);
      if (!next.delete(index)) next.add(index);
      return next;
    });

  const [fetchedModels, setFetchedModels] = useState<FetchedModel[]>([]);
  const [isFetchingModels, setIsFetchingModels] = useState(false);
  const modelFetchGeneration = useRef(0);
  const protocol = config.protocol ?? "openai";
  const { baseUrl, apiKey } = config;
  useEffect(() => {
    setFetchedModels((prev) => (prev.length === 0 ? prev : []));
    setIsFetchingModels(false);
    return () => {
      // 地址、Key 或协议变了,旧请求的结果不再适用。
      modelFetchGeneration.current += 1;
    };
  }, [protocol, baseUrl, apiKey]);
  const handleFetchModels = useCallback(() => {
    const endpoint = baseUrl.trim();
    if (!endpoint || !apiKey) {
      showFetchModelsError(null, t, {
        hasApiKey: Boolean(apiKey),
        hasBaseUrl: Boolean(endpoint),
      });
      return;
    }
    const generation = ++modelFetchGeneration.current;
    setFetchedModels([]);
    setIsFetchingModels(true);
    fetchModelsForConfig(endpoint, apiKey, undefined, undefined, undefined, {
      apiFormat: MODEL_FETCH_API_FORMATS[protocol],
    })
      .then((result) => {
        if (generation !== modelFetchGeneration.current) return;
        const fetched = [
          ...new Map(result.map((model) => [model.id, model])).values(),
        ];
        setFetchedModels(fetched);
        if (fetched.length === 0)
          toast.info(t("providerForm.fetchModelsEmpty"));
      })
      .catch((err) => {
        if (generation !== modelFetchGeneration.current) return;
        console.warn("[ModelFetch] Failed:", err);
        showFetchModelsError(err, t);
      })
      .finally(() => {
        if (generation === modelFetchGeneration.current) {
          setIsFetchingModels(false);
        }
      });
  }, [apiKey, baseUrl, protocol, t]);

  const fillModelMetadata = useModelMetadataFill({
    baseUrl,
    presets: piPresetModelSources,
    prefetch: fetchedModels.length > 0,
  });
  // 补全可能晚到:读最新的配置,确认这一行仍是这个模型再补。
  const fillModelMetadataFor = (index: number, id: string, silent?: boolean) =>
    fillModelMetadata(
      id,
      (metadata) => {
        const model = configRef.current.models?.[index];
        if (model?.model !== id) return false;
        const filled = fillQoderModel(model, metadata);
        if (!metadataFilledAnything(model, filled)) return false;
        updateModel(index, filled);
        return true;
      },
      { silent },
    );
  const handleApplyFetchedModels = ({ add, remove }: FetchedModelSelection) => {
    const removed = new Set(remove);
    const kept = (configRef.current.models ?? []).filter(
      (model) => !removed.has(model.model),
    );
    const configured = new Set(kept.map((model) => model.model));
    const added = add.filter((id) => !configured.has(id));
    update({
      ...configRef.current,
      models: [...kept, ...added.map((id) => newModel(id))],
    });
    setExpanded(new Set());
    // 弹窗里已经显示过这些参数,补完不再提示。
    added.forEach((id, offset) =>
      fillModelMetadataFor(kept.length + offset, id, true),
    );
  };

  const presetSelector = (
    <ProviderPresetSelector
      selectedPresetId={presetId}
      presetEntries={[
        { id: QODER_ACCOUNT_PRESET_ID, preset: qoderAccountPreset(edition) },
        ...PRESETS,
      ]}
      presetCategoryLabels={{
        custom: t("providerPreset.custom"),
        cn_official: t("providerForm.categoryCnOfficial"),
        third_party: t("providerPreset.group.thirdparty"),
        aggregator: t("providerPreset.group.thirdparty"),
        cloud_provider: t("providerPreset.group.cloud"),
        local: t("providerPreset.group.local"),
      }}
      category={category}
      onPresetChange={(id) => {
        setPresetId(id);
        if (id === QODER_ACCOUNT_PRESET_ID) return;
        const next = PRESETS.find((entry) => entry.id === id)?.preset;
        setCategory(next?.category ?? "custom");
        update(formConfig(structuredClone(next?.settingsConfig)));
        setExpanded(new Set());
        setProviderKey(next?.providerKey ?? "");
        form.reset({
          name: next?.nameKey ? t(next.nameKey) : (next?.name ?? ""),
          notes: "",
          websiteUrl: next?.websiteUrl ?? "",
          icon: next?.icon ?? "",
          iconColor: next?.iconColor ?? "",
          settingsConfig: "",
        });
      }}
    />
  );
  const manageAccounts = (
    <Button
      type="button"
      variant="neutral"
      onClick={() => onManageAuthAccounts?.("qoder_oauth")}
    >
      {t("qoder.manageAccounts")}
    </Button>
  );
  if (isAccountLogin) {
    return (
      <Form {...form}>
        <form
          id="provider-form"
          className="space-y-6"
          onSubmit={(event) => event.preventDefault()}
        >
          {presetSelector}
          {showAccountLogin && (
            <div className="space-y-3">
              <p className="text-body text-fg-2">
                {t("qoder.loginDescription")}
              </p>
              {manageAccounts}
            </div>
          )}
        </form>
      </Form>
    );
  }
  const defaultModelOptions = models.filter(
    (model, index) =>
      model.model.trim() &&
      models.findIndex((entry) => entry.model === model.model) === index,
  );
  return (
    <Form {...form}>
      <form
        id="provider-form"
        className="space-y-6"
        onSubmit={form.handleSubmit(async (identity) => {
          if (!ready || busy) return;
          setBusy(true);
          onSubmittingChange?.(true);
          setError("");
          try {
            const trimmed = identity.name.trim();
            await onSubmit({
              ...identity,
              name: trimmed,
              providerKey: isEdit ? providerId! : providerKey,
              meta: initialData?.meta,
              presetCategory: category,
              settingsConfig: JSON.stringify(
                isOfficial ? {} : finalize(config, trimmed),
              ),
            });
          } catch (cause) {
            setError(String(cause));
          } finally {
            setBusy(false);
            onSubmittingChange?.(false);
          }
        })}
      >
        {!isEdit && presetSelector}
        {error && (
          <p role="alert" className="text-sm text-destructive">
            {error}
          </p>
        )}
        <fieldset
          disabled={busy || Boolean(textError)}
          className="min-w-0 space-y-6 border-0 p-0 disabled:opacity-50"
        >
          <BasicFormFields
            form={form}
            beforeNameSlot={
              isOfficial ? undefined : (
                <div className="space-y-2">
                  <Label
                    htmlFor="qoder-provider-key"
                    className={REQUIRED_LABEL}
                  >
                    {t("opencode.providerKey")}
                  </Label>
                  <ImeSafeInput
                    id="qoder-provider-key"
                    value={providerKey}
                    disabled={isEdit}
                    normalize={normalizeKey}
                    onValueChange={setProviderKey}
                    placeholder={t("opencode.providerKeyPlaceholder")}
                  />
                  <p
                    className={
                      duplicate || (providerKey && !keyValid)
                        ? "text-xs text-destructive"
                        : "text-xs text-fg-2"
                    }
                  >
                    {duplicate
                      ? t("opencode.providerKeyDuplicate")
                      : isEdit
                        ? t("opencode.providerKeyLockedHint")
                        : t("qoder.invalidProviderId")}
                  </p>
                </div>
              )
            }
          />
          {isOfficial ? (
            <div className="space-y-3">
              <p className="text-sm text-fg-2">
                {t("qoder.officialCardManaged")}
              </p>
              {manageAccounts}
            </div>
          ) : (
            <>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <FormLabel htmlFor="qoder-protocol">
                    {t("opencode.npmPackage")}
                  </FormLabel>
                  <Select
                    value={protocol}
                    onValueChange={(value) =>
                      updateProvider({
                        protocol: value as Protocol,
                        authType: value === "anthropic" ? "api-key" : "bearer",
                      })
                    }
                  >
                    <SelectTrigger id="qoder-protocol">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {(Object.keys(PROTOCOL_LABELS) as Protocol[]).map(
                        (value) => (
                          <SelectItem key={value} value={value}>
                            {PROTOCOL_LABELS[value]}
                          </SelectItem>
                        ),
                      )}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <FormLabel htmlFor="qoder-auth-type">
                    {t("qoder.authType")}
                  </FormLabel>
                  <Select
                    value={config.authType ?? "bearer"}
                    onValueChange={(value) =>
                      updateProvider({ authType: value as AuthType })
                    }
                  >
                    <SelectTrigger id="qoder-auth-type">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {(Object.keys(AUTH_TYPE_LABELS) as AuthType[]).map(
                        (value) => (
                          <SelectItem key={value} value={value}>
                            {AUTH_TYPE_LABELS[value]}
                          </SelectItem>
                        ),
                      )}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-1">
                <ApiKeySection
                  id="qoder-api-key"
                  value={config.apiKey}
                  onChange={(value) => updateProvider({ apiKey: value })}
                  category={category}
                  shouldShowLink={Boolean(preset?.apiKeyUrl)}
                  websiteUrl={preset?.apiKeyUrl ?? ""}
                  isPartner={preset?.isPartner}
                  partnerPromotionKey={preset?.partnerPromotionKey}
                  required={false}
                />
                <p className="text-xs text-fg-2">{t("qoder.apiKeyHint")}</p>
              </div>
              <EndpointField
                id="qoder-base-url"
                label={t("opencode.baseUrl")}
                value={config.baseUrl}
                onChange={(value) => updateProvider({ baseUrl: value })}
                placeholder="https://api.example.com/v1"
              />
              <div className="space-y-3 border-l border-border pl-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-1">
                    <FormLabel>{t("opencode.models")}</FormLabel>
                    <HelpTip title={t("opencode.models")}>
                      {t("qoder.modelSelectionHint")}
                    </HelpTip>
                  </div>
                  <div className="flex gap-1">
                    <FetchedModelPicker
                      models={fetchedModels}
                      configuredModelIds={models.map((model) => model.model)}
                      onApply={handleApplyFetchedModels}
                      onFetch={handleFetchModels}
                      isFetching={isFetchingModels}
                      metadataSource={{
                        baseUrl,
                        presets: piPresetModelSources,
                      }}
                    />
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="h-7 gap-1"
                      onClick={() =>
                        updateProvider({ models: [...models, newModel()] })
                      }
                    >
                      <Plus className="h-3.5 w-3.5" />
                      {t("opencode.addModel")}
                    </Button>
                  </div>
                </div>
                {models.length === 0 ? (
                  <p className="py-2 text-sm text-fg-2">
                    {t("opencode.noModels")}
                  </p>
                ) : (
                  <div className="space-y-2">
                    <div className="mb-1 flex items-center gap-2 px-1 text-xs text-fg-2">
                      <span className="w-9" />
                      <span className={cn("flex-1", REQUIRED_LABEL)}>
                        {t("opencode.modelId")}
                      </span>
                      <span className="flex-1">{t("opencode.modelName")}</span>
                      <span className="w-9" />
                    </div>
                    {models.map((model, index) => (
                      <div key={index} className="space-y-2">
                        <div className="flex items-center gap-2">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => toggleExpanded(index)}
                            aria-label={t("opencode.toggleModelDetails")}
                            aria-expanded={expanded.has(index)}
                            className="h-9 w-9 shrink-0"
                          >
                            <ChevronRight
                              className={cn(
                                "h-4 w-4 transition-transform motion-reduce:transition-none",
                                expanded.has(index) && "rotate-90",
                              )}
                            />
                          </Button>
                          <div className="flex min-w-0 flex-1 gap-1">
                            <Input
                              id={`qoder-model-${index}`}
                              value={model.model}
                              onChange={(event) =>
                                updateModel(index, {
                                  model: event.target.value,
                                })
                              }
                              placeholder="model-id"
                              aria-label={t("opencode.modelId")}
                              className="min-w-0 flex-1"
                            />
                            {fetchedModels.length > 0 && (
                              <ModelDropdown
                                models={fetchedModels}
                                onSelect={(id) => {
                                  updateModel(index, { model: id });
                                  fillModelMetadataFor(index, id);
                                }}
                              />
                            )}
                          </div>
                          <Input
                            id={`qoder-model-name-${index}`}
                            value={model.displayName ?? ""}
                            onChange={(event) =>
                              updateModel(index, {
                                displayName: event.target.value || undefined,
                              })
                            }
                            placeholder={t("opencode.modelName")}
                            aria-label={t("opencode.modelName")}
                            className="min-w-0 flex-1"
                          />
                          <HoverTip content={t("common.delete")}>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              aria-label={t("common.delete")}
                              className="h-9 w-9 shrink-0 text-fg-2 hover:text-destructive"
                              onClick={() => {
                                updateProvider({
                                  models: models.filter(
                                    (_, position) => position !== index,
                                  ),
                                });
                                setExpanded(new Set());
                              }}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </HoverTip>
                        </div>
                        {expanded.has(index) && (
                          <div className="ml-9 grid gap-3 border-l-2 border-muted pl-4 sm:grid-cols-2">
                            <div className="flex min-h-9 flex-wrap items-center gap-x-8 gap-y-2 sm:col-span-2">
                              {(["tools", "vision"] as const).map((field) => (
                                <div
                                  key={field}
                                  className="flex items-center gap-2.5"
                                >
                                  <Label
                                    htmlFor={`qoder-model-${field}-${index}`}
                                    className="cursor-pointer"
                                  >
                                    {t(`qoder.${field}`)}
                                  </Label>
                                  <Switch
                                    id={`qoder-model-${field}-${index}`}
                                    checked={
                                      model.capabilities?.[field] ??
                                      field === "tools"
                                    }
                                    onCheckedChange={(checked) =>
                                      updateCapabilities(index, {
                                        [field]: checked,
                                      })
                                    }
                                  />
                                </div>
                              ))}
                              <div className="flex items-center gap-2.5">
                                <Label htmlFor={`qoder-thinking-${index}`}>
                                  {t("qoder.thinking")}
                                </Label>
                                <Select
                                  value={thinkingMode(model)}
                                  onValueChange={(value) => {
                                    const thinking =
                                      model.capabilities?.thinking;
                                    updateCapabilities(index, {
                                      thinking: {
                                        ...thinking,
                                        modes: value === "off" ? [] : [value],
                                        preferredMode:
                                          value === "off" ? undefined : value,
                                        requiresBudgetForEnabled:
                                          value === "enabled"
                                            ? true
                                            : undefined,
                                      },
                                    });
                                  }}
                                >
                                  <SelectTrigger
                                    id={`qoder-thinking-${index}`}
                                    className="w-36"
                                  >
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="off">
                                      {t("qoder.thinkingOff")}
                                    </SelectItem>
                                    <SelectItem value="enabled">
                                      {t("qoder.thinkingEnabled")}
                                    </SelectItem>
                                    <SelectItem value="adaptive">
                                      {t("qoder.thinkingAdaptive")}
                                    </SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </div>
                            {(
                              ["contextWindow", "maxOutputTokens"] as const
                            ).map((field) => (
                              <div key={field} className="space-y-2">
                                <Label htmlFor={`qoder-${field}-${index}`}>
                                  {t(`qoder.${field}`)}
                                </Label>
                                <Input
                                  id={`qoder-${field}-${index}`}
                                  type="number"
                                  min={1}
                                  step={1}
                                  value={model[field] ?? ""}
                                  onChange={(event) =>
                                    updateModel(index, {
                                      [field]:
                                        event.target.value === ""
                                          ? undefined
                                          : Number(event.target.value),
                                    })
                                  }
                                />
                                {field === "contextWindow" && (
                                  <GptContextWindowHint
                                    modelId={model.model}
                                    contextWindow={model.contextWindow}
                                  />
                                )}
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
                {defaultModelOptions.length > 1 && (
                  <div className="space-y-2">
                    <Label htmlFor="qoder-provider-default">
                      {t("qoder.providerDefaultModel")}
                    </Label>
                    <Select
                      value={
                        defaultModelOptions.some(
                          (model) => model.model === config.model,
                        )
                          ? config.model
                          : defaultModelOptions[0].model
                      }
                      onValueChange={(model) => updateProvider({ model })}
                    >
                      <SelectTrigger id="qoder-provider-default">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {defaultModelOptions.map((model) => (
                          <SelectItem key={model.model} value={model.model}>
                            {model.displayName || model.model}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-fg-2">
                      {t("qoder.providerDefaultModelHint")}
                    </p>
                  </div>
                )}
              </div>
            </>
          )}
        </fieldset>
        {!isOfficial && (
          <NativeConfigEditor
            appId="qoder"
            file="settings.json"
            id="qoder-settings-config"
            value={text}
            onChange={(next) => {
              setText(next);
              try {
                const parsed: unknown = JSON.parse(next);
                if (
                  !parsed ||
                  typeof parsed !== "object" ||
                  Array.isArray(parsed)
                ) {
                  setTextError(t("qoder.configJsonSchema"));
                  return;
                }
                setTextError(null);
                const parsedConfig = formConfig(parsed);
                configRef.current = parsedConfig;
                setConfig(parsedConfig);
              } catch (cause) {
                setTextError(
                  t("providerForm.nativeConfig.invalid", {
                    format: "JSON",
                    error: String(cause),
                  }),
                );
              }
            }}
            error={textError}
          />
        )}
        {showButtons && (
          <div className="flex justify-end gap-2">
            <Button
              type="button"
              variant="outline"
              disabled={busy}
              onClick={onCancel}
            >
              {t("common.cancel")}
            </Button>
            <Button type="submit" disabled={busy || !ready}>
              {submitLabel}
            </Button>
          </div>
        )}
      </form>
    </Form>
  );
}