Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(ai): send x-opencode-session on OpenCode Go requests (#2146)
Lukas Buck0d46bcdeb262
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 795623ff7..269edceaa 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -33,6 +33,7 @@ import {} from "./ai/chatRequestBody";import { getModelFamilyConstraints } from "./ai/modelFamilyConstraints";import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";+import { openCodeSessionHeaders } from "./ai/openCodeSession";import { createStreamingThinkFilter } from "./ai/streamingThinkFilter";import { extractApiErrorMessage } from "./ai/apiErrorMessage";import { clearTinfoilClientCache } from "./ai/tinfoilClient";@@ -319,6 +320,9 @@ class ReasoningService extends BaseReasoningService {requestBody: JSON.stringify(requestBody).substring(0, 200),});+ // Minted before the retry loop so every attempt of this call is one conversation.+ const openCodeHeaders = openCodeSessionHeaders(endpoint);+const requestGeneration = this.requestCancellationGeneration;const response = await withRetry(async () => {if (requestGeneration !== this.requestCancellationGeneration) {@@ -331,6 +335,7 @@ class ReasoningService extends BaseReasoningService {try {const headers: Record<string, string> = {"Content-Type": "application/json",+ ...openCodeHeaders,};if (apiKey) {headers["Authorization"] = `Bearer ${apiKey}`;@@ -621,6 +626,7 @@ class ReasoningService extends BaseReasoningService {const headers: Record<string, string> = {"Content-Type": "application/json",+ ...openCodeSessionHeaders(endpoint),};if (apiKey) {headers["Authorization"] = `Bearer ${apiKey}`;diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.tsindex 03543a252..77c9373ed 100644--- a/src/services/ai/inferenceProviders/openai.ts+++ b/src/services/ai/inferenceProviders/openai.ts@@ -14,6 +14,7 @@ import { detectEndpointDialect } from "../thinkingSuppressionDialects";import { getLlmRequestTimeoutSeconds } from "../../../helpers/llmRequestTimeout.js";import { extractApiErrorMessage } from "../apiErrorMessage";import { wrapCleanupTranscript } from "../../../config/prompts";+import { openCodeSessionHeaders } from "../openCodeSession";const OPENAI_ENDPOINT_PREF_STORAGE_KEY = "openAiEndpointPreference";const PROBE_TIMEOUT_MS = 2_000;@@ -192,6 +193,9 @@ export const openaiProvider: InferenceProvider = {endpointCandidates = getEndpointCandidates(openAiBase);}const isCustomEndpoint = openAiBase !== API_ENDPOINTS.OPENAI_BASE;+ // One cleanup call is one conversation: every attempt below (endpoint+ // fallback, parameter fallback, retry) reuses the same session id.+ const openCodeHeaders = openCodeSessionHeaders(openAiBase);logger.logReasoning("OPENAI_ENDPOINTS", {base: openAiBase,@@ -261,6 +265,7 @@ export const openaiProvider: InferenceProvider = {headers: {"Content-Type": "application/json",...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),+ ...openCodeHeaders,},body: JSON.stringify(requestBody),signal: controller.signal,diff --git a/src/services/ai/openCodeSession.ts b/src/services/ai/openCodeSession.tsnew file mode 100644index 000000000..38a29b0b3--- /dev/null+++ b/src/services/ai/openCodeSession.ts@@ -0,0 +1,22 @@+import { matchesHost } from "../../utils/urlUtils";++const OPENCODE_HOST = "opencode.ai";+const SESSION_HEADER = "x-opencode-session";++/**+ * OpenCode Go routes each conversation by a stable `x-opencode-session` id and+ * rejects requests without one (HTTP 400 MissingSessionID). Recognised by host+ * so a custom base such as https://opencode.ai/zen/go/v1 gets the header.+ */+export function isOpenCodeBase(baseUrl: string | null | undefined): boolean {+ return matchesHost(baseUrl, OPENCODE_HOST);+}++/**+ * Session header for one unit of work. Mint it once per call and reuse the+ * result across that call's endpoint fallback, parameter fallback and retries —+ * they are the same conversation. Empty for every other host.+ */+export function openCodeSessionHeaders(baseUrl: string | null | undefined): Record<string, string> {+ return isOpenCodeBase(baseUrl) ? { [SESSION_HEADER]: crypto.randomUUID() } : {};+}diff --git a/src/services/ai/providers.ts b/src/services/ai/providers.tsindex baa9b844c..015720591 100644--- a/src/services/ai/providers.ts+++ b/src/services/ai/providers.ts@@ -5,6 +5,7 @@ import { createGoogleGenerativeAI } from "@ai-sdk/google";import type { LanguageModel } from "ai";import { getTinfoilLanguageModel } from "./tinfoilClient";import { API_ENDPOINTS } from "../../config/constants";+import { openCodeSessionHeaders } from "./openCodeSession";// Renderer-side AI SDK factory. Cloud + local only — enterprise providers// (bedrock/azure/vertex) run in the main process via the@@ -55,7 +56,12 @@ export async function getAIModel(return createOpenAI({ apiKey, baseURL: API_ENDPOINTS.CORTI_MODELS_BASE }).chat(model);case "custom":// Custom OpenAI-compatible servers implement Chat Completions, not the Responses API.- return createOpenAI({ apiKey, baseURL }).chat(model);+ // One model instance answers one turn, so its session header is that turn's.+ return createOpenAI({+ apiKey,+ baseURL,+ headers: openCodeSessionHeaders(baseURL),+ }).chat(model);case "openrouter":// OpenRouter implements Chat Completions, not the OpenAI Responses API.return createOpenAI({diff --git a/src/services/ai/thinkingSuppressionDialects.ts b/src/services/ai/thinkingSuppressionDialects.tsindex 654d67cf0..793eaf43f 100644--- a/src/services/ai/thinkingSuppressionDialects.ts+++ b/src/services/ai/thinkingSuppressionDialects.ts@@ -1,4 +1,5 @@import { getModelFamilyConstraints } from "./modelFamilyConstraints";+import { matchesHost } from "../../utils/urlUtils";/*** Per-provider dialects for turning a model's thinking off. Model-family@@ -15,23 +16,13 @@ export interface EndpointDialect {/** Custom endpoints that need their own request shape, recognised by host. */export function detectEndpointDialect(baseUrl: string | null | undefined): EndpointDialect | null {- if (!baseUrl) return null;-- let host: string;- try {- const normalized = baseUrl.includes("://") ? baseUrl : `https://${baseUrl}`;- host = new URL(normalized).hostname.toLowerCase();- } catch {- return null;- }-- if (host === "mistral.ai" || host.endsWith(".mistral.ai")) {+ if (matchesHost(baseUrl, "mistral.ai")) {return { key: "mistral", tokenParam: "max_tokens", supportsTemperature: true };}- if (host === "deepseek.com" || host.endsWith(".deepseek.com")) {+ if (matchesHost(baseUrl, "deepseek.com")) {return { key: "deepseek", tokenParam: "max_tokens", supportsTemperature: true };}- if (host === "cerebras.ai" || host.endsWith(".cerebras.ai")) {+ if (matchesHost(baseUrl, "cerebras.ai")) {return { key: "cerebras", tokenParam: "max_tokens", supportsTemperature: true };}diff --git a/src/utils/urlUtils.ts b/src/utils/urlUtils.tsindex 4dd63984b..ece2b3429 100644--- a/src/utils/urlUtils.ts+++ b/src/utils/urlUtils.ts@@ -59,6 +59,20 @@ export function isSecureHttpEndpoint(url: string): boolean {}}+// Scheme-less input is normalized to https so a bare "host/path" base still+// matches, and a subdomain counts as the same provider.+export function matchesHost(url: string | null | undefined, host: string): boolean {+ if (!url) return false;++ try {+ const normalized = url.includes("://") ? url : `https://${url}`;+ const hostname = new URL(normalized).hostname.toLowerCase();+ return hostname === host || hostname.endsWith(`.${host}`);+ } catch {+ return false;+ }+}+const AZURE_HOST_SUFFIXES = [".openai.azure.com",".cognitiveservices.azure.com",diff --git a/test/services/openCodeSession.test.js b/test/services/openCodeSession.test.jsnew file mode 100644index 000000000..328612de4--- /dev/null+++ b/test/services/openCodeSession.test.js@@ -0,0 +1,83 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const loadSession = () => import("../../src/services/ai/openCodeSession.ts");+const loadProviders = () => import("../../src/services/ai/providers.ts");++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++test("isOpenCodeBase recognises OpenCode hosts and nothing else", async () => {+ const { isOpenCodeBase } = await loadSession();++ assert.equal(isOpenCodeBase("https://opencode.ai/zen/go/v1"), true);+ assert.equal(isOpenCodeBase("https://api.opencode.ai/zen/go/v1"), true);+ assert.equal(isOpenCodeBase("HTTPS://OpenCode.AI/zen/go/v1"), true);+ assert.equal(isOpenCodeBase("opencode.ai/zen/go/v1"), true);++ // A lookalike host must not borrow the header (and the session id with it).+ assert.equal(isOpenCodeBase("https://opencode.ai.evil.com/v1"), false);+ assert.equal(isOpenCodeBase("https://notopencode.ai/v1"), false);+ assert.equal(isOpenCodeBase("https://api.openai.com/v1"), false);+ assert.equal(isOpenCodeBase("not a url"), false);+ assert.equal(isOpenCodeBase(""), false);+ assert.equal(isOpenCodeBase(null), false);+ assert.equal(isOpenCodeBase(undefined), false);+});++test("openCodeSessionHeaders mints one id per call and stays empty elsewhere", async () => {+ const { openCodeSessionHeaders } = await loadSession();++ assert.deepEqual(openCodeSessionHeaders("https://api.openai.com/v1"), {});+ assert.deepEqual(openCodeSessionHeaders(undefined), {});++ const first = openCodeSessionHeaders("https://opencode.ai/zen/go/v1");+ const second = openCodeSessionHeaders("https://opencode.ai/zen/go/v1");+ assert.match(first["x-opencode-session"], UUID_RE);+ // Separate units of work are separate conversations.+ assert.notEqual(first["x-opencode-session"], second["x-opencode-session"]);+});++/** Drains an AI SDK stream and returns the headers the transport actually sent. */+async function captureChatHeaders(t, baseUrl) {+ const { getAIModel } = await loadProviders();+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });++ let sent = null;+ globalThis.fetch = async (input, init = {}) => {+ sent = init.headers || {};+ const chunk = (delta, finishReason = null) =>+ `data: ${JSON.stringify({+ id: "chatcmpl-opencode-session-test",+ object: "chat.completion.chunk",+ created: 1,+ model: "kimi-k2.5",+ choices: [{ index: 0, delta, finish_reason: finishReason }],+ })}\n\n`;+ return new Response(`${chunk({ content: "ok" })}${chunk({}, "stop")}data: [DONE]\n\n`, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ };++ const model = await getAIModel("custom", "kimi-k2.5", "test-key", baseUrl);+ const { stream } = await model.doStream({+ prompt: [{ role: "user", content: [{ type: "text", text: "hello" }] }],+ });+ for await (const _part of stream) {+ // Drain so the request completes.+ }+ return sent;+}++test("the chat transport sends a session id to OpenCode Go", async (t) => {+ const sent = await captureChatHeaders(t, "https://opencode.ai/zen/go/v1");+ assert.match(sent["x-opencode-session"], UUID_RE);+});++test("the chat transport sends no session id to other custom endpoints", async (t) => {+ const sent = await captureChatHeaders(t, "https://responses-only.example/v1");+ assert.equal("x-opencode-session" in sent, false);+});diff --git a/test/services/openaiOpenCodeSession.test.js b/test/services/openaiOpenCodeSession.test.jsnew file mode 100644index 000000000..97e806514--- /dev/null+++ b/test/services/openaiOpenCodeSession.test.js@@ -0,0 +1,133 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/services/ai/inferenceProviders/openai.ts");++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++// openai.ts caches the winning endpoint per base in a module-level Map, so a base+// shared between tests would make them order-dependent: the first test's fallback+// pins "chat" and the next one never attempts /responses. One base per test.+const APEX_BASE = "https://opencode.ai/zen/go/v1";+const SUBDOMAIN_BASE = "https://api.opencode.ai/zen/go/v1";+const OTHER_BASE = "https://responses-only.example/v1";++function makeCtx() {+ return {+ getApiKey: async () => "test-key",+ getSystemPrompt: () => "Clean the transcript",+ getCustomDictionary: () => [],+ getPreferredLanguage: () => "en",+ getUiLanguage: () => "en",+ callChatCompletionsApi: async () => {+ throw new Error("Unexpected chat completions delegation");+ },+ calculateMaxTokens: () => 4096,+ };+}++/** Serve /models as unavailable, /responses as unsupported, /chat/completions as success. */+function installFetchRecorder(t, requests) {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async (input, init = {}) => {+ const endpoint = String(input);+ const method = init.method || "GET";+ requests.push({ method, endpoint, headers: init.headers || {} });++ if (method === "GET" && endpoint.endsWith("/models")) {+ return new Response(JSON.stringify({ error: { message: "unauthorized" } }), {+ status: 401,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (endpoint.endsWith("/responses")) {+ return new Response(JSON.stringify({ error: { message: "not found" } }), {+ status: 404,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (endpoint.endsWith("/chat/completions")) {+ return new Response(+ JSON.stringify({ choices: [{ message: { content: "Cleaned" }, finish_reason: "stop" }] }),+ { status: 200, headers: { "Content-Type": "application/json" } }+ );+ }+ throw new Error(`Unexpected request: ${method} ${endpoint}`);+ };+}++async function callWithBase(baseUrl) {+ const { openaiProvider } = await load();+ return openaiProvider.call({+ text: "Clean this transcript please",+ model: "kimi-k2.5",+ agentName: null,+ config: {+ provider: "custom",+ baseUrl,+ customApiKey: "test-key",+ systemPrompt: "Clean the transcript",+ },+ ctx: makeCtx(),+ });+}++const sessionIdsOf = (requests) =>+ requests.filter((r) => r.method === "POST").map((r) => r.headers["x-opencode-session"]);++test("OpenCode Go requests carry one stable x-opencode-session id per call", async (t) => {+ const requests = [];+ installFetchRecorder(t, requests);++ const result = await callWithBase(APEX_BASE);+ assert.equal(result, "Cleaned");++ const posts = requests.filter((r) => r.method === "POST");+ assert.deepEqual(+ posts.map((r) => r.endpoint),+ [`${APEX_BASE}/responses`, `${APEX_BASE}/chat/completions`]+ );+ const ids = sessionIdsOf(requests);+ assert.match(ids[0], UUID_RE);+ // The endpoint fallback belongs to the same conversation, so the id is reused.+ assert.equal(ids[1], ids[0]);+ assert.equal(posts[0].headers.Authorization, "Bearer test-key");+});++test("a second call is a new conversation with a different session id", async (t) => {+ const requests = [];+ installFetchRecorder(t, requests);++ await callWithBase(SUBDOMAIN_BASE);+ const firstCallIds = sessionIdsOf(requests);+ requests.length = 0;+ await callWithBase(SUBDOMAIN_BASE);+ const secondCallIds = sessionIdsOf(requests);++ // The first call pays the /responses fallback, so it proves per-call stability;+ // the second reuses the remembered endpoint and is a single request.+ assert.equal(firstCallIds.length, 2);+ assert.equal(new Set(firstCallIds).size, 1);+ assert.equal(new Set(secondCallIds).size, 1);+ assert.match(secondCallIds[0], UUID_RE);+ assert.notEqual(secondCallIds[0], firstCallIds[0]);+});++test("other custom endpoints do not get the OpenCode header", async (t) => {+ const requests = [];+ installFetchRecorder(t, requests);++ await callWithBase(OTHER_BASE);++ const posts = requests.filter((r) => r.method === "POST");+ assert.deepEqual(+ posts.map((r) => r.endpoint),+ [`${OTHER_BASE}/responses`, `${OTHER_BASE}/chat/completions`]+ );+ for (const r of posts) {+ assert.equal("x-opencode-session" in r.headers, false, `${r.endpoint} carried the header`);+ }+});diff --git a/test/services/reasoningServiceOpenCodeSession.test.js b/test/services/reasoningServiceOpenCodeSession.test.jsnew file mode 100644index 000000000..739e6723e--- /dev/null+++ b/test/services/reasoningServiceOpenCodeSession.test.js@@ -0,0 +1,97 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++async function loadReasoningService(t, cachePrefix) {+ installBrowserGlobals(t, {});+ const vite = await createRendererServer(t, { cachePrefix });+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });+ t.after(() => reasoningService.destroy());+ return reasoningService;+}++/** Captures the headers of the streaming POST and answers with a one-chunk SSE body. */+function installStreamRecorder(t, sent) {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async (input, init = {}) => {+ sent.push({ endpoint: String(input), headers: init.headers || {} });+ const event = `data: ${JSON.stringify({ choices: [{ delta: { content: "ok" } }] })}\n\n`;+ return new Response(`${event}data: [DONE]\n\n`, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ };+}++async function streamAgainst(reasoningService, lanUrl) {+ const stream = reasoningService.processTextStreaming(+ [{ role: "user", content: "hello" }],+ "kimi-k2.5",+ "lan",+ { systemPrompt: "Answer the user.", lanUrl }+ );+ let output = "";+ for await (const chunk of stream) output += chunk;+ return output;+}++test("self-hosted streaming sends a session id to OpenCode Go", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-opencode-stream-test-");+ const sent = [];+ installStreamRecorder(t, sent);++ assert.equal(await streamAgainst(reasoningService, "https://opencode.ai/zen/go/v1"), "ok");++ assert.equal(sent.length, 1);+ assert.equal(sent[0].endpoint, "https://opencode.ai/zen/go/v1/chat/completions");+ assert.match(sent[0].headers["x-opencode-session"], UUID_RE);+});++test("self-hosted streaming sends no session id to other endpoints", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-opencode-stream-other-test-");+ const sent = [];+ installStreamRecorder(t, sent);++ assert.equal(await streamAgainst(reasoningService, "http://127.0.0.1:11434/v1"), "ok");++ assert.equal(sent.length, 1);+ assert.equal("x-opencode-session" in sent[0].headers, false);+});++/** Captures the headers of the non-streaming POST and answers with a chat completion. */+function installCompletionRecorder(t, sent) {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async (input, init = {}) => {+ sent.push({ endpoint: String(input), headers: init.headers || {} });+ return new Response(+ JSON.stringify({ choices: [{ message: { content: "Cleaned" }, finish_reason: "stop" }] }),+ { status: 200, headers: { "Content-Type": "application/json" } }+ );+ };+}++test("self-hosted cleanup sends a session id to OpenCode Go", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-opencode-cleanup-test-");+ const sent = [];+ installCompletionRecorder(t, sent);++ const result = await reasoningService.processText("clean this up", "kimi-k2.5", null, {+ lanUrl: "https://opencode.ai/zen/go/v1",+ });++ assert.equal(result, "Cleaned");+ assert.equal(sent.length, 1);+ assert.equal(sent[0].endpoint, "https://opencode.ai/zen/go/v1/chat/completions");+ assert.match(sent[0].headers["x-opencode-session"], UUID_RE);+});