Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

59.9 KB
Raw Blame
/**
 * source(目录加载/兜底/合并)与 registry(可见性/来源/路由解析)的纯逻辑测试。
 *
 * 2026-07-19 统一重构后:bundled 的 anthropic/openai/xd 是动态清单供应商(零静态模型),
 * registry / resolveRoute 的行为测试统一在「运行时注入后的目录」fixture 上进行
 * (与生产一致:active-catalog 把 SDK 发现 / codex 注册表 / 网关下发注入后再 buildRegistry)。
 */

import { describe, it, expect, vi } from "vitest";
import { modelRegistryCanonicalJson } from "../modelRegistryCanonical.js";

import { BUNDLED_CATALOG } from "../catalog.js";
import {
  loadCatalog,
  loadCatalogWithSource,
  resolveCatalogUrl,
  resolveFallbackCatalogUrl,
  mergeWithBundled,
  CATALOG_CFG_PATH,
  type CatalogIO,
} from "../source.js";
import {
  buildRegistry,
  providersForAgent,
  connectedProvidersForAgent,
  providerOffersModel,
  getModel,
  sourcesForModel,
  chatEligibleSourcesForModel,
  effectiveSourceIdForModel,
  resolveRoute,
} from "../registry.js";
import type { Catalog, CatalogModel, Provider } from "../types.js";

const MINIMAL: Catalog = {
  version: "test",
  providers: [
    {
      id: "anthropic",
      name: "Anthropic",
      source: "builtin",
      agents: ["claude-code"],
      auth: { method: "oauth" },
      routing: {
        "claude-code": {
          upstream: "https://api.anthropic.com",
          authStrategy: "oauth-passthrough",
        },
      },
      models: {
        "claude-code": [
          {
            id: "claude-opus-4-8",
            name: "Opus 4.8",
            contextWindow: 1_000_000,
            efforts: ["high"],
            defaultEffort: "high",
          },
        ],
      },
    },
  ],
};

function model(id: string, extra: Partial<CatalogModel> = {}): CatalogModel {
  return {
    id,
    name: id,
    contextWindow: 200_000,
    efforts: [],
    defaultEffort: null,
    ...extra,
  };
}

/** 模拟生产形态:动态清单注入后的目录(active-catalog 合并结果的等价物)。 */
function runtimeCatalog(): Catalog {
  const clone = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
  for (const p of clone.providers) {
    if (p.id === "anthropic") {
      const models = [
        model("claude-opus-4-8", {
          name: "Opus 4.8",
          contextWindow: 1_000_000,
        }),
      ];
      p.models["claude-code"] = models;
      p.models.codex = models;
    }
    if (p.id === "openai") {
      p.models.codex = [model("gpt-5.5", { name: "GPT-5.5" })];
      p.models["claude-code"] = [model("chatgpt/gpt-5.5", { name: "GPT-5.5" })];
    }
    if (p.id === "xd") {
      p.models["claude-code"] = [
        model("claude-opus-4-8", {
          name: "Opus 4.8",
          contextWindow: 1_000_000,
        }),
        model("gpt-5.5", { name: "GPT-5.5" }),
      ];
      p.models.codex = [model("gpt-5.5", { name: "GPT-5.5" })];
    }
  }
  return clone;
}

describe("resolveCatalogUrl", () => {
  it("opts explicit catalog endpoints into media without changing unrelated query parameters", () => {
    const resolved = new URL(
      resolveCatalogUrl({
        url: "https://example.com/api/model-catalog/catalog?region=cn&registryMedia=0&registrySchemaVersion=4",
      })!,
    );
    expect(Object.fromEntries(resolved.searchParams)).toEqual({
      region: "cn",
      registryMedia: "1",
      registryLocalRuntimes: "1",
      registrySchemaVersion: "6",
    });
  });

  it("scopes LKG reads and writes to the media-capable URL", async () => {
    const cfg = { baseUrl: "https://model-access.example.com" };
    const readCache = vi.fn().mockResolvedValue(null);
    const writeCache = vi.fn();
    await loadCatalog(cfg, {
      fetchText: vi.fn().mockResolvedValue(JSON.stringify({ ...MINIMAL, modelRegistry: BUNDLED_CATALOG.modelRegistry })),
      readCache,
      writeCache,
    });
    expect(readCache).toHaveBeenCalledWith(resolveCatalogUrl(cfg));
    expect(writeCache).toHaveBeenCalledWith(
      resolveCatalogUrl(cfg),
      expect.any(String),
    );
    expect(readCache).not.toHaveBeenCalledWith(
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6",
    );
  });
  it("prefers explicit url", () => {
    expect(
      resolveCatalogUrl({ url: "https://x/y.json", baseUrl: "https://b" }),
    ).toBe("https://x/y.json");
  });
  it("builds from baseUrl + public catalog API path", () => {
    expect(
      resolveCatalogUrl({ baseUrl: "https://model-access.example.com/" }),
    ).toBe(
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6&registryMedia=1&registryLocalRuntimes=1",
    );
  });
  it("builds the migration OSS fallback URL", () => {
    expect(
      resolveFallbackCatalogUrl({
        fallbackBaseUrl: "https://cdn.example.com/base/",
      }),
    ).toBe(`https://cdn.example.com/base${CATALOG_CFG_PATH}`);
  });
  it("returns null when neither given", () => {
    expect(resolveCatalogUrl({})).toBeNull();
  });
});

describe("mergeWithBundled", () => {
  it("keeps primary providers and fills missing bundled ones by id", () => {
    const merged = mergeWithBundled(MINIMAL);
    const ids = merged.providers.map((p) => p.id);
    expect(ids).toContain("anthropic");
    expect(ids).toContain("openai");
    expect(ids).toContain("xd");
    // primary's anthropic wins (only 1 cc model in MINIMAL)
    expect(
      merged.providers.find((p) => p.id === "anthropic")!.models["claude-code"]!
        .length,
    ).toBe(1);
  });

  it("keeps a newer bundled Registry without replacing the independent xAI fallback provider", () => {
    const bundledRegistry = BUNDLED_CATALOG.modelRegistry;
    const bundledXai = BUNDLED_CATALOG.providers.find(
      (provider) => provider.id === "xai",
    );
    if (!bundledRegistry) throw new Error("missing bundled modelRegistry");
    if (!bundledXai) throw new Error("missing bundled xAI provider");
    const staleRegistry = {
      ...bundledRegistry,
      updatedAt: "2026-01-01T00:00:00.000Z",
      models: [bundledRegistry.models[0]!],
    };
    const staleXai = { ...bundledXai, name: "STALE-XAI" };

    const merged = mergeWithBundled({
      ...MINIMAL,
      providers: [...MINIMAL.providers, staleXai],
      modelRegistry: staleRegistry,
    });

    expect(merged.modelRegistry).toBe(bundledRegistry);
    expect(merged.modelRegistry?.models.length).toBeGreaterThan(
      staleRegistry.models.length,
    );
    expect(
      merged.providers.find((provider) => provider.id === "xai")?.name,
    ).toBe("STALE-XAI");
  });

  it("uses a newer primary modelRegistry as one complete snapshot, including retirements", () => {
    const bundledRegistry = BUNDLED_CATALOG.modelRegistry;
    const bundledXai = BUNDLED_CATALOG.providers.find(
      (provider) => provider.id === "xai",
    );
    if (!bundledRegistry) throw new Error("missing bundled modelRegistry");
    if (!bundledXai) throw new Error("missing bundled xAI provider");
    const newerRegistry = {
      ...bundledRegistry,
      updatedAt: "2099-01-01T00:00:00.000Z",
      models: [{ ...bundledRegistry.models[0]!, status: "retired" as const }],
    };
    const newerXai = { ...bundledXai, name: "NEWER-XAI" };

    const merged = mergeWithBundled({
      ...MINIMAL,
      providers: [...MINIMAL.providers, newerXai],
      modelRegistry: newerRegistry,
    });

    expect(merged.modelRegistry).toBe(newerRegistry);
    expect(merged.modelRegistry?.models).toHaveLength(1);
    expect(merged.modelRegistry?.models[0]?.status).toBe("retired");
    const mergedXai = merged.providers.find(
      (provider) => provider.id === "xai",
    );
    expect(mergedXai).toMatchObject({
      ...newerXai,
      agents: expect.arrayContaining(["claude-code", "codex", "pi"]),
      routing: expect.objectContaining({ pi: bundledXai.routing.pi }),
      models: expect.objectContaining({ pi: bundledXai.models.pi }),
    });
  });

  it("orders result by bundled provider order (v2 远端只带 xai 时不得窜位)", () => {
    const v2Remote: Catalog = {
      version: "2",
      providers: [
        JSON.parse(
          JSON.stringify(BUNDLED_CATALOG.providers.find((p) => p.id === "xai")),
        ),
      ],
    };
    const merged = mergeWithBundled(v2Remote);
    expect(merged.providers.map((p) => p.id)).toEqual([
      "anthropic",
      "openai",
      "xai",
      "xd",
      "gemini",
    ]);
    // 远端独有的新供应商追加在 bundled 之后。
    const withExtra: Catalog = {
      version: "2",
      providers: [
        ...v2Remote.providers,
        { ...MINIMAL.providers[0], id: "newvendor", name: "NewVendor" },
      ],
    };
    expect(mergeWithBundled(withExtra).providers.map((p) => p.id)).toEqual([
      "anthropic",
      "openai",
      "xai",
      "xd",
      "gemini",
      "newvendor",
    ]);
  });

  it("backfills the bundled SuperGrok Pi runtime when a legacy v2 xAI block masks it", () => {
    const bundledXai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
    );
    const legacyXai = structuredClone(bundledXai);
    legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
    delete legacyXai.routing.pi;
    delete legacyXai.models.pi;

    const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
    const xai = merged.providers.find((provider) => provider.id === "xai");

    expect(xai?.agents).toContain("pi");
    expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
    expect(xai?.models.pi).toEqual(bundledXai.models.pi);
  });

  it("does not invent a SuperGrok Pi runtime for current or differently routed xAI providers", () => {
    const bundledXai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
    );
    const withoutPi = structuredClone(bundledXai);
    withoutPi.agents = withoutPi.agents.filter((agent) => agent !== "pi");
    delete withoutPi.routing.pi;
    delete withoutPi.models.pi;

    const current = mergeWithBundled({
      version: BUNDLED_CATALOG.version,
      providers: [withoutPi],
    }).providers.find((provider) => provider.id === "xai");
    expect(current?.agents).not.toContain("pi");
    expect(current?.routing.pi).toBeUndefined();
    expect(current?.models.pi).toBeUndefined();

    const rerouted = mergeWithBundled({
      version: "2",
      providers: [
        {
          ...withoutPi,
          routing: {
            ...withoutPi.routing,
            codex: {
              ...withoutPi.routing.codex!,
              upstream: "https://different.example.test/v1",
            },
          },
        },
      ],
    }).providers.find((provider) => provider.id === "xai");
    expect(rerouted?.agents).not.toContain("pi");
    expect(rerouted?.routing.pi).toBeUndefined();
    expect(rerouted?.models.pi).toBeUndefined();
  });

  it.each([
    { label: "api access", access: { kind: "api" } as const },
    { label: "managed access", access: { kind: "managed" } as const },
    {
      label: "different subscription",
      access: { kind: "subscription", product: "OtherGrok" } as const,
    },
  ])("does not backfill SuperGrok Pi for explicit $label", ({ access }) => {
    const bundledXai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
    );
    const legacyXai = structuredClone(bundledXai);
    legacyXai.access = access;
    legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
    delete legacyXai.routing.pi;
    delete legacyXai.models.pi;

    const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
    const xai = merged.providers.find((provider) => provider.id === "xai");

    expect(xai?.access).toEqual(access);
    expect(xai?.agents).not.toContain("pi");
    expect(xai?.routing.pi).toBeUndefined();
    expect(xai?.models.pi).toBeUndefined();
  });

  it("keeps the SuperGrok Pi backfill when an old catalog explicitly repeats the same access", () => {
    const bundledXai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
    );
    const legacyXai = structuredClone(bundledXai);
    legacyXai.access = { kind: "subscription", product: "SuperGrok" };
    legacyXai.agents = legacyXai.agents.filter((agent) => agent !== "pi");
    delete legacyXai.routing.pi;
    delete legacyXai.models.pi;

    const merged = mergeWithBundled({ version: "2", providers: [legacyXai] });
    const xai = merged.providers.find((provider) => provider.id === "xai");

    expect(xai?.agents).toContain("pi");
    expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
    expect(xai?.models.pi).toEqual(bundledXai.models.pi);
  });

  it("backfills access for an old primary catalog without mutating it", () => {
    const merged = mergeWithBundled(MINIMAL);
    expect(MINIMAL.providers[0].access).toBeUndefined();
    expect(merged.providers.find((p) => p.id === "anthropic")?.access).toEqual({
      kind: "subscription",
      product: "Claude.ai",
    });
  });

  it("preserves access explicitly supplied by the primary catalog", () => {
    const primary: Catalog = {
      ...MINIMAL,
      providers: MINIMAL.providers.map((p) => ({
        ...p,
        access: { kind: "api" },
      })),
    };
    expect(
      mergeWithBundled(primary).providers.find((p) => p.id === "anthropic")
        ?.access,
    ).toEqual({ kind: "api" });
  });

  it("同 updatedAt 异 Registry 内容在首次启动合并时保留 bundled 不可变快照", () => {
    const bundledRegistry = structuredClone(BUNDLED_CATALOG.modelRegistry!);
    const mutatedRegistry = structuredClone(bundledRegistry);
    mutatedRegistry.models[0] = {
      ...mutatedRegistry.models[0]!,
      name: "Mutated in place",
    };
    const primary: Catalog = { ...MINIMAL, modelRegistry: mutatedRegistry };

    const merged = mergeWithBundled(primary);
    expect(modelRegistryCanonicalJson(merged.modelRegistry!)).toBe(
      modelRegistryCanonicalJson(bundledRegistry),
    );
  });

  it("首次启动合并把等价时区表示视为同一 Registry revision", () => {
    const bundledRegistry = structuredClone(BUNDLED_CATALOG.modelRegistry!);
    const shifted = new Date(
      Date.parse(bundledRegistry.updatedAt) + 8 * 60 * 60 * 1_000,
    )
      .toISOString()
      .replace("Z", "+08:00");
    const remoteXai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!,
    );
    remoteXai.name = "REMOTE-XAI";
    const primary: Catalog = {
      ...MINIMAL,
      providers: [...MINIMAL.providers, remoteXai],
      modelRegistry: { ...bundledRegistry, updatedAt: shifted },
    };

    const merged = mergeWithBundled(primary);
    expect(merged.modelRegistry?.updatedAt).toBe(shifted);
    expect(
      merged.providers.find((provider) => provider.id === "xai")?.name,
    ).toBe("REMOTE-XAI");
  });

  it("旧远端未声明 xAI 媒体能力时继承 bundled;显式空清单仍可停用", () => {
    const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
    const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
    delete oldRemoteXai.imageModels;
    delete oldRemoteXai.videoModels;
    const inherited = mergeWithBundled({
      version: "2",
      providers: [oldRemoteXai],
    });
    expect(
      inherited.providers.find((p) => p.id === "xai")?.imageModels,
    ).toEqual(bundledXai.imageModels);
    expect(
      inherited.providers.find((p) => p.id === "xai")?.videoModels,
    ).toEqual(bundledXai.videoModels);

    const explicitlyDisabled = mergeWithBundled({
      version: "2",
      providers: [{ ...oldRemoteXai, imageModels: [], videoModels: [] }],
    });
    expect(
      explicitlyDisabled.providers.find((p) => p.id === "xai")?.imageModels,
    ).toEqual([]);
    expect(
      explicitlyDisabled.providers.find((p) => p.id === "xai")?.videoModels,
    ).toEqual([]);
  });

  it("旧远端未声明向量清单时继承 bundled;显式空清单仍是停用语义", () => {
    // 与 xai 图像清单同一个道理(PR #1707 review):向量清单是客户端新增的 bundled
    // 元数据,远端 / 本地目录里同 id 的 xd 可能还是升级前的结构。primary 整体优先
    // 会让旧结构把新字段整段遮掉 → 目录派生空清单 → 设置页"无可用模型"、所有
    // embed_text 直接 NO_CANDIDATE,能力等于没上线。
    const bundledXd = BUNDLED_CATALOG.providers.find((p) => p.id === "xd")!;
    const oldRemoteXd = JSON.parse(JSON.stringify(bundledXd)) as Provider;
    delete oldRemoteXd.embeddingModels;
    delete oldRemoteXd.embeddingDefaults;
    const inherited = mergeWithBundled({
      version: "2",
      providers: [oldRemoteXd],
    });
    const inheritedXd = inherited.providers.find((p) => p.id === "xd");
    expect(inheritedXd?.embeddingModels).toEqual(bundledXd.embeddingModels);
    expect(inheritedXd?.embeddingDefaults).toEqual(bundledXd.embeddingDefaults);

    // 显式 `[]` = "这个供应商不提供向量",不能被 bundled 顶回来。
    const explicitlyDisabled = mergeWithBundled({
      version: "2",
      providers: [{ ...oldRemoteXd, embeddingModels: [] }],
    });
    expect(
      explicitlyDisabled.providers.find((p) => p.id === "xd")?.embeddingModels,
    ).toEqual([]);
  });

  it("旧远端改变鉴权或路由形状时不继承 bundled 图像能力", () => {
    const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
    const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
    delete oldRemoteXai.imageModels;
    delete oldRemoteXai.videoModels;

    const apiKeyXai: Provider = {
      ...oldRemoteXai,
      auth: { method: "apiKey" },
    };
    const alternateRouteXai: Provider = {
      ...oldRemoteXai,
      routing: {
        ...oldRemoteXai.routing,
        codex: {
          ...oldRemoteXai.routing.codex!,
          upstream: "https://oauth-proxy.example.test",
        },
      },
    };

    expect(
      mergeWithBundled({ version: "2", providers: [apiKeyXai] }).providers.find(
        (p) => p.id === "xai",
      )?.imageModels,
    ).toBeUndefined();
    expect(
      mergeWithBundled({ version: "2", providers: [apiKeyXai] }).providers.find(
        (p) => p.id === "xai",
      )?.videoModels,
    ).toBeUndefined();
    expect(
      mergeWithBundled({
        version: "2",
        providers: [alternateRouteXai],
      }).providers.find((p) => p.id === "xai")?.imageModels,
    ).toBeUndefined();
    expect(
      mergeWithBundled({
        version: "2",
        providers: [alternateRouteXai],
      }).providers.find((p) => p.id === "xai")?.videoModels,
    ).toBeUndefined();
  });

  it("旧 xAI 条目仅在 access 缺省或仍为同一订阅时继承 bundled 图像能力", () => {
    const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === "xai")!;
    const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
    delete oldRemoteXai.imageModels;
    delete oldRemoteXai.videoModels;

    for (const access of [
      { kind: "api" as const },
      { kind: "managed" as const },
      { kind: "subscription" as const, product: "Another subscription" },
    ]) {
      expect(
        mergeWithBundled({
          version: "2",
          providers: [{ ...oldRemoteXai, access }],
        }).providers.find((p) => p.id === "xai")?.imageModels,
      ).toBeUndefined();
      expect(
        mergeWithBundled({
          version: "2",
          providers: [{ ...oldRemoteXai, access }],
        }).providers.find((p) => p.id === "xai")?.videoModels,
      ).toBeUndefined();
    }

    expect(
      mergeWithBundled({
        version: "2",
        providers: [{ ...oldRemoteXai, access: bundledXai.access }],
      }).providers.find((p) => p.id === "xai")?.imageModels,
    ).toEqual(bundledXai.imageModels);
    expect(
      mergeWithBundled({
        version: "2",
        providers: [{ ...oldRemoteXai, access: bundledXai.access }],
      }).providers.find((p) => p.id === "xai")?.videoModels,
    ).toEqual(bundledXai.videoModels);
  });

  it("非 xAI 远端条目缺少媒体字段时不从 bundled 恢复已撤下能力", () => {
    const bundledOpenai = BUNDLED_CATALOG.providers.find(
      (p) => p.id === "openai",
    )!;
    const remoteOpenai = JSON.parse(JSON.stringify(bundledOpenai)) as Provider;
    delete remoteOpenai.imageModels;

    expect(
      mergeWithBundled({
        version: "2",
        providers: [remoteOpenai],
      }).providers.find((p) => p.id === "openai")?.imageModels,
    ).toBeUndefined();
  });

  it("旧目录在官方 Codex 路由未声明 custom tool 能力时继承 bundled 能力", () => {
    const oldProviders = BUNDLED_CATALOG.providers.map((provider) => {
      const oldProvider = structuredClone(provider);
      if (oldProvider.routing.codex) {
        delete oldProvider.routing.codex.supportsResponsesCustomTools;
      }
      return oldProvider;
    });

    const merged = mergeWithBundled({ version: "2", providers: oldProviders });

    expect(
      merged.providers.find((provider) => provider.id === "openai")?.routing
        .codex?.supportsResponsesCustomTools,
    ).toBe(true);
    expect(
      merged.providers.find((provider) => provider.id === "xai")?.routing.codex
        ?.supportsResponsesCustomTools,
    ).toBe(false);
    expect(
      merged.providers.find((provider) => provider.id === "xd")?.routing.codex
        ?.supportsResponsesCustomTools,
    ).toBe(false);

    const explicitOpenai = structuredClone(
      oldProviders.find((provider) => provider.id === "openai")!,
    );
    explicitOpenai.routing.codex!.supportsResponsesCustomTools = false;
    expect(
      mergeWithBundled({
        version: "2",
        providers: [explicitOpenai],
      }).providers.find((provider) => provider.id === "openai")?.routing.codex
        ?.supportsResponsesCustomTools,
    ).toBe(false);
  });

  it("不为改变鉴权或 upstream 的同名 Provider 猜测 custom tool 能力", () => {
    const bundledOpenai = structuredClone(
      BUNDLED_CATALOG.providers.find((provider) => provider.id === "openai")!,
    );
    delete bundledOpenai.routing.codex!.supportsResponsesCustomTools;
    const apiKeyOpenai: Provider = {
      ...bundledOpenai,
      auth: { method: "apiKey" },
    };
    const reroutedOpenai: Provider = {
      ...bundledOpenai,
      routing: {
        ...bundledOpenai.routing,
        codex: {
          ...bundledOpenai.routing.codex!,
          upstream: "https://responses.example.test/v1",
        },
      },
    };

    expect(
      mergeWithBundled({
        version: "2",
        providers: [apiKeyOpenai],
      }).providers.find((provider) => provider.id === "openai")?.routing.codex
        ?.supportsResponsesCustomTools,
    ).toBeUndefined();
    expect(
      mergeWithBundled({
        version: "2",
        providers: [reroutedOpenai],
      }).providers.find((provider) => provider.id === "openai")?.routing.codex
        ?.supportsResponsesCustomTools,
    ).toBeUndefined();
  });

  it("does not infer bundled billing when a same-id primary changes auth or upstream", () => {
    const apiKeyPrimary: Catalog = {
      ...MINIMAL,
      providers: MINIMAL.providers.map((p) => ({
        ...p,
        auth: { method: "apiKey" as const },
        routing: {
          "claude-code": {
            ...p.routing["claude-code"]!,
            authStrategy: "api-key-header" as const,
          },
        },
      })),
    };
    const alternateOAuthPrimary: Catalog = {
      ...MINIMAL,
      providers: MINIMAL.providers.map((p) => ({
        ...p,
        routing: {
          "claude-code": {
            ...p.routing["claude-code"]!,
            upstream: "https://oauth-proxy.example.test",
          },
        },
      })),
    };

    const apiKeyMerged = mergeWithBundled(apiKeyPrimary).providers.find(
      (p) => p.id === "anthropic",
    );
    const altMerged = mergeWithBundled(alternateOAuthPrimary).providers.find(
      (p) => p.id === "anthropic",
    );
    expect(apiKeyMerged?.access).toBeUndefined();
    expect(altMerged?.access).toBeUndefined();
  });
});

describe("loadCatalog", () => {
  it("reports whether local, remote, or bundled supplied the snapshot", async () => {
    const local = await loadCatalogWithSource(
      { localPath: "/repo/providers.json" },
      { readFile: vi.fn(async () => JSON.stringify(MINIMAL)) },
    );
    const remote = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      { fetchText: vi.fn(async () => JSON.stringify(MINIMAL)) },
    );
    const bundled = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      {
        fetchText: vi.fn(async () => {
          throw new Error("network down");
        }),
      },
    );

    expect(local).toMatchObject({
      source: "local",
      capabilityEvidence: "current",
      unverifiedXdMediaKinds: ["image", "video", "embedding"],
      catalog: { version: "test" },
      authorityCatalog: { version: "test" },
    });
    expect(remote).toMatchObject({
      source: "remote",
      capabilityEvidence: "current",
      unverifiedXdMediaKinds: ["image", "video", "embedding"],
      catalog: { version: "test" },
      authorityCatalog: { version: "test" },
    });
    expect(bundled).toEqual({
      source: "bundled",
      capabilityEvidence: "fallback",
      unverifiedXdMediaKinds: ["image", "video", "embedding"],
      catalog: BUNDLED_CATALOG,
      authorityCatalog: null,
    });
  });

  it("tracks only XD media fields inherited from bundled in a current snapshot", async () => {
    const bundledXd = BUNDLED_CATALOG.providers.find(
      (provider) => provider.id === "xd",
    );
    if (!bundledXd) throw new Error("missing bundled XD provider");
    const oldXd = structuredClone(bundledXd);
    delete oldXd.embeddingModels;
    delete oldXd.embeddingDefaults;

    const inherited = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      {
        fetchText: vi.fn(async () =>
          JSON.stringify({ version: "2", providers: [oldXd] }),
        ),
      },
    );
    expect(inherited.capabilityEvidence).toBe("current");
    expect(inherited.unverifiedXdMediaKinds).toEqual(["embedding"]);
    expect(
      inherited.catalog.providers.find((provider) => provider.id === "xd")
        ?.embeddingModels,
    ).toEqual(bundledXd.embeddingModels);

    const explicitlyDisabled = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      {
        fetchText: vi.fn(async () =>
          JSON.stringify({
            version: "2",
            providers: [{ ...oldXd, embeddingModels: [] }],
          }),
        ),
      },
    );
    expect(explicitlyDisabled.unverifiedXdMediaKinds).toEqual([]);
    expect(
      explicitlyDisabled.catalog.providers.find(
        (provider) => provider.id === "xd",
      )?.embeddingModels,
    ).toEqual([]);
  });

  it("only backfills Pi metadata for proven legacy snapshots across local, remote, and cache", async () => {
    const bundledPreset = BUNDLED_CATALOG.presets?.find(
      (preset) => preset.id === "deepseek",
    );
    if (!bundledPreset) throw new Error("missing bundled DeepSeek preset");
    const { pi: _missing, ...legacyRuntimes } = bundledPreset.runtimes;
    const legacy = JSON.stringify({
      version: "2",
      providers: MINIMAL.providers,
      presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],
    });
    const current = JSON.stringify({
      version: BUNDLED_CATALOG.version,
      providers: MINIMAL.providers,
      presets: [{ ...bundledPreset, runtimes: legacyRuntimes }],
    });
    const local = await loadCatalogWithSource(
      { localPath: "/repo/providers.json" },
      { readFile: vi.fn(async () => legacy) },
    );
    const remote = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      { fetchText: vi.fn(async () => legacy) },
    );
    const cache = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json", remoteBudgetMs: 0 },
      { readCache: vi.fn(async () => legacy) },
    );
    for (const loaded of [local, remote, cache]) {
      expect(
        loaded.catalog.presets?.find((preset) => preset.id === "deepseek")
          ?.runtimes.pi,
      ).toEqual(bundledPreset.runtimes.pi);
      expect(
        loaded.authorityCatalog?.presets?.find(
          (preset) => preset.id === "deepseek",
        )?.runtimes.pi,
      ).toBeUndefined();
    }

    const currentLoaded = await loadCatalogWithSource(
      { url: "https://catalog.example.test/providers.json" },
      { fetchText: vi.fn(async () => current) },
    );
    expect(
      currentLoaded.catalog.presets?.find((preset) => preset.id === "deepseek")
        ?.runtimes.pi,
    ).toBeUndefined();
  });

  it("persists a valid remote snapshot and uses its source-scoped LKG after failure", async () => {
    const url = "https://catalog.example.test/providers.json";
    const writeCache = vi.fn(
      async (_scope: string, _text: string) => undefined,
    );
    const remote = await loadCatalogWithSource(
      { url },
      {
        fetchText: vi.fn(async () => JSON.stringify(MINIMAL)),
        writeCache,
      },
    );
    expect(remote.source).toBe("remote");
    expect(writeCache).toHaveBeenCalledWith(url, JSON.stringify(MINIMAL));

    const cached = await loadCatalogWithSource(
      { url },
      {
        fetchText: vi.fn(async () => {
          throw new Error("offline");
        }),
        readCache: vi.fn(async (scope) =>
          scope === url ? JSON.stringify(MINIMAL) : null,
        ),
      },
    );
    expect(cached).toMatchObject({
      source: "cache",
      catalog: { version: "test" },
    });
    expect(cached.capabilityEvidence).toBe("fallback");
  });

  it("keeps a newer cached modelRegistry when a valid remote Catalog is stale", async () => {
    const url = "https://catalog.example.test/providers.json";
    const newerUpdatedAt = "2099-08-02T00:00:00.000Z";
    const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
    const xai = BUNDLED_CATALOG.providers.find(
      (provider) => provider.id === "xai",
    );
    if (!xai) throw new Error("missing bundled xAI provider");
    const older: Catalog = {
      ...MINIMAL,
      providers: [...MINIMAL.providers, { ...xai, name: "STALE-XAI" }],
      modelRegistry: {
        ...registry,
        updatedAt: "2026-07-30T00:00:00.000Z",
        models: registry.models.map((entry: { id: string }) =>
          entry.id === "openai/gpt-5.6-sol"
            ? { ...entry, name: "STALE" }
            : entry,
        ),
      },
    };
    const newer: Catalog = {
      ...MINIMAL,
      providers: [...MINIMAL.providers, { ...xai, name: "NEWER-LKG-XAI" }],
      modelRegistry: {
        ...registry,
        updatedAt: newerUpdatedAt,
        models: registry.models.map((entry: { id: string }) =>
          entry.id === "openai/gpt-5.6-sol"
            ? { ...entry, name: "NEWER-LKG" }
            : entry,
        ),
      },
    };
    const writeCache = vi.fn(
      async (_scope: string, _text: string) => undefined,
    );

    const loaded = await loadCatalogWithSource(
      { url },
      {
        fetchText: vi.fn(async () => JSON.stringify(older)),
        readCache: vi.fn(async () => JSON.stringify(newer)),
        writeCache,
      },
    );

    expect(loaded.source).toBe("remote");
    expect(loaded.capabilityEvidence).toBe("fallback");
    expect(loaded.catalog.providers[0]?.name).toBe(MINIMAL.providers[0]?.name);
    expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
    expect(
      loaded.catalog.modelRegistry?.models.find(
        (entry) => entry.id === "openai/gpt-5.6-sol",
      )?.name,
    ).toBe("NEWER-LKG");
    expect(
      loaded.catalog.providers.find((provider) => provider.id === "xai")?.name,
    ).toBe("NEWER-LKG-XAI");
    const persisted = JSON.parse(writeCache.mock.calls[0]![1]);
    expect(persisted.modelRegistry.updatedAt).toBe(newerUpdatedAt);
    expect(
      persisted.providers.find((provider: Provider) => provider.id === "xai")
        ?.name,
    ).toBe("NEWER-LKG-XAI");
  });

  it("rejects a remote registry that republishes the same updatedAt with different content (keeps LKG)", async () => {
    const url = "https://catalog.example.test/providers.json";
    const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
    const updatedAt = "2026-08-01T00:00:00.000Z";
    const cached: Catalog = {
      ...MINIMAL,
      modelRegistry: { ...registry, updatedAt },
    };
    // 同 updatedAt、内容被悄悄改写 = 非法重发(纠错必须 forward-fix 抬 updatedAt)。
    const mutatedRemote: Catalog = {
      ...MINIMAL,
      modelRegistry: {
        ...registry,
        updatedAt,
        models: registry.models.slice(1),
      },
    };
    const warns: string[] = [];

    const loaded = await loadCatalogWithSource(
      { url },
      {
        fetchText: vi.fn(async () => JSON.stringify(mutatedRemote)),
        readCache: vi.fn(async () => JSON.stringify(cached)),
        writeCache: vi.fn(async () => undefined),
        log: (level, msg) => {
          if (level === "warn") warns.push(msg);
        },
      },
    );

    expect(loaded.source).toBe("remote");
    expect(loaded.capabilityEvidence).toBe("fallback");
    expect(loaded.catalog.modelRegistry?.models).toHaveLength(
      registry.models.length,
    );
    expect(
      warns.some((msg) => msg.includes("republished the same updatedAt")),
    ).toBe(true);
  });

  it("adopts the newer snapshot returned by a serialized LKG commit", async () => {
    const url = "https://catalog.example.test/providers.json";
    const newerUpdatedAt = "2099-08-01T00:00:00.000Z";
    const registry = JSON.parse(JSON.stringify(BUNDLED_CATALOG.modelRegistry));
    const newer: Catalog = {
      ...MINIMAL,
      modelRegistry: {
        ...registry,
        updatedAt: newerUpdatedAt,
      },
    };
    const older: Catalog = {
      ...MINIMAL,
      modelRegistry: {
        ...registry,
        updatedAt: "2026-07-30T00:00:00.000Z",
      },
    };

    const loaded = await loadCatalogWithSource(
      { url },
      {
        fetchText: vi.fn(async () => JSON.stringify(older)),
        writeCache: vi.fn(async () => JSON.stringify(newer)),
      },
    );

    expect(loaded.source).toBe("remote");
    expect(loaded.capabilityEvidence).toBe("fallback");
    expect(loaded.catalog.modelRegistry?.updatedAt).toBe(newerUpdatedAt);
  });

  it("reads LKG even when the startup network budget is zero and rejects bad cache", async () => {
    const url = "https://catalog.example.test/providers.json";
    const fetchText = vi.fn();
    const cached = await loadCatalogWithSource(
      { url, remoteBudgetMs: 0 },
      {
        fetchText,
        readCache: vi.fn(async () => JSON.stringify(MINIMAL)),
      },
    );
    expect(fetchText).not.toHaveBeenCalled();
    expect(cached.source).toBe("cache");

    const invalid = await loadCatalogWithSource(
      { url, remoteBudgetMs: 0 },
      {
        fetchText,
        readCache: vi.fn(async () => '{"version":"bad","providers":[]}'),
      },
    );
    expect(invalid).toEqual({
      source: "bundled",
      capabilityEvidence: "fallback",
      unverifiedXdMediaKinds: ["image", "video", "embedding"],
      catalog: BUNDLED_CATALOG,
      authorityCatalog: null,
    });
  });

  it("dev: reads local path, skips network", async () => {
    const fetchText = vi.fn();
    const io: CatalogIO = {
      readFile: vi.fn(async () => JSON.stringify(MINIMAL)),
      fetchText,
    };
    const cat = await loadCatalog({ localPath: "/repo/providers.json" }, io);
    expect(io.readFile).toHaveBeenCalledWith("/repo/providers.json");
    expect(fetchText).not.toHaveBeenCalled();
    expect(cat.providers.find((p) => p.id === "anthropic")).toBeTruthy();
  });

  it("falls back from public API to legacy OSS before bundled", async () => {
    const writeCache = vi.fn(
      async (_scope: string, _text: string) => undefined,
    );
    const fetchText = vi
      .fn()
      .mockRejectedValueOnce(new Error("api unavailable"))
      .mockResolvedValueOnce(
        JSON.stringify({
          ...MINIMAL,
          cindyModelMeta: {
            version: 1,
            models: { retired: { contextWindow: 1 } },
          },
        }),
      );
    const cat = await loadCatalog(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText, writeCache },
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      1,
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6&registryMedia=1&registryLocalRuntimes=1",
      15_000,
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      2,
      "https://cdn.example.com/cindy/cfg/providers.json",
      expect.any(Number),
    );
    expect(cat.version).toBe("test");
    expect(cat).not.toHaveProperty("cindyModelMeta");
    expect(writeCache).toHaveBeenCalledWith(
      "https://cdn.example.com/cindy/cfg/providers.json",
      expect.any(String),
    );
    expect(JSON.parse(writeCache.mock.calls[0]![1])).not.toHaveProperty(
      "cindyModelMeta",
    );
  });

  it("marks legacy OSS as fallback evidence even when its HTTP request succeeds", async () => {
    const fetchText = vi
      .fn()
      .mockRejectedValueOnce(new Error("api unavailable"))
      .mockResolvedValueOnce(JSON.stringify(MINIMAL));
    const result = await loadCatalogWithSource(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText },
    );

    expect(result).toMatchObject({
      source: "remote",
      capabilityEvidence: "fallback",
      catalog: { version: "test" },
      authorityCatalog: null,
    });
  });
  it("falls back from invalid public API payload to legacy OSS before bundled", async () => {
    const fetchText = vi
      .fn()
      .mockResolvedValueOnce(
        JSON.stringify({
          ...MINIMAL,
          cindyModelMeta: { version: 1, models: {} },
        }),
      )
      .mockResolvedValueOnce(JSON.stringify(MINIMAL));
    const cat = await loadCatalog(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText },
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      1,
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6&registryMedia=1&registryLocalRuntimes=1",
      15_000,
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      2,
      "https://cdn.example.com/cindy/cfg/providers.json",
      expect.any(Number),
    );
    expect(cat.version).toBe("test");
  });

  it("loads a legacy OSS LKG after removing its retired metadata block", async () => {
    const legacyUrl = "https://cdn.example.com/cindy/cfg/providers.json";
    const fetchText = vi.fn().mockRejectedValue(new Error("offline"));
    const readCache = vi.fn(async (scope: string) =>
      scope === legacyUrl
        ? JSON.stringify({
            ...MINIMAL,
            cindyModelMeta: { version: 1, models: {} },
          })
        : null,
    );
    const result = await loadCatalogWithSource(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText, readCache },
    );
    expect(result.source).toBe("cache");
    expect(result.capabilityEvidence).toBe("fallback");
    expect(result.catalog.version).toBe("test");
    expect(result.catalog).not.toHaveProperty("cindyModelMeta");
    expect(result.authorityCatalog).toBeNull();
  });

  it("shares one remote budget across the public API and legacy OSS fallback", async () => {
    const now = vi
      .fn()
      .mockReturnValueOnce(1_000)
      .mockReturnValueOnce(1_000)
      .mockReturnValueOnce(11_000);
    const fetchText = vi
      .fn()
      .mockRejectedValueOnce(new Error("api timeout"))
      .mockResolvedValueOnce(JSON.stringify(MINIMAL));
    const cat = await loadCatalog(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        remoteBudgetMs: 15_000,
        now,
      },
      { fetchText },
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      1,
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6&registryMedia=1&registryLocalRuntimes=1",
      15_000,
    );
    expect(fetchText).toHaveBeenNthCalledWith(
      2,
      "https://cdn.example.com/cindy/cfg/providers.json",
      5_000,
    );
    expect(cat.version).toBe("test");
  });

  it("does not start legacy OSS after the shared remote budget is exhausted", async () => {
    const now = vi
      .fn()
      .mockReturnValueOnce(1_000)
      .mockReturnValueOnce(1_000)
      .mockReturnValueOnce(16_000);
    const fetchText = vi.fn().mockRejectedValueOnce(new Error("api timeout"));
    const cat = await loadCatalog(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        remoteBudgetMs: 15_000,
        now,
      },
      { fetchText },
    );
    expect(fetchText).toHaveBeenCalledTimes(1);
    expect(fetchText).toHaveBeenCalledWith(
      "https://model-access.example.com/api/model-catalog/catalog?registrySchemaVersion=6&registryMedia=1&registryLocalRuntimes=1",
      15_000,
    );
    expect(cat.version).toBe(BUNDLED_CATALOG.version);
  });

  it("uses explicit URL without also retrying the legacy OSS fallback", async () => {
    const fetchText = vi
      .fn()
      .mockRejectedValue(new Error("override unavailable"));
    const cat = await loadCatalog(
      {
        url: "https://override.example.com/providers.json",
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText },
    );
    expect(fetchText).toHaveBeenCalledTimes(1);
    expect(fetchText).toHaveBeenCalledWith(
      "https://override.example.com/providers.json",
      15_000,
    );
    expect(cat.version).toBe(BUNDLED_CATALOG.version);
  });

  it("redacts credentials, query, and hash from remote URL diagnostics", async () => {
    const remoteUrl =
      "https://catalog-user:[email protected]/providers.json?token=secret-token#private";
    const log = vi.fn<NonNullable<CatalogIO["log"]>>();
    const fetchText = vi.fn(async (url: string) => {
      throw new Error(`request failed for ${url}`);
    });

    await loadCatalog({ url: remoteUrl, now: () => 0 }, { fetchText, log });

    expect(fetchText).toHaveBeenCalledWith(remoteUrl, 15_000);
    const diagnostics = JSON.stringify(log.mock.calls);
    expect(diagnostics).toContain(
      "https://override.example.com/providers.json",
    );
    expect(diagnostics).not.toContain("catalog-user");
    expect(diagnostics).not.toContain("catalog-pass");
    expect(diagnostics).not.toContain("secret-token");
    expect(diagnostics).not.toContain("#private");
  });

  it("keeps special legacy JSON keys inert and lets strict parsing reject them", async () => {
    const legacyPayload = JSON.stringify(MINIMAL).replace(
      "{",
      '{"__proto__":{"polluted":true},"cindyModelMeta":{"version":1},',
    );
    const fetchText = vi
      .fn()
      .mockRejectedValueOnce(new Error("api unavailable"))
      .mockResolvedValueOnce(legacyPayload);

    const result = await loadCatalogWithSource(
      {
        baseUrl: "https://model-access.example.com",
        fallbackBaseUrl: "https://cdn.example.com/cindy",
        now: () => 0,
      },
      { fetchText },
    );

    expect(result).toEqual({
      source: "bundled",
      capabilityEvidence: "fallback",
      unverifiedXdMediaKinds: ["image", "video", "embedding"],
      catalog: BUNDLED_CATALOG,
      authorityCatalog: null,
    });
    expect(
      (Object.prototype as { polluted?: unknown }).polluted,
    ).toBeUndefined();
  });

  it("falls back to bundled when fetch fails", async () => {
    const io: CatalogIO = {
      fetchText: vi.fn(async () => {
        throw new Error("network down");
      }),
    };
    const cat = await loadCatalog({ url: "https://x/y.json" }, io);
    expect(cat.version).toBe(BUNDLED_CATALOG.version);
    expect(cat.providers.map((p) => p.id).sort()).toEqual([
      "anthropic",
      "gemini",
      "openai",
      "xai",
      "xd",
    ]);
  });

  it("disableFetch → bundled (no network)", async () => {
    const fetchText = vi.fn();
    const cat = await loadCatalog(
      { url: "https://x/y.json", disableFetch: true },
      { fetchText },
    );
    expect(fetchText).not.toHaveBeenCalled();
    expect(cat.providers.length).toBe(BUNDLED_CATALOG.providers.length);
  });
});

describe("registry visibility & sources(运行时注入 fixture)", () => {
  const views = buildRegistry(runtimeCatalog(), {
    xd: true,
    anthropic: false,
    openai: false,
  });

  it("providersForAgent ignores connection", () => {
    expect(
      providersForAgent(views, "claude-code")
        .map((p) => p.id)
        .sort(),
    ).toEqual(["anthropic", "openai", "xai", "xd"]);
    expect(
      providersForAgent(views, "codex")
        .map((p) => p.id)
        .sort(),
    ).toEqual(["openai", "xai", "xd"]);
  });

  it("connectedProvidersForAgent honors connection", () => {
    expect(
      connectedProvidersForAgent(views, "claude-code").map((p) => p.id),
    ).toEqual(["xd"]);
    expect(connectedProvidersForAgent(views, "codex").map((p) => p.id)).toEqual(
      ["xd"],
    );
  });

  it("agent selectors and model sources exclude disabled runtimes", () => {
    const catalog = runtimeCatalog();
    const xd = catalog.providers.find((provider) => provider.id === "xd")!;
    xd.routing.codex = { ...xd.routing.codex!, disabled: true };
    const disabledViews = buildRegistry(catalog, { xd: true });

    expect(
      providersForAgent(disabledViews, "codex").map((provider) => provider.id),
    ).not.toContain("xd");
    expect(connectedProvidersForAgent(disabledViews, "codex")).toEqual([]);
    expect(sourcesForModel(disabledViews, "gpt-5.5", "codex")).toEqual([]);
    expect(
      connectedProvidersForAgent(disabledViews, "claude-code").map(
        (provider) => provider.id,
      ),
    ).toEqual(["xd"]);
  });

  it("agent selectors and model sources exclude a declared agent with no routing descriptor", () => {
    const catalog = runtimeCatalog();
    const xd = catalog.providers.find((provider) => provider.id === "xd")!;
    delete xd.routing.codex;
    const missingRouteViews = buildRegistry(catalog, { xd: true });

    expect(
      providersForAgent(missingRouteViews, "codex").map(
        (provider) => provider.id,
      ),
    ).not.toContain("xd");
    expect(connectedProvidersForAgent(missingRouteViews, "codex")).toEqual([]);
    expect(sourcesForModel(missingRouteViews, "gpt-5.5", "codex")).toEqual([]);
  });

  it("providerOffersModel / getModel (agent-scoped)", () => {
    const xd = views.find((p) => p.id === "xd")!;
    expect(providerOffersModel(xd, "gpt-5.5", "codex")).toBe(true);
    expect(providerOffersModel(xd, "no-such", "codex")).toBe(false);
    expect(providerOffersModel(xd, "claude-opus-4-8", "codex")).toBe(false);
    expect(getModel(xd, "claude-opus-4-8", "claude-code")?.name).toBe(
      "Opus 4.8",
    );
  });

  it("sourcesForModel: only connected providers by default", () => {
    expect(
      sourcesForModel(views, "claude-opus-4-8", "claude-code").map((p) => p.id),
    ).toEqual(["xd"]);
    expect(
      sourcesForModel(views, "claude-opus-4-8", "claude-code", {
        onlyConnected: false,
      })
        .map((p) => p.id)
        .sort(),
    ).toEqual(["anthropic", "xd"]);
  });

  it("sourcesForModel: same model two sources when both connected", () => {
    const all = buildRegistry(runtimeCatalog(), {
      xd: true,
      anthropic: true,
      openai: true,
      xai: true,
    });
    expect(
      sourcesForModel(all, "gpt-5.5", "codex")
        .map((p) => p.id)
        .sort(),
    ).toEqual(["openai", "xd"]);
    expect(
      sourcesForModel(all, "gpt-5.5", "claude-code").map((p) => p.id),
    ).toEqual(["xd"]);
    expect(
      sourcesForModel(all, "xai/grok-4.3", "codex").map((p) => p.id),
    ).toEqual(["xai"]);
  });

  it("effectiveSourceIdForModel 只在真正提供当前模型的已连接来源里选默认", () => {
    const openaiOnly = buildRegistry(runtimeCatalog(), {
      xd: false,
      anthropic: false,
      openai: true,
      xai: false,
    });
    expect(
      effectiveSourceIdForModel(
        openaiOnly,
        null,
        "claude-opus-4-8",
        "claude-code",
      ),
    ).toBeNull();
    expect(
      effectiveSourceIdForModel(
        openaiOnly,
        null,
        "chatgpt/gpt-5.5",
        "claude-code",
      ),
    ).toBe("openai");
  });

  it("effectiveSourceIdForModel 保留有效显式来源,失效时不替换账号", () => {
    const all = buildRegistry(runtimeCatalog(), {
      xd: true,
      anthropic: true,
      openai: true,
      xai: true,
    });
    expect(
      effectiveSourceIdForModel(
        all,
        "anthropic",
        "claude-opus-4-8",
        "claude-code",
      ),
    ).toBe("anthropic");
    expect(
      effectiveSourceIdForModel(
        all,
        "openai",
        "claude-opus-4-8",
        "claude-code",
      ),
    ).toBeNull();
  });

  it("effectiveSourceIdForModel 不把请求路由到非聊天来源(issue #882 第 3 点,2026-07 review):同一 id 在不同来源上 mode 不一致时,只信聊天来源", () => {
    const mixedModeCatalog: Catalog = {
      version: "test",
      providers: [
        {
          id: "xd",
          name: "XD",
          source: "builtin",
          agents: ["claude-code"],
          auth: { method: "managed" },
          routing: {
            "claude-code": {
              upstream: "https://xd.test",
              authStrategy: "gateway-key",
            },
          },
          models: {
            "claude-code": [model("shared-id", { mode: "image_generation" })],
          },
        },
        {
          id: "openai",
          name: "OpenAI",
          source: "builtin",
          agents: ["claude-code"],
          auth: { method: "oauth" },
          routing: {
            "claude-code": {
              upstream: "https://api.openai.com",
              authStrategy: "oauth-passthrough",
            },
          },
          models: {
            "claude-code": [model("shared-id", { mode: "chat" })],
          },
        },
      ],
    };
    const views = buildRegistry(mixedModeCatalog, { xd: true, openai: true });
    // 显式指定的来源不是聊天来源时拒绝,不改用另一个账号。
    expect(
      effectiveSourceIdForModel(views, "xd", "shared-id", "claude-code"),
    ).toBeNull();
    // 未显式指定 providerId 时,默认来源同样只能是聊天来源。
    expect(
      effectiveSourceIdForModel(views, null, "shared-id", "claude-code"),
    ).toBe("openai");

    // chatEligibleSourcesForModel 是这份过滤的共享底层——直接断言它自己的输出,
    // 保证 UI 侧的"有没有可发送来源"判断(ChatInput/useConnectedSource/
    // isSelectedSourceDisconnected)与路由解析用的是同一份口径,不会互相打架。
    expect(
      chatEligibleSourcesForModel(views, "shared-id", "claude-code").map(
        (p) => p.id,
      ),
    ).toEqual(["openai"]);
  });

  it("chatEligibleSourcesForModel 不误杀用户自定义供应商显式配置的模型(2026-07 review 第 25 轮)", () => {
    // flux-image-x 的 id 撞上 /image/ 启发式,但它来自 source:'user' 的自定义供应商且
    // group 是未知的 custom:*——isAgentSelectableModel 的 userProvider 例外有意放行
    // (用户显式配置的就是聊天模型)。裸 isChatEligible 会把它从路由/发送门禁里删掉,
    // 用户配好的模型 UI 显示"没有已连接的来源"、请求发不出去。
    const userProviderCatalog: Catalog = {
      version: "test",
      providers: [
        {
          id: "custom-p",
          name: "Custom",
          source: "user",
          agents: ["claude-code"],
          auth: { method: "apiKey" },
          routing: {
            "claude-code": {
              upstream: "https://custom.test",
              authStrategy: "api-key-header",
            },
          },
          models: {
            "claude-code": [
              model("flux-image-x", { group: "custom:custom-p" }),
            ],
          },
        },
      ],
    };
    const views = buildRegistry(userProviderCatalog, { "custom-p": true });
    expect(
      chatEligibleSourcesForModel(views, "flux-image-x", "claude-code").map(
        (p) => p.id,
      ),
    ).toEqual(["custom-p"]);
    expect(
      effectiveSourceIdForModel(
        views,
        "custom-p",
        "flux-image-x",
        "claude-code",
      ),
    ).toBe("custom-p");
  });
});

describe("resolveRoute(运行时注入 fixture)", () => {
  const views = buildRegistry(runtimeCatalog(), {
    xd: true,
    anthropic: true,
    openai: true,
    xai: true,
  });
  // xd 网关地址以内置身份卡(builtin.ts,端点单点)为准;门禁校验其与权威源一致
  const xdRouting = BUNDLED_CATALOG.providers.find(
    (prov) => prov.id === "xd",
  )?.routing;

  it("anthropic claude (claude-code) → direct upstream, oauth-passthrough", () => {
    const r = resolveRoute(
      views,
      "anthropic",
      "claude-opus-4-8",
      "claude-code",
    );
    expect(r?.routing.upstream).toBe("https://api.anthropic.com");
    expect(r?.routing.authStrategy).toBe("oauth-passthrough");
  });

  it("anthropic claude has no Codex / Pi route (subscription stays inside the Claude Code CLI)", () => {
    expect(resolveRoute(views, "anthropic", "claude-opus-4-8", "codex")).toBeNull();
    expect(resolveRoute(views, "anthropic", "claude-opus-4-8", "pi")).toBeNull();
    expect(resolveRoute(views, "anthropic", "claude-opus-4-8", "claude-code")?.routing.upstream).toBe(
      "https://api.anthropic.com",
    );
  });

  it("xd claude (claude-code) → gateway, gateway-key, 不删 anthropic-beta(fast 经网关透传)", () => {
    const r = resolveRoute(views, "xd", "claude-opus-4-8", "claude-code");
    expect(r?.routing.upstream).toBe(xdRouting?.["claude-code"]?.upstream);
    expect(r?.routing.authStrategy).toBe("gateway-key");
    expect(r?.routing.headerDelete).toBeUndefined();
  });

  it("xd gpt (codex) → gateway/v1; openai gpt (codex) → chatgpt direct", () => {
    expect(
      resolveRoute(views, "xd", "gpt-5.5", "codex")?.routing.upstream,
    ).toBe(xdRouting?.codex?.upstream);
    const oa = resolveRoute(views, "openai", "gpt-5.5", "codex");
    expect(oa?.routing.upstream).toBe("https://chatgpt.com/backend-api/codex");
    expect(oa?.routing.authStrategy).toBe("oauth-passthrough");
  });

  it("xai grok (codex) → api.x.ai/v1 with provider OAuth token and xai/ model rewrite", () => {
    const r = resolveRoute(views, "xai", "xai/grok-4.3", "codex");
    expect(r?.routing.upstream).toBe("https://api.x.ai/v1");
    expect(r?.routing.authStrategy).toBe("provider-oauth-header");
    expect(r?.routing.modelIdRewrite).toEqual({ stripPrefix: "xai/" });
  });

  it("rejects unsupported (provider, model, agent) combos", () => {
    expect(
      resolveRoute(views, "anthropic", "gpt-5.5", "claude-code"),
    ).toBeNull();
    expect(
      resolveRoute(views, "openai", "claude-opus-4-8", "codex"),
    ).toBeNull();
    expect(
      resolveRoute(views, "nope", "claude-opus-4-8", "claude-code"),
    ).toBeNull();
  });

  it("rejects a disabled route even when provider, model, and agent match", () => {
    const disabledViews = views.map((provider) =>
      provider.id === "xai"
        ? {
            ...provider,
            routing: {
              ...provider.routing,
              codex: { ...provider.routing.codex!, disabled: true },
            },
          }
        : provider,
    );
    expect(
      resolveRoute(disabledViews, "xai", "xai/grok-4.3", "codex"),
    ).toBeNull();
  });

  it("动态供应商未注入清单时不解析路由(无可用性证明不路由)", () => {
    const bare = buildRegistry(BUNDLED_CATALOG, {
      xd: true,
      anthropic: true,
      openai: true,
      xai: true,
    });
    expect(
      resolveRoute(bare, "anthropic", "claude-opus-4-8", "claude-code"),
    ).toBeNull();
    expect(resolveRoute(bare, "xd", "gpt-5.5", "codex")).toBeNull();
    expect(
      resolveRoute(bare, "xai", "xai/grok-4.3", "codex")?.routing.upstream,
    ).toBe("https://api.x.ai/v1");
  });
});

describe("server-delivered local models", () => {
  it("accepts later V4 updates and preserves an explicit empty recommendation through offline fallback", async () => {
    const snapshot = {
      ...MINIMAL,
      modelRegistry: {
        schemaVersion: 4,
        updatedAt: "2099-01-01T00:00:00.000Z",
        models: [],
        localModels: { version: 1, models: [], featuredIds: [] },
      },
    };
    let cached: string | null = null;
    const cfg = { baseUrl: "https://model-access.example.com" };
    const io: CatalogIO = {
      fetchText: async () => JSON.stringify(snapshot),
      readCache: async () => cached,
      writeCache: async (_scope, text) => {
        cached = text;
      },
    };
    const remote = await loadCatalogWithSource(cfg, io);
    expect(remote.catalog.modelRegistry?.localModels).toEqual(
      snapshot.modelRegistry.localModels,
    );
    const offline = await loadCatalogWithSource(cfg, {
      ...io,
      fetchText: async () => {
        throw new Error("offline");
      },
    });
    expect(offline.source).toBe("cache");
    expect(offline.catalog.modelRegistry?.localModels?.featuredIds).toEqual([]);
    const invalid = structuredClone(snapshot);
    invalid.modelRegistry.localModels.featuredIds = ["missing"] as never[];
    const rejected = await loadCatalogWithSource(cfg, {
      ...io,
      fetchText: async () => JSON.stringify(invalid),
    });
    expect(rejected.catalog.modelRegistry?.localModels).toEqual(
      snapshot.modelRegistry.localModels,
    );
    expect(JSON.parse(cached!).modelRegistry.localModels.featuredIds).toEqual(
      [],
    );
    const conflict = structuredClone(snapshot);
    delete (conflict.modelRegistry as { localModels?: unknown }).localModels;
    const retained = await loadCatalogWithSource(cfg, {
      ...io,
      fetchText: async () => JSON.stringify(conflict),
    });
    expect(retained.catalog.modelRegistry?.localModels).toEqual(
      snapshot.modelRegistry.localModels,
    );
  });
});

// Tier: integration. Same loader instance/unchanged code accepts data-only updates;
// schema negotiation uses one deadline and never blends two profile revisions.
describe('V6 negotiation', () => {
  it('retries a frozen unknown-version response as V5 once and caches the actual variant', async () => {
    const old = { ...MINIMAL, modelRegistry: { schemaVersion: 5, updatedAt: '2099-01-01T00:00:00.000Z', models: [] } };
    let clock = 0;
    const fetchText = vi.fn(async (url: string) => { clock += 7; return JSON.stringify(url.includes('Version=6') ? MINIMAL : old); });
    const writeCache = vi.fn(async () => {});
    const result = await loadCatalogWithSource({ baseUrl: 'https://models.example', now: () => clock, remoteBudgetMs: 100 }, { fetchText, writeCache });
    expect(fetchText).toHaveBeenCalledTimes(2);
    expect(fetchText).toHaveBeenNthCalledWith(2, expect.stringContaining('registrySchemaVersion=5'), 93);
    expect(result.catalog.modelRegistry?.schemaVersion).toBe(5);
    expect(writeCache).toHaveBeenCalledWith(expect.stringContaining('registrySchemaVersion=5'), expect.any(String));
  });
});

it('keeps the accepted complete V6 snapshot when an old server answers with its V5 projection', async () => {
  const { projectRegistryV5 } = await import('../modelInterfaceContract.js');
  const current = { ...MINIMAL, modelRegistry: structuredClone(BUNDLED_CATALOG.modelRegistry!) };
  current.modelRegistry.updatedAt = '2099-01-01T00:00:00.000Z';
  const legacy = { ...current, modelRegistry: projectRegistryV5(current.modelRegistry) };
  const writeCache = vi.fn(async () => {});
  const result = await loadCatalogWithSource({ baseUrl: 'https://models.example' }, {
    fetchText: async () => JSON.stringify(legacy),
    readCache: async url => url.includes('Version=6') ? JSON.stringify(current) : null,
    writeCache,
  });
  expect(result.catalog.modelRegistry).toEqual(current.modelRegistry);
  expect(result.capabilityEvidence).toBe('fallback');
  expect(writeCache).toHaveBeenCalledWith(expect.stringContaining('Version=6'), expect.any(String));
});