Skip to content

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

fix(oauth): preserve thinking metadata for live-only models

Zhangyinglunc9b6e2c97ba5
diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.ts
index 783fe2dcb..0580c28a0 100644
--- a/apps/desktop/electron/main/oauth.ts
+++ b/apps/desktop/electron/main/oauth.ts
@@ -18,7 +18,7 @@
import { randomUUID } from "node:crypto";
-import { InMemoryModelsStore } from "@earendil-works/pi-ai";
+import { getSupportedThinkingLevels, InMemoryModelsStore } from "@earendil-works/pi-ai";
import type {
Api,
AuthEvent,
@@ -57,7 +57,6 @@ import {
type OAuthStartResult,
type OAuthVendor,
type ModelBinding,
- type ThinkingLevel,
} from "@pi-desktop/shared";
export { OAUTH_AUTH_KIND };
@@ -100,32 +99,12 @@ export function protocolForApiStyle(apiStyle: string): string {
const LIVE_MODELS_TTL_MS = 30_000;
const LIVE_MODELS_NEGATIVE_TTL_MS = 15_000;
-const THINKING_LEVEL_ORDER = [
- "off",
- "minimal",
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
-] as const satisfies readonly ThinkingLevel[];
/** xAI and the other account lists also publish generators. Those are not conversation models. */
export function isXaiConversationModel(modelId: string): boolean {
return isConversationModelId(modelId);
}
-function thinkingLevelsFromPiModel(model: Model<Api>): ThinkingLevel[] {
- const map = model.thinkingLevelMap as Partial<Record<string, string | null>> | undefined;
- if (!map) return model.reasoning ? ["low", "medium", "high"] : ["off"];
- const levels = THINKING_LEVEL_ORDER.filter((level) => typeof map[level] === "string");
- return levels.length > 0
- ? [...levels]
- : model.reasoning
- ? ["low", "medium", "high"]
- : ["off"];
-}
-
export type HostCall = <T = unknown>(
method: string,
params?: unknown,
@@ -558,10 +537,9 @@ export class VendorOAuth {
}
/**
- * models.dev is the metadata source when it already knows the id. A model
- * that exists only on the live list otherwise inherits limits and thinking
- * levels from a pinned sibling of the same tier. xAI uses an explicit
- * newest-first order so pin order cannot pick an older Grok.
+ * models.dev is authoritative for known ids. Live-only models inherit limits,
+ * thinking levels, and adapter compatibility from a pinned same-tier sibling.
+ * xAI uses an explicit newest-first order so pin order cannot pick an older Grok.
*/
private async withPinnedSiblingFallback(
account: AccountModels,
@@ -582,9 +560,14 @@ export class VendorOAuth {
const input = (sibling.input ?? []).filter(
(modality): modality is "text" | "image" => modality === "text" || modality === "image",
);
+ const thinkingLevelMap = config.thinkingLevelMap ?? sibling.thinkingLevelMap;
+ const supportedThinkingLevels = getSupportedThinkingLevels({ ...sibling, thinkingLevelMap });
return {
...config,
- reasoning: sibling.reasoning,
+ // Keep the protocol and wire effort mapping paired with borrowed reasoning.
+ compat: { ...sibling.compat, ...config.compat },
+ thinkingLevelMap,
+ reasoning: supportedThinkingLevels.some((level) => level !== "off"),
input: input.length > 0 ? input : config.input,
contextWindow: sibling.contextWindow,
maxTokens: sibling.maxTokens,
@@ -593,7 +576,7 @@ export class VendorOAuth {
input: sibling.contextWindow,
output: sibling.maxTokens,
},
- supportedThinkingLevels: thinkingLevelsFromPiModel(sibling),
+ supportedThinkingLevels,
};
}
diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjs
index 6a1855d81..f81ec9d8b 100644
--- a/apps/desktop/test/vendor-oauth-login.test.mjs
+++ b/apps/desktop/test/vendor-oauth-login.test.mjs
@@ -1,6 +1,17 @@
import assert from "node:assert/strict";
import test from "node:test";
+import {
+ capabilitiesFromModelConfig,
+ clampThinkingLevel,
+ genericModelConfig,
+ modelConfigWithBinding,
+} from "@pi-desktop/agent-runtime";
+import {
+ buildProviderModel,
+ createProviderModels,
+} from "../../../packages/agent-runtime/dist/provider-binding.js";
+
import {
VendorOAuth,
apiStyleForWireApi,
@@ -767,5 +778,188 @@ test("a new Grok inherits grok-4.6 even when an older Grok is first in the pin",
const binding = await oauth.bindingFor(done.providerId, "grok-4.7");
assert.equal(binding.modelConfig.contextWindow, 500_000);
assert.equal(binding.modelConfig.maxTokens, 500_000);
- assert.deepEqual(binding.supportedThinkingLevels, ["low", "medium", "high", "xhigh"]);
+ assert.deepEqual(binding.supportedThinkingLevels, ["minimal", "low", "medium", "high", "xhigh"]);
+});
+
+async function liveCopilotBinding(sibling, options = {}) {
+ const modelId = options.modelId ?? "claude-sonnet-99";
+ const { events, oauth } = harness({
+ provider: {
+ id: "github-copilot",
+ name: "GitHub Copilot",
+ baseUrl: "https://api.individual.githubcopilot.com",
+ auth: { oauth: { name: "GitHub Copilot", loginLabel: "Sign in" } },
+ },
+ models: [sibling],
+ modelConfigFor: options.modelConfigFor,
+ fetch: async () => new Response(JSON.stringify({
+ data: [{ id: modelId, model_picker_enabled: true, policy: { state: "enabled" } }],
+ }), { status: 200, headers: { "content-type": "application/json" } }),
+ });
+ const { loginId } = await oauth.start("github-copilot");
+ const prompt = await waitFor(events, "prompt");
+ oauth.respond({ loginId, promptId: prompt.request.promptId, value: "test-code" });
+ const done = await waitFor(events, "done");
+ const binding = await oauth.bindingFor(done.providerId, modelId);
+ assert.ok(binding, "the account's newly offered model must be runnable");
+ return binding;
+}
+
+const adaptiveSonnet = {
+ id: "claude-sonnet-5",
+ name: "Claude Sonnet 5",
+ api: "anthropic-messages",
+ provider: "github-copilot",
+ baseUrl: "https://api.individual.githubcopilot.com",
+ reasoning: true,
+ input: ["text", "image"],
+ contextWindow: 1_000_000,
+ maxTokens: 128_000,
+ cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 },
+ compat: { forceAdaptiveThinking: true },
+ thinkingLevelMap: {
+ off: null,
+ minimal: null,
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ },
+};
+
+test("a live-only Claude model retains its sibling's thinking protocol and effort mapping", async () => {
+ const binding = await liveCopilotBinding(adaptiveSonnet);
+ assert.equal(binding.apiStyle, "anthropic_messages");
+ assert.equal(binding.modelConfig.name, "claude-sonnet-99");
+ assert.equal(binding.modelConfig.compat?.forceAdaptiveThinking, true);
+ assert.deepEqual(binding.modelConfig.thinkingLevelMap, adaptiveSonnet.thinkingLevelMap);
+ assert.equal(binding.modelConfig.contextWindow, 1_000_000);
+ assert.equal(binding.modelConfig.maxTokens, 128_000);
+});
+
+test("live-only reasoning models preserve default levels in sparse effort maps", async () => {
+ const binding = await liveCopilotBinding({
+ ...adaptiveSonnet,
+ thinkingLevelMap: { xhigh: "xhigh", max: "max" },
+ });
+ assert.deepEqual(binding.supportedThinkingLevels, [
+ "off", "minimal", "low", "medium", "high", "xhigh", "max",
+ ]);
+ assert.equal(clampThinkingLevel(binding, "high"), "high");
+});
+
+test("live-only models respect null-disabled levels and non-reasoning siblings", async () => {
+ const restricted = await liveCopilotBinding({
+ ...adaptiveSonnet,
+ thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null },
+ });
+ assert.deepEqual(restricted.supportedThinkingLevels, ["xhigh"]);
+ const nonReasoning = await liveCopilotBinding({ ...adaptiveSonnet, reasoning: false });
+ assert.equal(nonReasoning.supportsReasoning, false);
+ assert.deepEqual(nonReasoning.supportedThinkingLevels, ["off"]);
+});
+
+test("a live-only model without a same-tier sibling keeps generic capabilities", async () => {
+ const binding = await liveCopilotBinding(adaptiveSonnet, { modelId: "claude-haiku-99" });
+ assert.equal(binding.supportsReasoning, false);
+ assert.deepEqual(binding.supportedThinkingLevels, ["off"]);
+ assert.equal(binding.modelConfig.compat, undefined);
+ assert.equal(binding.modelConfig.thinkingLevelMap, undefined);
+});
+
+test("published model metadata takes precedence over the pinned sibling", async () => {
+ const published = {
+ ...genericModelConfig("claude-sonnet-99"),
+ source: "models.dev",
+ reasoning: true,
+ supportedThinkingLevels: ["low", "high"],
+ thinkingLevelMap: { low: "low", high: "high" },
+ thinkingProtocol: "legacy",
+ };
+ const binding = await liveCopilotBinding(adaptiveSonnet, { modelConfigFor: async () => published });
+ assert.deepEqual(binding.modelConfig, published);
+ assert.deepEqual(binding.supportedThinkingLevels, ["low", "high"]);
+});
+
+test("an explicit effort map on generic metadata governs the fallback's supported levels", async () => {
+ const config = {
+ ...genericModelConfig("claude-sonnet-99"),
+ thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: "high", xhigh: null, max: null },
+ compat: { forceAdaptiveThinking: false },
+ };
+ const binding = await liveCopilotBinding(adaptiveSonnet, { modelConfigFor: async () => config });
+ assert.equal(binding.modelConfig.compat.forceAdaptiveThinking, false);
+ assert.deepEqual(binding.modelConfig.thinkingLevelMap, config.thinkingLevelMap);
+ assert.deepEqual(binding.supportedThinkingLevels, ["high"]);
+});
+
+test("live-only Claude bindings send adaptive thinking with the requested wire effort", async () => {
+ const binding = await liveCopilotBinding({
+ ...adaptiveSonnet,
+ thinkingLevelMap: { off: null, minimal: null, xhigh: "xhigh", max: "max" },
+ });
+ const modelConfig = modelConfigWithBinding(binding.modelConfig);
+ const provider = {
+ ...binding,
+ modelConfig,
+ ...capabilitiesFromModelConfig(modelConfig),
+ id: "test-account-row",
+ name: "GitHub Copilot",
+ vendorKey: "github-copilot",
+ modelId: "claude-sonnet-99",
+ authKind: "oauth",
+ apiKey: "",
+ resolveAuth: async () => ({ apiKey: "test-copilot-access-token" }),
+ };
+ const model = buildProviderModel(provider);
+ const models = createProviderModels(provider, model);
+ for (const level of ["high", "xhigh", "max"]) {
+ let request;
+ const result = await models.streamSimple(model, {
+ messages: [{ role: "user", content: "fixture", timestamp: 1 }],
+ }, {
+ reasoning: clampThinkingLevel(provider, level),
+ maxRetries: 0,
+ fetch: async (input, init) => {
+ request = new Request(input, init);
+ return Response.json({ type: "error", error: { type: "invalid_request_error", message: "fixture response" } }, { status: 400 });
+ },
+ }).result();
+ assert.equal(result.stopReason, "error");
+ assert.ok(request, "the real adapter must reach the HTTP boundary");
+ const body = await request.json();
+ assert.equal(body.model, "claude-sonnet-99");
+ assert.equal(body.thinking.type, "adaptive");
+ assert.equal(body.output_config.effort, level);
+ assert.equal("budget_tokens" in body.thinking, false);
+ assert.equal(request.headers.get("Authorization"), "Bearer test-copilot-access-token");
+ assert.equal(request.headers.get("x-api-key"), null);
+ }
+});
+
+test("legacy thinking siblings are not implicitly promoted to adaptive", async () => {
+ const binding = await liveCopilotBinding({
+ ...adaptiveSonnet,
+ id: "claude-sonnet-4.5",
+ compat: undefined,
+ thinkingLevelMap: undefined,
+ });
+ assert.notEqual(binding.modelConfig.compat?.forceAdaptiveThinking, true);
+ assert.equal(binding.modelConfig.thinkingLevelMap, undefined);
+ assert.deepEqual(binding.supportedThinkingLevels, ["off", "minimal", "low", "medium", "high"]);
+});
+
+test("live-only thinking restrictions survive runtime launch without a saved model binding", async () => {
+ const disabled = { off: null, minimal: null, low: null, medium: null, high: null, xhigh: null, max: null };
+ for (const [sibling, expected] of [
+ [{ ...adaptiveSonnet, thinkingLevelMap: { ...disabled, high: "high" } }, { supportsReasoning: true, supportedThinkingLevels: ["high"] }],
+ [{ ...adaptiveSonnet, reasoning: false, thinkingLevelMap: undefined }, { supportsReasoning: false, supportedThinkingLevels: ["off"] }],
+ [{ ...adaptiveSonnet, thinkingLevelMap: disabled }, { supportsReasoning: false, supportedThinkingLevels: ["off"] }],
+ ]) {
+ const binding = await liveCopilotBinding(sibling);
+ const effective = modelConfigWithBinding(binding.modelConfig);
+ assert.deepEqual(capabilitiesFromModelConfig(effective), expected);
+ assert.deepEqual(effective.thinkingLevelMap, sibling.thinkingLevelMap);
+ }
});
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index cf31aefc8..83bfe30da 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -219,9 +219,11 @@ PI-Desktop must not permanently restrict users to a short fixed model list.
`last_updated`, `modalities.input/output`, `open_weights`,
`limit.context/input/output`, `cost`, `interleaved`, `status`,
`experimental`, and `provider` into the shared model surfaces.
-5. pi-ai remains only the request/OAuth implementation layer. Its bundled model
- catalog and model capability functions are not read for names, limits,
- pricing, modalities, reasoning, or other model configuration.
+5. pi-ai remains the request/OAuth implementation layer; published model
+ configuration comes from models.dev, not pi-ai's bundled catalog. The
+ bounded exception is the live-only OAuth same-tier fallback in §8a, which
+ borrows an existing adapter contract and interprets its effort mapping with
+ pi-ai's capability helper until published metadata becomes available.
6. Input and output modality arrays retain `text`, `image`, `audio`, `video`,
and `pdf`. The text agent picker exposes models that can handle text while
preserving all raw records in the file for future surfaces. Image input is
@@ -512,12 +514,24 @@ is the endpoint that vendor actually publishes:
- Radius keeps its gateway catalog refresh and is not probed again.
Image, video, speech and embedding ids are dropped. A model models.dev does
-not know yet inherits limits from a pinned sibling of the same tier; xAI uses
-an explicit newest-first sibling (`grok-4.7`, then `grok-4.6`, then
-`grok-4.5`, then `grok-4.3`) so pin order cannot select an older Grok. A different tier is not
-used. models.dev still cannot add an id the account list did not return. A
-vendor may span wire APIs — Copilot serves Anthropic, Chat Completions and
-Responses models — so the row's `apiStyle` follows the selected model.
+not know yet inherits limits, reasoning, adapter compatibility, and the wire
+effort mapping from a pinned sibling of the same tier; xAI uses an explicit
+newest-first sibling (`grok-4.7`, then `grok-4.6`, then `grok-4.5`, then
+`grok-4.3`) so pin order cannot select an older Grok. A different tier is not
+used. Existing model metadata takes precedence over borrowed compatibility and
+effort mappings. Supported thinking levels follow pi-ai's mapping contract:
+missing entries retain adapter defaults, `null` disables a level, and `xhigh`
+or `max` requires an explicit mapping. Non-reasoning siblings remain off-only.
+Without a stored user binding, runtime configuration preserves these inferred
+restrictions instead of reopening every generic thinking level. An all-disabled
+effort map remains non-reasoning. Truly unclassified generic models and explicit
+user overrides retain their existing effective-thinking policy.
+The same effective mapping determines both the supported levels and wire
+effort, so a sparse map cannot silently promote `high` to `xhigh` or lose the
+adaptive protocol. Published models.dev records bypass this fallback entirely.
+models.dev still cannot add an id the account list did not return. A vendor
+may span wire APIs — Copilot serves Anthropic, Chat Completions and Responses
+models — so the row's `apiStyle` follows the selected model.
Deleting a row calls the normal host `providers.delete` path, which removes its
OAuth secret and metadata; it never logs out or deletes another row with the
same vendor key.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d1a3fc9c9..4e66a5e01 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8551,19 +8551,30 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
the provider's configured base URL/API style. 3. Force a Settings catalog
refresh and confirm it refetches models.dev without changing the bundled
release file or writing a user cache. 4. Add an ID absent from models.dev
- and inspect its generic fallback card.
+ and inspect its generic fallback card. 5. In the OAuth protocol fixture,
+ sign in to an account that offers a new Claude ID absent from models.dev
+ but with a pinned same-tier sibling. Resolve its runtime binding, apply
+ runtime model configuration without a saved model binding, and send `high`,
+ `xhigh`, and `max` through the real Anthropic adapter to an intercepted HTTP
+ boundary. Repeat with null-disabled levels, an all-disabled map, a
+ non-reasoning sibling, and an ID with no same-tier sibling.
- **Expected**: models.dev fields prefill known model bindings and remain the
- sole metadata source. Provider keys are never included in the fixed
- models.dev request. Provider discovery remains available only to supply
- custom/account-specific IDs; those IDs receive the generic text-only,
- non-reasoning defaults. pi-ai supplies the selected transport and OAuth/account
- availability, not model metadata.
-- **Specs linked**: `03-runtime/11-provider-model-system.md` §6.2,
+ published metadata source. Provider keys are never included in the fixed
+ models.dev request. Custom IDs without metadata retain generic defaults.
+ An OAuth live-only ID may use the existing same-tier fallback: protocol
+ compatibility and effort mappings travel with borrowed reasoning. Requests
+ use adaptive thinking and the requested effort, without legacy token budgets;
+ sparse mappings retain defaults and explicit nulls remain unsupported. A
+ non-reasoning sibling remains off-only, and no same-tier sibling means no
+ inferred reasoning. Published metadata and explicit mapping/compatibility
+ values take precedence. Copilot Bearer authentication remains unchanged.
+- **Specs linked**: `03-runtime/11-provider-model-system.md` §6.2 and §8a,
`03-runtime/13-model-catalog-and-selection.md` §11.1–§12, ADR 0134
- **Acceptance**: B (model config), C (conversation & stream), Security
- **Milestone**: M6+
-- **Status**: Unit/source-contract covered; full provider-dialog journey Draft
- (run only in a capable environment when this surface changes)
+- **Status**: OAuth-to-runtime-binding-to-adapter HTTP contract automated in
+ `apps/desktop/test/vendor-oauth-login.test.mjs`. Full provider-dialog journey
+ Draft. No live account or paid provider request is required for this fixture.
#### E2E-NAV-plugins-button-goes-back: Plugins footer reuses navigation history
diff --git a/packages/agent-runtime/src/model-capabilities.ts b/packages/agent-runtime/src/model-capabilities.ts
index 0db1749c4..21f682c82 100644
--- a/packages/agent-runtime/src/model-capabilities.ts
+++ b/packages/agent-runtime/src/model-capabilities.ts
@@ -83,6 +83,12 @@ export function modelConfigWithBinding(
>
| null,
): ModelConfig {
+ // A live-only account model may already carry explicit sibling capabilities.
+ // Preserve those until a stored user binding overrides them; only a truly
+ // unclassified generic row needs the unrestricted defaults below.
+ if (!binding && (model.supportedThinkingLevels?.length || model.thinkingLevelMap)) {
+ return model;
+ }
// A generic discovery row carries no trusted capability restriction. Keep
// all levels selectable unless the user stored a non-empty override.
// This is an effective runtime policy, not published catalog metadata.