Skip to content

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

fix(oauth): log a redacted response excerpt when a model list fails

aharond16aadb4994d
diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.ts
index 783fe2dcb..54f57ca5d 100644
--- a/apps/desktop/electron/main/oauth.ts
+++ b/apps/desktop/electron/main/oauth.ts
@@ -46,6 +46,7 @@ import {
parseVendorModelIds,
pinnedSiblingId,
readVendorModelList,
+ VendorModelListError,
vendorModelListRequest,
wireForLiveModel,
} from "./vendor-live-models.ts";
@@ -534,6 +535,9 @@ export class VendorOAuth {
this.log("warn", "vendor account model list failed", {
vendorId: account.vendorId,
message: error instanceof Error ? error.message : String(error),
+ ...(error instanceof VendorModelListError
+ ? { status: error.status, responseExcerpt: error.responseExcerpt }
+ : {}),
});
return this.rememberLiveModels(account.providerId, null);
}
diff --git a/apps/desktop/electron/main/vendor-live-models.ts b/apps/desktop/electron/main/vendor-live-models.ts
index f96c64821..d366928d3 100644
--- a/apps/desktop/electron/main/vendor-live-models.ts
+++ b/apps/desktop/electron/main/vendor-live-models.ts
@@ -8,6 +8,7 @@
const LIVE_MODELS_TIMEOUT_MS = 8_000;
const MAX_RETRY_DELAY_MS = 1_000;
+const MAX_ERROR_EXCERPT_CHARS = 300;
/**
* `client_version` sent to ChatGPT's `GET /codex/models`.
@@ -369,6 +370,67 @@ function retryDelayMs(response: Response): number {
return Math.min(delay, MAX_RETRY_DELAY_MS);
}
+/** A non-2xx model-list response. `responseExcerpt` is safe to log. */
+export class VendorModelListError extends Error {
+ readonly status: number;
+ readonly responseExcerpt: string | undefined;
+
+ constructor(status: number, responseExcerpt: string | undefined) {
+ super(`model list request failed (${status})`);
+ this.name = "VendorModelListError";
+ this.status = status;
+ this.responseExcerpt = responseExcerpt;
+ }
+}
+
+const CREDENTIAL_HEADER = /^(?:authorization|x-api-key)$/i;
+const BEARER_VALUE = /\b(?:bearer|basic)\s+[A-Za-z0-9+/_=.~-]+/gi;
+const JWT_VALUE = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
+const REDACTED = "***REDACTED***";
+
+function requestCredentials(headers: Record<string, string>): string[] {
+ return Object.entries(headers).flatMap(([name, value]) => {
+ if (!CREDENTIAL_HEADER.test(name)) return [];
+ const secret = value.replace(/^(?:bearer|basic)\s+/i, "").trim();
+ return secret.length >= 8 ? [secret] : [];
+ });
+}
+
+/**
+ * Short, single-line excerpt of an error body with the request's own
+ * credentials and anything token-shaped removed, so a failure can be
+ * diagnosed from the log without leaking the account token.
+ */
+export function summarizeErrorBody(
+ body: string,
+ headers: Record<string, string>,
+): string | undefined {
+ let text = body;
+ for (const secret of requestCredentials(headers)) {
+ text = text.split(secret).join(REDACTED);
+ }
+ text = text
+ .replace(BEARER_VALUE, (match) => `${match.split(/\s+/, 1)[0]} ${REDACTED}`)
+ .replace(JWT_VALUE, REDACTED)
+ .replace(/\s+/g, " ")
+ .trim();
+ if (!text) return undefined;
+ return text.length > MAX_ERROR_EXCERPT_CHARS
+ ? `${text.slice(0, MAX_ERROR_EXCERPT_CHARS)}…`
+ : text;
+}
+
+async function errorExcerpt(
+ response: Response,
+ headers: Record<string, string>,
+): Promise<string | undefined> {
+ try {
+ return summarizeErrorBody(await response.text(), headers);
+ } catch {
+ return undefined;
+ }
+}
+
/** GET the vendor model list. Retries one HTTP 429, then throws. */
export async function readVendorModelList(
request: VendorModelListRequest,
@@ -392,7 +454,10 @@ export async function readVendorModelList(
continue;
}
if (!response.ok) {
- throw new Error(`model list request failed (${response.status})`);
+ throw new VendorModelListError(
+ response.status,
+ await errorExcerpt(response, request.headers),
+ );
}
return await response.json();
} finally {
diff --git a/apps/desktop/test/vendor-live-models.test.mjs b/apps/desktop/test/vendor-live-models.test.mjs
index 6fe7cc027..1cf918f1c 100644
--- a/apps/desktop/test/vendor-live-models.test.mjs
+++ b/apps/desktop/test/vendor-live-models.test.mjs
@@ -3,8 +3,10 @@ import test from "node:test";
import {
CODEX_MODELS_CLIENT_VERSION,
+ VendorModelListError,
parseVendorModelIds,
pinnedSiblingId,
+ readVendorModelList,
vendorModelListRequest,
wireForLiveModel,
} from "../electron/main/vendor-live-models.ts";
@@ -114,3 +116,34 @@ test("Copilot only keeps a new id when its family has one wire API", () => {
);
});
+test("a failed model list keeps a token-free excerpt of the response body", async () => {
+ const token = codexToken();
+ const request = vendorModelListRequest({ vendorId: "openai-codex", apiKey: token });
+ const body = JSON.stringify({
+ detail: [{ loc: ["query", "client_version"], msg: "Field required" }],
+ echoed: `Bearer ${token}`,
+ raw: token,
+ other: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.c2ln",
+ padding: "x".repeat(2_000),
+ });
+ const fetchImpl = async () => new Response(body, { status: 400 });
+ const error = await readVendorModelList(request, fetchImpl).catch((caught) => caught);
+ assert.ok(error instanceof VendorModelListError);
+ assert.equal(error.status, 400);
+ assert.equal(error.message, "model list request failed (400)");
+ assert.match(error.responseExcerpt, /client_version/);
+ assert.match(error.responseExcerpt, /Field required/);
+ assert.equal(error.responseExcerpt.includes(token), false);
+ assert.equal(error.responseExcerpt.includes(token.split(".")[1]), false);
+ assert.equal(error.responseExcerpt.includes("eyJhbGciOiJIUzI1NiJ9"), false);
+ assert.ok(error.responseExcerpt.length <= 301);
+});
+
+test("a failed model list with an empty body has no excerpt", async () => {
+ const request = vendorModelListRequest({ vendorId: "xai", apiKey: "xai-token-123456" });
+ const fetchImpl = async () => new Response("", { status: 503 });
+ const error = await readVendorModelList(request, fetchImpl).catch((caught) => caught);
+ assert.ok(error instanceof VendorModelListError);
+ assert.equal(error.status, 503);
+ assert.equal(error.responseExcerpt, undefined);
+});
diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjs
index 212c94ad4..65246971d 100644
--- a/apps/desktop/test/vendor-oauth-login.test.mjs
+++ b/apps/desktop/test/vendor-oauth-login.test.mjs
@@ -170,6 +170,7 @@ function harness(options = {}) {
return fakeModels(store, options);
},
modelConfigFor: options.modelConfigFor,
+ log: options.log,
newId: () => `id-${++counter}`,
fetch:
options.fetch ??
@@ -834,3 +835,32 @@ test("a ChatGPT account lists the models /codex/models returns for its client ve
assert.equal(binding.baseUrl, "https://chatgpt.com/backend-api");
});
+test("a failed ChatGPT model list logs the status and a token-free response excerpt", async () => {
+ const logs = [];
+ const code = codexLoginCode();
+ const fetchModels = async () => new Response(JSON.stringify({
+ detail: [{ loc: ["query", "client_version"], msg: "Field required" }],
+ echoed: `access-for-${code}`,
+ }), { status: 400 });
+ const { host, events, oauth } = harness({
+ fetch: fetchModels,
+ log: (level, message, data) => logs.push({ level, message, data }),
+ provider: codexProvider(),
+ models: [codexModel("gpt-6-luna")],
+ });
+ const { loginId } = await oauth.start("openai-codex");
+ const prompt = await waitFor(events, "prompt");
+ oauth.respond({ loginId, promptId: prompt.request.promptId, value: code });
+ const done = await waitFor(events, "done");
+ // pi-ai's pinned list is still the fallback.
+ assert.deepEqual(host.providers.get(done.providerId).models.map((model) => model.id), ["gpt-6-luna"]);
+ const failed = logs.find((entry) => entry.message === "vendor account model list failed");
+ assert.ok(failed, `no model list failure log; saw ${logs.map((entry) => entry.message).join(", ")}`);
+ assert.equal(failed.level, "warn");
+ assert.equal(failed.data.vendorId, "openai-codex");
+ assert.equal(failed.data.status, 400);
+ assert.match(failed.data.responseExcerpt, /client_version/);
+ const logged = JSON.stringify(logs);
+ assert.equal(logged.includes(code), false);
+ assert.equal(logged.includes(code.split(".")[1]), false);
+});
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index adbf1a411..120786444 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -514,6 +514,11 @@ is the endpoint that vendor actually publishes:
for Kimi). xAI still drops image and video generators.
- Radius keeps its gateway catalog refresh and is not probed again.
+A failed account request logs the HTTP status and a short, single-line
+excerpt of the response body with the request's credentials and any
+token-shaped value removed, so an upstream contract change is diagnosable
+from the provider log.
+
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
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index 4c0d3ed3c..dbe07a1dd 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -415,6 +415,8 @@ Codex CLI 版本(`CODEX_MODELS_CLIENT_VERSION`),账户模型缺失时调
只有在其家族已经对应唯一线路 API 时才加入。Anthropic 用 OAuth 身份头请求
`GET {base}/v1/models`。Kimi、Meta、xAI、OpenRouter 请求 `GET {base}/models`
(Kimi 走 Anthropic 风格的 `/v1`)。Radius 继续用网关目录刷新,不再另打一遍。
+账户请求失败时,日志记录 HTTP 状态码和一小段单行的响应内容摘要,其中去掉了
+请求自身的凭据和任何形似令牌的值,便于从提供商日志诊断上游契约变化。
图像、视频、语音和嵌入模型会被丢掉。models.dev 不认识的 id 只从同档位的 pin
兄弟继承限额,xAI 按 `grok-4.7`、`grok-4.6`、`grok-4.5`、`grok-4.3` 的固定新到旧顺序,
不按 pin 顺序。models.dev 不能把账户列表里没有的 id 加进去。一个厂商可以