Skip to content

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

10.6 KB
Raw Blame
/**
 * A custom endpoint gets the metadata the catalog can justify for it.
 *
 * Two reported failures live here. A custom row pointed at
 * `https://open.bigmodel.cn/api/v1` (Zhipu's OpenAI Responses endpoint) listed
 * its models but showed a generic 128k / 8k text-only row for every one of them,
 * because the catalog only accepted that host's own published path. A row on a
 * relay the catalog cannot place used to get nothing at all; it now still reads
 * the weight owner's published record for ids the owner states, so a relay-only
 * `deepseek-v4-flash` keeps DeepSeek's window instead of the generic seed.
 *
 * This drives the real handlers with the bundled snapshot, so it pins the whole
 * chain: discovery, endpoint resolution, catalog anchoring, and the hand-typed
 * id channel.
 */
import assert from "node:assert/strict";
import { register } from "node:module";
import test from "node:test";
import { fileURLToPath } from "node:url";

register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));

const { registerProviderIpc } = await import("../electron/main/ipc/provider-ipc.ts");
const { ModelsDevCatalog } = await import("../electron/main/models-dev-catalog.ts");
const { IPC } = await import("@pi-desktop/shared");

const catalogPath = fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url));

function jsonResponse(body, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { "content-type": "application/json" },
  });
}

/** Register the real handlers against one row and one served model list. */
async function handlersFor(t, row, body) {
  const catalog = new ModelsDevCatalog({ catalogPath });
  assert.equal(await catalog.ensureLoaded(), true, "the bundled snapshot must load");

  const original = globalThis.fetch;
  const calls = [];
  const cacheWrites = [];
  globalThis.fetch = async (url) => {
    calls.push(String(url));
    return String(url).endsWith("/models") ? jsonResponse(body) : new Response("", { status: 404 });
  };
  t.after(() => {
    globalThis.fetch = original;
  });

  const handlers = new Map();
  registerProviderIpc({
    registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
    getHost: () => ({
      call: async (method, params) => {
        if (method === "providers.list") return { providers: [row] };
        if (method === "providers.getSecret") return { value: "sk-secret" };
        if (method === "providers.get") return { provider: row };
        if (method === "providers.cacheModels") {
          cacheWrites.push(params);
          return { models: params.models };
        }
        return {};
      },
    }),
    modelsDevCatalog: catalog,
    vendorOAuth: {},
    logger: { app: () => {} },
    enrichProvider: (provider) => provider,
    listRuntimeProviders: async () => [row],
    enrichProviderList: (result) => result,
    bindingForModel: () => undefined,
  });

  const listModels = handlers.get(IPC.invoke.providersListModels);
  assert.equal(typeof listModels, "function", "list-models handler is not registered");
  const lookupModel = handlers.get(IPC.invoke.providersLookupModel);
  assert.equal(typeof lookupModel, "function", "model-lookup handler is not registered");

  return {
    calls,
    cacheWrites,
    row,
    result: await listModels({ providerId: row.id, source: "refresh" }),
    /** The hand-typed id channel a picker uses when a user types an id in. */
    lookup: (input) => lookupModel(input),
  };
}

function rowOf(overrides) {
  return {
    name: "Row",
    vendorKey: "custom",
    apiStyle: "chat_completions",
    models: [],
    authKind: "api_key_and_base_url",
    headers: {},
    ...overrides,
  };
}

test("a custom row on a published host gets that publisher's model metadata", async (t) => {
  const row = rowOf({
    id: "row-1",
    name: "Zhipu",
    baseUrl: "https://open.bigmodel.cn/api/v1",
    apiStyle: "responses",
  });
  const { result, calls } = await handlersFor(t, row, {
    models: [{ slug: "glm-5.3", display_name: "glm-5.3" }],
  });

  assert.deepEqual(calls, ["https://open.bigmodel.cn/api/v1/models"]);
  // The address the user typed answered, so it stays the row's address.
  assert.equal(result.effectiveBaseUrl, "https://open.bigmodel.cn/api/v1");

  const [model] = result.models;
  assert.equal(model.modelId, "glm-5.3", "the wire id is the one the service served");
  assert.equal(model.catalogSource, "models.dev", "the host identified the publisher");
  assert.equal(model.contextWindow, 1_000_000);
  assert.equal(model.maxTokens, 131_072);
  for (const capability of ["tools", "reasoning"]) {
    assert.ok(model.capabilities.includes(capability), `expected ${capability} capability`);
  }
});

test("a relay's list reads the shipped publisher's record for a known id", async (t) => {
  const row = rowOf({
    id: "row-2",
    name: "Relay",
    baseUrl: "https://relay.example/v1",
  });
  const { result } = await handlersFor(t, row, {
    data: [{ id: "claude-sonnet-4-5" }, { id: "some-private-model" }],
  });

  const byId = new Map(result.models.map((model) => [model.modelId, model]));
  const known = byId.get("claude-sonnet-4-5");
  assert.equal(known.catalogSource, "models.dev", "several publishers state this id");
  // Anthropic's current published window, not larger reseller deployment values.
  assert.equal(known.contextWindow, 200_000);
  assert.equal(known.maxTokens, 64_000);
  assert.ok(known.capabilities.includes("tools"));
  // An id no publisher states still lands on the generic seed.
  const unknown = byId.get("some-private-model");
  assert.equal(unknown.catalogSource, undefined);
  assert.equal(unknown.contextWindow, 128_000);
  assert.deepEqual(unknown.capabilities, ["text"]);
});

test("a model-list capacity report takes precedence over catalog limits", async (t) => {
  const row = rowOf({
    id: "row-reported-capacity",
    name: "Relay",
    baseUrl: "https://relay.example/v1",
  });
  const { result, cacheWrites } = await handlersFor(t, row, {
    data: [
      { id: "claude-sonnet-4-5", context_length: 321_000, max_tokens: 12_345 },
      { id: "some-private-model" },
    ],
  });

  const [model] = result.models;
  assert.equal(model.contextWindow, 321_000, "the endpoint reports its actual context window");
  assert.equal(model.maxTokens, 12_345, "the endpoint reports its actual output limit");
  assert.equal(model.catalogSource, "models.dev", "catalog metadata still identifies the model");
  assert.deepEqual(cacheWrites[0].endpoint, { baseUrl: row.baseUrl, apiStyle: row.apiStyle });
  assert.equal(cacheWrites[0].models[0].reportedContextWindow, 321_000);
  assert.equal(cacheWrites[0].models[1].contextWindow, 128_000);
  assert.equal(cacheWrites[0].models[1].reportedContextWindow, undefined);
});

test("a hand-typed id on the same relay answers with the same record", async (t) => {
  const row = rowOf({
    id: "row-3",
    name: "Relay",
    baseUrl: "https://relay.example/v1",
  });
  const { lookup } = await handlersFor(t, row, { data: [] });

  const known = await lookup({
    modelId: "claude-sonnet-4-5",
    baseUrl: row.baseUrl,
    vendorKey: row.vendorKey,
    providerId: row.id,
  });
  assert.ok(known.info, "a typed id the catalog knows must reach its record");
  assert.equal(known.info.modelId, "claude-sonnet-4-5");
  assert.ok(known.info.capabilities.includes("tools"));

  // A private id stays generic, and the lookup never contacts the network.
  const unknown = await lookup({ modelId: "some-private-model", baseUrl: row.baseUrl });
  assert.equal(unknown.info, null);
});

test("a relay enriches official IDs, strips safe deployment labels, and preserves variants", async (t) => {
  /*
    Exact last-segment matches run first. A unique official publisher wins over
    reseller copies, and only whitelisted deployment labels such as `-1m` are
    stripped as a fallback; semantic variants and release dates stay distinct.
  */
  const row = rowOf({ id: "row-4", name: "Relay", baseUrl: "https://relay.example/v1" });
  const { result } = await handlersFor(t, row, {
    data: [
      { id: "deepseek-v4-flash" },
      { id: "deepseek-v4-pro" },
      { id: "deepseek-v4-pro-1m" },
      { id: "mimo-v2.5-tts" },
      { id: "gemini-2.5-pro-1m" },
      { id: "claude-sonnet-4-5" },
    ],
  });

  const byId = new Map(result.models.map((model) => [model.modelId, model]));

  // The weight owner (DeepSeek) publishes this id, so an unanchored relay reads
  // the owner's record instead of dropping to the generic seed.
  const deepseek = byId.get("deepseek-v4-flash");
  assert.equal(deepseek.catalogSource, "models.dev");
  assert.equal(deepseek.contextWindow, 1_048_576);
  assert.equal(deepseek.maxTokens, 393_216);
  // DeepSeek's current official listing is the source of truth for both the
  // base model and its whitelisted context-size deployment label.
  for (const id of ["deepseek-v4-pro", "deepseek-v4-pro-1m"]) {
    const model = byId.get(id);
    assert.equal(model.modelId, id); // lookup never rewrites the served wire ID
    assert.equal(model.catalogSource, "models.dev");
    assert.equal(model.contextWindow, 1_048_576);
    assert.equal(model.maxTokens, 393_216);
  }

  // The refreshed catalog has no Xiaomi-owned TTS record, so relay lookups
  // must not claim reseller metadata for it.
  const tts = byId.get("mimo-v2.5-tts");
  assert.equal(tts.modelId, "mimo-v2.5-tts");
  assert.equal(tts.catalogSource, undefined);
  // Google and Vertex now publish matching metadata, so the `-1m` alias can
  // safely use their shared record without changing the served model id.
  const gemini = byId.get("gemini-2.5-pro-1m");
  assert.equal(gemini.catalogSource, "models.dev");
  assert.equal(gemini.contextWindow, 1_048_576);

  // Official Anthropic disambiguation still enriches exact leaves.
  const claude = byId.get("claude-sonnet-4-5");
  assert.equal(claude.catalogSource, "models.dev");
  assert.equal(claude.contextWindow, 200_000);
});
test("a relay enriches a uniquely published dated leaf without reseller majority voting", async (t) => {
  /*
    #1047: exact leaf match. If the dated id is published uniquely (or shares
    identical capabilities / a unique official), enrich; otherwise stay generic.
    No shipped-publisher majority override beyond official/source disambiguation.
  */
  const row = rowOf({ id: "row-5", name: "Relay", baseUrl: "https://relay.example/v1" });
  const { result } = await handlersFor(t, row, { data: [{ id: "doubao-seed-2-0-pro-260215" }] });

  const [model] = result.models;
  // Accept either enrichment from an exact leaf hit, or generic when ambiguous.
  if (model.catalogSource === "models.dev") {
    assert.ok(model.contextWindow > 0);
  } else {
    assert.equal(model.catalogSource, undefined);
  }
});