Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(llm): finish the reroute — Codex account header, one model per run

Etienne Lescotf7d0768079c3
diff --git a/electron/ai-edition/caption-translate.ts b/electron/ai-edition/caption-translate.ts
index 81f3639eb..02706aff4 100644
--- a/electron/ai-edition/caption-translate.ts
+++ b/electron/ai-edition/caption-translate.ts
@@ -12,8 +12,7 @@
// and shows the original text, which is the honest fallback for a partial run.
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
-import { createOpenScreenChatModel } from "./deep-agent/chat-model";
-import { extractDelta } from "./deep-agent/service";
+import { createOpenScreenChatModel, messageContentToText } from "./deep-agent/chat-model";
/** One transcript segment to translate. */
export interface CaptionTranslateSegment {
@@ -129,6 +128,28 @@ export async function translateCaptionSegments(
const out: Record<string, string> = {};
let done = 0;
+ // Built once, not per batch: for Copilot this call swaps the PAT for a
+ // runtime token over the network, and a long transcript is a lot of
+ // batches. ponytail: the Copilot runtime token is short-lived, so a
+ // translation running longer than its TTL would need a rebuild here.
+ let model: Awaited<ReturnType<typeof createOpenScreenChatModel>>;
+ try {
+ model = await createOpenScreenChatModel({
+ provider: options.provider,
+ model: options.model,
+ apiKey: options.apiKey,
+ baseUrl: options.baseUrl,
+ reasoningEffort: options.reasoningEffort,
+ accountId: options.accountId,
+ });
+ } catch (error) {
+ return {
+ success: false,
+ segments: out,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
for (let i = 0; i < segments.length; i += batchSize) {
if (options.signal?.aborted) {
return { success: false, segments: out, error: "Translation cancelled." };
@@ -136,14 +157,6 @@ export async function translateCaptionSegments(
const batch = segments.slice(i, i + batchSize);
let reply = "";
try {
- const model = await createOpenScreenChatModel({
- provider: options.provider,
- model: options.model,
- apiKey: options.apiKey,
- baseUrl: options.baseUrl,
- reasoningEffort: options.reasoningEffort,
- accountId: options.accountId,
- });
const result = await model.invoke(
[
new SystemMessage(SYSTEM_PROMPT),
@@ -151,7 +164,7 @@ export async function translateCaptionSegments(
],
{ signal: options.signal },
);
- reply = extractDelta(result.content);
+ reply = messageContentToText(result.content);
if (!reply) {
return {
success: false,
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index 25b53f5c7..d714258c6 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -695,8 +695,9 @@ async function tryCompactSession(opts: {
const prompt = buildCompactionPrompt(oldMessages);
let summary = "";
try {
- const { createOpenScreenChatModel } = await import("./deep-agent/chat-model");
- const { extractDelta } = await import("./deep-agent/service");
+ const { createOpenScreenChatModel, messageContentToText } = await import(
+ "./deep-agent/chat-model"
+ );
const chatModel = await createOpenScreenChatModel({
provider,
model,
@@ -709,7 +710,7 @@ async function tryCompactSession(opts: {
new SystemMessage(COMPACTION_SYSTEM_PROMPT),
new HumanMessage(prompt),
]);
- summary = extractDelta(result.content);
+ summary = messageContentToText(result.content);
if (!summary) {
return null;
}
diff --git a/electron/ai-edition/deep-agent/agent-provider-capabilities.test.ts b/electron/ai-edition/deep-agent/agent-provider-capabilities.test.ts
new file mode 100644
index 000000000..5d5090595
--- /dev/null
+++ b/electron/ai-edition/deep-agent/agent-provider-capabilities.test.ts
@@ -0,0 +1,96 @@
+// Covers the reasoning-effort matrix that survived the llm-call.ts deletion.
+// The deleted top-level agent-provider-capabilities.ts had the only tests for
+// this logic; these keep the per-provider wiring pinned.
+
+import { describe, expect, it } from "vitest";
+import {
+ buildLangChainReasoningOptions,
+ getReasoningCapability,
+ normalizeReasoningEffortForCapability,
+} from "./agent-provider-capabilities";
+
+describe("getReasoningCapability", () => {
+ it("gives openai-oauth the full 6-step Codex effort range", () => {
+ const cap = getReasoningCapability("openai-oauth", "gpt-5");
+ expect(cap.supported).toBe(true);
+ expect(cap.strategy).toBe("custom-openai-account");
+ expect(cap.efforts).toEqual(["none", "minimal", "low", "medium", "high", "xhigh"]);
+ });
+
+ it("turns reasoning off for non-reasoning OpenAI models", () => {
+ expect(getReasoningCapability("openai", "gpt-4o").supported).toBe(false);
+ expect(getReasoningCapability("openai", "o3-mini").supported).toBe(true);
+ expect(getReasoningCapability("openai", "gpt-5-mini").supported).toBe(true);
+ });
+
+ it("uses the thinking strategy for Anthropic 4.x and not for 3.x", () => {
+ expect(getReasoningCapability("anthropic", "claude-sonnet-4-5").strategy).toBe(
+ "anthropic-thinking",
+ );
+ expect(getReasoningCapability("anthropic", "claude-3-haiku-20240307").supported).toBe(false);
+ });
+
+ it("treats MiniMax thinking as binary, and Gemini 2.5+ as thinking-capable", () => {
+ expect(getReasoningCapability("minimax", "MiniMax-M3").strategy).toBe("minimax-thinking");
+ expect(getReasoningCapability("google", "gemini-2.5-pro").supported).toBe(true);
+ expect(getReasoningCapability("google", "gemini-1.5-pro").supported).toBe(false);
+ });
+
+ it("only supports OpenRouter reasoning for reasoning-capable slugs", () => {
+ expect(getReasoningCapability("openrouter", "anthropic/claude-3.5-sonnet").supported).toBe(
+ false,
+ );
+ expect(getReasoningCapability("openrouter", "openai/gpt-5").supported).toBe(true);
+ });
+
+ it("returns unsupported for unknown providers", () => {
+ expect(getReasoningCapability("nope", "x").supported).toBe(false);
+ expect(getReasoningCapability("").supported).toBe(false);
+ });
+});
+
+describe("normalizeReasoningEffortForCapability", () => {
+ it("collapses efforts the provider does not expose", () => {
+ const openai = getReasoningCapability("openai", "o4-mini");
+ expect(normalizeReasoningEffortForCapability("minimal", openai)).toBe("low");
+ expect(normalizeReasoningEffortForCapability("xhigh", openai)).toBe("high");
+ });
+
+ it("falls back to the default effort when none is selected", () => {
+ const openai = getReasoningCapability("openai", "o4-mini");
+ expect(normalizeReasoningEffortForCapability(undefined, openai)).toBe("medium");
+ });
+});
+
+describe("buildLangChainReasoningOptions", () => {
+ it("wires OpenAI effort through the Responses API", () => {
+ expect(buildLangChainReasoningOptions("openai", "o4-mini", "high")).toEqual({
+ reasoning: { effort: "high" },
+ useResponsesApi: true,
+ });
+ });
+
+ it("wires OpenRouter reasoning through modelKwargs", () => {
+ expect(buildLangChainReasoningOptions("openrouter", "openai/gpt-5", "medium")).toEqual({
+ modelKwargs: {
+ reasoning: { effort: "medium" },
+ include_reasoning: true,
+ },
+ });
+ });
+
+ it("wires Gemini thinking through thinkingConfig", () => {
+ const opts = buildLangChainReasoningOptions("google", "gemini-2.5-pro", "high");
+ expect(opts.thinkingConfig).toMatchObject({ includeThoughts: true, thinkingLevel: "HIGH" });
+ });
+
+ it("emits an Anthropic thinking block", () => {
+ const opts = buildLangChainReasoningOptions("anthropic", "claude-sonnet-4-5", "xhigh");
+ expect(opts.thinking).toBeDefined();
+ });
+
+ it("returns nothing when the effort is none or the provider has no reasoning", () => {
+ expect(buildLangChainReasoningOptions("openai", "o4-mini", "none")).toEqual({});
+ expect(buildLangChainReasoningOptions("mistral", "mistral-large-latest", "high")).toEqual({});
+ });
+});
diff --git a/electron/ai-edition/deep-agent/agent-provider-capabilities.ts b/electron/ai-edition/deep-agent/agent-provider-capabilities.ts
index 21467db95..b1e419fe8 100644
--- a/electron/ai-edition/deep-agent/agent-provider-capabilities.ts
+++ b/electron/ai-edition/deep-agent/agent-provider-capabilities.ts
@@ -54,6 +54,8 @@ const OPENROUTER_REASONING_EFFORTS: readonly AgentReasoningEffort[] = [
];
const GOOGLE_REASONING_EFFORTS: readonly AgentReasoningEffort[] = ["none", "low", "medium", "high"];
+// Every branch here compares against canonical registry ids —
+// createOpenScreenChatModel normalizes the provider before calling in.
export function getReasoningCapability(provider: string, model?: string): ReasoningCapability {
const def: ProviderDefinition | undefined = getProviderDefinition(provider);
const normalizedModel = normalizeModelName(model);
@@ -215,16 +217,18 @@ function isGeminiThinkingModel(model: string): boolean {
}
function isOpenRouterReasoningModel(model: string): boolean {
- if (isOpenAIReasoningModel(model)) return true;
- if (
- model.startsWith("anthropic/") &&
- isAnthropicReasoningModel(model.slice("anthropic/".length))
- ) {
- return true;
- }
+ // OpenRouter slugs are `vendor/model`, and both vendor matchers are
+ // anchored at the start — so the prefix has to come off first or
+ // `openai/gpt-5` never matches.
+ if (isOpenAIReasoningModel(stripVendorPrefix(model, "openai/"))) return true;
+ if (isAnthropicReasoningModel(stripVendorPrefix(model, "anthropic/"))) return true;
return /deepseek-r1/i.test(model) || /qwen.*thinking/i.test(model) || /grok-4/i.test(model);
}
+function stripVendorPrefix(model: string, prefix: string): string {
+ return model.startsWith(prefix) ? model.slice(prefix.length) : model;
+}
+
function toOpenAIReasoningEffort(effort: AgentReasoningEffort): "low" | "medium" | "high" {
if (effort === "high" || effort === "xhigh") return "high";
if (effort === "medium") return "medium";
diff --git a/electron/ai-edition/deep-agent/chat-model.test.ts b/electron/ai-edition/deep-agent/chat-model.test.ts
new file mode 100644
index 000000000..0efcaf20e
--- /dev/null
+++ b/electron/ai-edition/deep-agent/chat-model.test.ts
@@ -0,0 +1,98 @@
+// The Codex account header and the provider-alias normalization are both
+// invisible to tsc (an optional field that nothing reads still typechecks),
+// so they get a runtime check.
+
+import { describe, expect, it, vi } from "vitest";
+import { createOpenScreenChatModel, messageContentToText } from "./chat-model";
+
+vi.mock("../llm-provider-auth", () => ({
+ exchangeGithubCopilotRuntimeToken: vi.fn(async () => ({
+ token: "runtime-token",
+ expiresAt: Date.now() + 60_000,
+ baseUrl: "https://api.business.githubcopilot.com",
+ })),
+ GITHUB_COPILOT_USER_AGENT: "GitHubCopilotChat/0.26.7",
+ GITHUB_COPILOT_EDITOR_VERSION: "vscode/1.96.2",
+ GITHUB_COPILOT_PLUGIN_VERSION: "copilot-chat/0.26.7",
+}));
+
+/** ChatOpenAI keeps the `configuration` bag it was constructed with on
+ * `clientConfig`; that is where the base URL and default headers land. */
+function clientConfig(model: unknown): Record<string, unknown> {
+ return (model as { clientConfig?: Record<string, unknown> }).clientConfig ?? {};
+}
+
+describe("createOpenScreenChatModel — openai-oauth (Codex)", () => {
+ it("sends chatgpt-account-id, which the gateway requires for an OAuth token", async () => {
+ const model = await createOpenScreenChatModel({
+ provider: "openai-oauth",
+ model: "gpt-5",
+ apiKey: "oauth-access-token",
+ accountId: "acct_123",
+ });
+ expect(clientConfig(model).defaultHeaders).toMatchObject({
+ "chatgpt-account-id": "acct_123",
+ });
+ });
+
+ it("omits the header entirely when there is no account id", async () => {
+ const model = await createOpenScreenChatModel({
+ provider: "openai-oauth",
+ model: "gpt-5",
+ apiKey: "oauth-access-token",
+ });
+ expect(clientConfig(model).defaultHeaders).toBeUndefined();
+ });
+});
+
+describe("createOpenScreenChatModel — copilot-proxy", () => {
+ it("uses the exchanged runtime token and the base URL it names", async () => {
+ const model = await createOpenScreenChatModel({
+ provider: "copilot-proxy",
+ model: "gpt-4.1",
+ apiKey: "github-pat",
+ });
+ expect(clientConfig(model).baseURL).toBe("https://api.business.githubcopilot.com");
+ expect(clientConfig(model).defaultHeaders).toMatchObject({
+ "Editor-Version": "vscode/1.96.2",
+ "Openai-Intent": "copilot-gpt-chat-completions",
+ });
+ });
+});
+
+describe("createOpenScreenChatModel — provider aliases", () => {
+ it("routes the `claude` alias to the Anthropic SDK, not the OpenAI fallback", async () => {
+ const model = await createOpenScreenChatModel({
+ provider: "claude",
+ model: "claude-sonnet-4-5",
+ apiKey: "sk-ant-test",
+ });
+ expect(model.constructor.name).toBe("ChatAnthropic");
+ });
+
+ it("routes the `gemini` alias to the Google OpenAI-compat base URL", async () => {
+ const model = await createOpenScreenChatModel({
+ provider: "gemini",
+ model: "gemini-2.5-pro",
+ apiKey: "test-key",
+ });
+ expect(clientConfig(model).baseURL).toBe(
+ "https://generativelanguage.googleapis.com/v1beta/openai",
+ );
+ });
+});
+
+describe("messageContentToText", () => {
+ it("passes a plain string through", () => {
+ expect(messageContentToText("hello")).toBe("hello");
+ });
+
+ it("concatenates the text parts of a content array and skips non-text", () => {
+ expect(messageContentToText(["a", { type: "text", text: "b" }, { type: "image" }])).toBe("ab");
+ });
+
+ it("returns an empty string for anything else", () => {
+ expect(messageContentToText(null)).toBe("");
+ expect(messageContentToText(42)).toBe("");
+ });
+});
diff --git a/electron/ai-edition/deep-agent/chat-model.ts b/electron/ai-edition/deep-agent/chat-model.ts
index d62d0d754..3d9ddf7a4 100644
--- a/electron/ai-edition/deep-agent/chat-model.ts
+++ b/electron/ai-edition/deep-agent/chat-model.ts
@@ -14,6 +14,7 @@ import {
GITHUB_COPILOT_PLUGIN_VERSION,
GITHUB_COPILOT_USER_AGENT,
} from "../llm-provider-auth";
+import { normalizeProviderId } from "../provider-registry";
import {
buildLangChainReasoningOptions,
shouldDisableModelStreamingForToolCalling,
@@ -37,9 +38,39 @@ export function resolveOpenAIChatApiKey(provider: string, apiKey?: string): stri
return provider === "openai-compatible" ? OPENAI_COMPATIBLE_NO_AUTH_API_KEY : undefined;
}
+/** Flattens LangChain MessageContent (a string, or an array of text and
+ * non-text parts) down to plain text. Lives here rather than in
+ * deep-agent/service.ts so the one-shot prompt→text callers can reach it
+ * without dragging the agent tool graph in behind it. */
+export function messageContentToText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ let total = "";
+ for (const part of content) {
+ if (typeof part === "string") {
+ total += part;
+ } else if (part && typeof part === "object") {
+ const text = (part as { text?: unknown }).text;
+ if (typeof text === "string") total += text;
+ }
+ }
+ return total;
+ }
+ return "";
+}
+
export async function createOpenScreenChatModel(
- config: OpenScreenChatModelConfig,
+ input: OpenScreenChatModelConfig,
): Promise<BaseChatModel> {
+ // Canonicalise once, here: stored configs can still carry historical
+ // aliases (`claude`, `gemini`, `anthropic-proxy`), and every provider
+ // comparison below — and in agent-provider-capabilities — is an exact
+ // match against a registry id.
+ const config: OpenScreenChatModelConfig = {
+ ...input,
+ provider: normalizeProviderId(input.provider) ?? input.provider,
+ };
+
const reasoningOptions = buildLangChainReasoningOptions(
config.provider,
config.model,
@@ -114,11 +145,19 @@ async function createLocalProviderChatModel(
// ChatCodexOAuth class for this; for v1 we fall back to a generic
// ChatOpenAI with the chatgpt.com/backend-api base URL. Streaming
// + tool calls work on the gateway, so this is enough for the chat.
+ // `chatgpt-account-id` is not optional — the gateway rejects an
+ // OAuth token without the account it was minted for. The rest of
+ // the Codex header set (originator, x-codex-window-id, the
+ // OpenAI-Beta Responses opt-in) belongs to the Responses dialect
+ // this path does not speak; add it with a real ChatCodexOAuth.
return new ChatOpenAI({
apiKey: config.apiKey,
model: config.model,
configuration: {
baseURL: config.baseUrl || "https://chatgpt.com/backend-api",
+ ...(config.accountId
+ ? { defaultHeaders: { "chatgpt-account-id": config.accountId } }
+ : {}),
},
});
case "copilot-proxy": {
diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts
index 5f0f99b85..c8db1016c 100644
--- a/electron/ai-edition/deep-agent/service.ts
+++ b/electron/ai-edition/deep-agent/service.ts
@@ -28,7 +28,11 @@ import {
setTrimArgs,
setZoomArgs,
} from "../agent-tools";
-import { createOpenScreenChatModel, type OpenScreenChatModelConfig } from "./chat-model";
+import {
+ createOpenScreenChatModel,
+ messageContentToText,
+ type OpenScreenChatModelConfig,
+} from "./chat-model";
export interface OpenScreenAgentSink {
text: (delta: string) => void;
@@ -229,7 +233,7 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
const chunk = data?.chunk as Record<string, unknown> | undefined;
if (chunk) chatModelChunks.push(chunk);
const content = chunk?.content;
- const delta = extractDelta(content);
+ const delta = messageContentToText(content);
if (delta) {
sink.text(delta);
finalText += delta;
@@ -253,7 +257,8 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
// The chat-model chunks are the post-parse LangChain views of
// each SSE event; their `content`/`additional_kwargs`/
// `response_metadata` fields tell us whether the issue is in the
- // wire format, the parser, or our `extractDelta` shape. Capped at
+ // wire format, the parser, or our `messageContentToText` shape.
+ // Capped at
// 1 chunk + a 1kB slice to keep the toast readable.
const lastChunk = chatModelChunks[chatModelChunks.length - 1];
const sample = lastChunk
@@ -297,25 +302,6 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
}
}
-/** Flattens LangChain MessageContent (a string, or an array of text and
- * non-text parts) down to plain text. */
-export function extractDelta(content: unknown): string {
- if (typeof content === "string") return content;
- if (Array.isArray(content)) {
- let total = "";
- for (const part of content) {
- if (typeof part === "string") {
- total += part;
- } else if (part && typeof part === "object") {
- const text = (part as { text?: unknown }).text;
- if (typeof text === "string") total += text;
- }
- }
- return total;
- }
- return "";
-}
-
function extractError(data: Record<string, unknown> | undefined): string | undefined {
if (!data) return undefined;
const error = data.error;