Compare commits

..
Author SHA1 Message Date
陈大猫 3260bf4206 fix(electron): isolate unpackaged app profiles 2026-11-18 14:05:02 +08:00
13 changed files with 95 additions and 312 deletions

No files matched your search

@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
if (!result.ok) {
if (discoveryKeyRef.current !== requestKey) return;
+20
View File
@@ -0,0 +1,20 @@
const fs = require("node:fs");
const path = require("node:path");
function configureAppProfile(app, devServerUrl) {
const unpackaged = !app.isPackaged;
const isDev = unpackaged && Boolean(devServerUrl);
if (unpackaged) {
// Keep the existing development profile path for both Vite and dist.
app.setName("Netcatty Dev");
const devProfile = path.join(app.getPath("userData"), "dev");
fs.mkdirSync(devProfile, { recursive: true });
app.setPath("userData", devProfile);
// Chromium's Local Storage, IndexedDB and other session state must
// follow the profile even if Electron has already resolved sessionData.
app.setPath("sessionData", devProfile);
}
return { isDev, effectiveDevServerUrl: isDev ? devServerUrl : undefined };
}
module.exports = { configureAppProfile };
+51
View File
@@ -0,0 +1,51 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { test } = require("node:test");
const { configureAppProfile } = require("./appProfile.cjs");
function fakeApp(t, isPackaged) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-profile-"));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
const production = path.join(tmp, "netcatty");
const paths = { userData: production, sessionData: production };
const app = {
isPackaged,
name: "Netcatty",
setName(name) { this.name = name; },
getPath(name) { return paths[name]; },
setPath(name, value) {
assert.ok(fs.statSync(value).isDirectory());
paths[name] = value;
},
};
return { app, paths, production };
}
test("unpackaged dist launches isolate both application and Chromium state", (t) => {
const { app, paths, production } = fakeApp(t, false);
assert.deepEqual(configureAppProfile(app, undefined), {
isDev: false, effectiveDevServerUrl: undefined,
});
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
assert.equal(app.name, "Netcatty Dev");
});
test("Vite launches keep the development profile and URL", (t) => {
const { app, paths, production } = fakeApp(t, false);
const url = "http://localhost:5173";
assert.deepEqual(configureAppProfile(app, url), { isDev: true, effectiveDevServerUrl: url });
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
});
test("packaged launches keep their data paths and ignore a Vite URL", (t) => {
const { app, paths, production } = fakeApp(t, true);
assert.deepEqual(configureAppProfile(app, "http://localhost:5173"), {
isDev: false, effectiveDevServerUrl: undefined,
});
assert.deepEqual(paths, { userData: production, sessionData: production });
assert.equal(app.name, "Netcatty");
});
+4 -9
View File
@@ -88,6 +88,10 @@ const path = require("node:path");
const os = require("node:os");
const fs = require("node:fs");
const { execFile } = require("node:child_process");
// Separate profile selection from renderer loading. In particular, source
// builds serving dist/ still need a non-production profile.
const { configureAppProfile } = require("./appProfile.cjs");
const { isDev, effectiveDevServerUrl } = configureAppProfile(app, process.env.VITE_DEV_SERVER_URL);
const { getCliDiscoveryFilePath } = require("./cli/discoveryPath.cjs");
const {
SSH_DEEP_LINK_CHANNEL,
@@ -291,15 +295,6 @@ app.on("web-contents-created", (_event, contents) => {
});
});
// Application configuration
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
// Never treat a packaged app as "dev" even if the user has VITE_DEV_SERVER_URL set globally.
const isDev = !app.isPackaged && !!devServerUrl;
const effectiveDevServerUrl = isDev ? devServerUrl : undefined;
if (isDev) {
app.setName("Netcatty Dev");
app.setPath("userData", path.join(app.getPath("userData"), "dev"));
}
const { applyPortableDataDirectory } = require("./portableData.cjs");
const portableData = applyPortableDataDirectory({ app });
if (portableData) {
@@ -71,19 +71,3 @@ test("normalizeAnthropicSdkBaseURL preserves custom non-/v1 path prefixes", () =
"https://gateway.example/api/v1",
);
});
test("normalizes the official Ark Agent Plan Anthropic prefix only", () => {
const base = "https://ark.cn-beijing.volces.com/api/plan";
for (const input of [base, base + "/", " " + base + " ", base + "/v1", base + "/v1/"]) {
assert.equal(normalizeAnthropicSdkBaseURL(input), base + "/v1");
}
for (const input of [
base.replace("https:", "http:"),
base.replace(".com", ".com.example"),
base.replace(".com", ".com:8443"),
base + "/custom",
"https://gateway.example/api/plan",
]) {
assert.equal(normalizeAnthropicSdkBaseURL(input), input);
}
});
@@ -39,7 +39,6 @@ export function isBareOriginBaseURL(baseURL: string): boolean {
* Normalize a stored Anthropic-compat Base URL for @ai-sdk/anthropic.
* - Bare hosts gain a /v1 suffix (Claude Code style → SDK style).
* - Bases that already end in /v1 are left unchanged.
* - The official Ark Agent Plan /api/plan prefix gains a /v1 suffix.
* - Other path prefixes (custom proxies) are left unchanged so chat keeps
* requesting `{prefix}/messages` rather than `{prefix}/v1/messages`.
*/
@@ -47,9 +46,6 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string {
const trimmed = stripTrailingSlashes(baseURL);
if (!trimmed) return trimmed;
if (anthropicBaseIncludesV1(trimmed)) return trimmed;
// Claude Code appends /v1/messages to the documented Ark Agent Plan base.
// The Anthropic SDK appends only /messages, so supply the missing /v1.
if (trimmed === "https://ark.cn-beijing.volces.com/api/plan") return `${trimmed}/v1`;
if (!isBareOriginBaseURL(trimmed)) return trimmed;
return `${trimmed}/v1`;
}
+1 -6
View File
@@ -142,12 +142,7 @@ export async function fetchProviderModelCatalog(
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, endpoint);
const headers = buildModelDiscoveryHeaders(
style,
apiKey,
await decryptProviderHeaders(provider.customHeaders),
baseURL,
);
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders));
const result = await bridge.aiFetch(
url,
'GET',
@@ -1,34 +1,13 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildModelDiscoveryHeaders,
isCustomAnthropicBaseURL,
resolveModelsDiscoveryEndpoint,
} from "./modelDiscoveryHeaders";
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from "./modelDiscoveryHeaders";
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version only on official anthropic host", () => {
for (const baseURL of [undefined, "", "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
"x-api-key": "sk-test",
"anthropic-version": "2023-06-01",
});
assert.equal(isCustomAnthropicBaseURL(baseURL), false);
}
});
test("buildModelDiscoveryHeaders sends both x-api-key and Bearer auth on custom anthropic bases", () => {
for (const baseURL of [
"https://ark.cn-beijing.volces.com/api/plan",
"https://gateway.example/v1",
]) {
assert.equal(isCustomAnthropicBaseURL(baseURL), true);
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
"x-api-key": "sk-test",
Authorization: "Bearer sk-test",
"anthropic-version": "2023-06-01",
});
}
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version for the anthropic family", () => {
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test"), {
"x-api-key": "sk-test",
"anthropic-version": "2023-06-01",
});
});
test("buildModelDiscoveryHeaders uses Bearer auth for the openai-compatible family", () => {
@@ -86,16 +65,4 @@ test('custom discovery headers override default auth regardless of case', () =>
assert.equal(Object.keys(headers).filter(key => key.toLowerCase() === name.toLowerCase()).length, 1);
assert.equal(headers['X-Tenant'], 'tenant');
}
const customAnthropicAuth = buildModelDiscoveryHeaders(
'anthropic',
'default-key',
{ authorization: 'Bearer custom-token' },
'https://ark.cn-beijing.volces.com/api/plan',
);
assert.deepEqual(customAnthropicAuth, {
'x-api-key': 'default-key',
'anthropic-version': '2023-06-01',
authorization: 'Bearer custom-token',
});
});
+2 -23
View File
@@ -27,27 +27,11 @@ export function resolveModelsDiscoveryEndpoint(
return STYLE_DEFAULT_MODELS_ENDPOINT[style] ?? presetEndpoint;
}
/**
* True when `baseURL` is a valid URL whose host is not the official
* `api.anthropic.com` endpoint. Omitted or blank values default to the
* official host and return `false`.
*/
export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
const trimmed = baseURL?.trim();
if (!trimmed) return false;
try {
return new URL(trimmed).hostname.toLowerCase() !== "api.anthropic.com";
} catch {
return false;
}
}
/**
* Pick auth headers for a provider's `/models` discovery endpoint.
*
* Each wire-protocol family uses its own auth dialect:
* - `anthropic`: `x-api-key` + `anthropic-version` on official `api.anthropic.com`;
* custom Anthropic-compatible gateways also receive `Authorization: Bearer ...`
* - `anthropic`: `x-api-key` + `anthropic-version`
* - `google`: `x-goog-api-key` (Google Generative AI rejects Bearer)
* - `openai`: `Authorization: Bearer …` (also the OpenAI-compat default)
*
@@ -57,16 +41,12 @@ export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
function buildDefaultModelDiscoveryHeaders(
style: ProviderStyle,
apiKey: string | undefined,
baseURL?: string,
): Record<string, string> {
if (!apiKey) return {};
switch (style) {
case "anthropic":
return {
"x-api-key": apiKey,
...(isCustomAnthropicBaseURL(baseURL)
? { Authorization: `Bearer ${apiKey}` }
: {}),
"anthropic-version": "2023-06-01",
};
case "google":
@@ -81,9 +61,8 @@ export function buildModelDiscoveryHeaders(
style: ProviderStyle,
apiKey: string | undefined,
customHeaders: Record<string, string> = {},
baseURL?: string,
): Record<string, string> {
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL);
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey);
const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase()));
return Object.fromEntries([
...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())),
@@ -59,38 +59,17 @@ test("validateProviderProbeInputs requires base URL and API key except for ollam
);
});
test("classifyProviderProbeResponse marks auth, permission, server, and transport failures as error", () => {
test("classifyProviderProbeResponse marks auth and transport failures as error", () => {
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 401, latencyMs: 120, error: "Unauthorized" }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 403, latencyMs: 90 }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 502, latencyMs: 200 }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 0, latencyMs: 30, error: "Request timeout" }).health,
"error",
);
});
test("classifyProviderProbeResponse downgrades HTTP 404 models-list probe to warn", () => {
const result = classifyProviderProbeResponse({
ok: false,
status: 404,
latencyMs: 95,
data: "404 page not found",
});
assert.equal(result.health, "warn");
assert.equal(result.statusCode, 404);
assert.equal(result.latencyMs, 95);
assert.ok(result.error && result.error.includes("404"));
});
test("classifyProviderProbeResponse marks 2xx with models payload as ok", () => {
const result = classifyProviderProbeResponse({
ok: true,
@@ -209,11 +188,11 @@ test("probeProviderConnection returns typed failures before fetch", async () =>
});
test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bases", async () => {
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
const calls: string[] = [];
const run = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
aiFetch: async (url) => {
calls.push(url);
return {
ok: true,
status: 200,
@@ -226,90 +205,6 @@ test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bas
providerId: "custom",
style: "anthropic",
});
assert.deepEqual(calls, [
{
url: "https://gateway.example/v1/models",
headers: {
"x-api-key": "sk-test",
Authorization: "Bearer sk-test",
"anthropic-version": "2023-06-01",
},
},
]);
assert.deepEqual(calls, ["https://gateway.example/v1/models"]);
assert.equal(run.ok, true);
});
test("probeProviderConnection keeps official Anthropic free of Bearer while custom gateways get Bearer and 404 warns", async () => {
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
const official = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return {
ok: true,
status: 200,
data: JSON.stringify({ data: [{ id: "claude-sonnet-4-5" }] }),
};
},
},
baseURL: "https://api.anthropic.com",
apiKey: "sk-ant-test",
providerId: "anthropic",
style: "anthropic",
});
assert.equal(official.ok, true);
assert.deepEqual(calls[0], {
url: "https://api.anthropic.com/v1/models",
headers: {
"x-api-key": "sk-ant-test",
"anthropic-version": "2023-06-01",
},
});
const agentPlanOpenAI = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return { ok: false, status: 404, data: "404 page not found" };
},
},
baseURL: "https://ark.cn-beijing.volces.com/api/plan/v3",
apiKey: "ark-key",
providerId: "custom",
style: "openai",
});
assert.equal(agentPlanOpenAI.ok, true);
if (!agentPlanOpenAI.ok) throw new Error("expected probe result");
assert.equal(agentPlanOpenAI.classification.health, "warn");
assert.equal(agentPlanOpenAI.classification.statusCode, 404);
assert.deepEqual(calls[1], {
url: "https://ark.cn-beijing.volces.com/api/plan/v3/models",
headers: { Authorization: "Bearer ark-key" },
});
const agentPlanAnthropic = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return { ok: false, status: 404, data: "404 page not found" };
},
},
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
apiKey: "ark-key",
providerId: "custom",
style: "anthropic",
});
assert.equal(agentPlanAnthropic.ok, true);
if (!agentPlanAnthropic.ok) throw new Error("expected probe result");
assert.equal(agentPlanAnthropic.classification.health, "warn");
assert.equal(agentPlanAnthropic.classification.statusCode, 404);
assert.deepEqual(calls[2], {
url: "https://ark.cn-beijing.volces.com/api/plan/v1/models",
headers: {
"x-api-key": "ark-key",
Authorization: "Bearer ark-key",
"anthropic-version": "2023-06-01",
},
});
});
+2 -16
View File
@@ -98,8 +98,7 @@ function countModelsInPayload(data: string | undefined): number | undefined {
/**
* Map a lightweight `/models` (or equivalent) probe response to green / yellow / red.
* Yellow covers slow-but-successful replies, empty model catalogs, and HTTP 404
* (gateways that work for chat without exposing a models listing route).
* Yellow covers slow-but-successful replies and empty model catalogs.
*/
export function classifyProviderProbeResponse(input: {
ok: boolean;
@@ -116,14 +115,6 @@ export function classifyProviderProbeResponse(input: {
...(input.error ? { error: input.error } : {}),
};
if (input.status === 404) {
return {
...base,
health: "warn",
error: input.error || "Model list not available (HTTP 404)",
};
}
if (!input.ok || input.status < 200 || input.status >= 300) {
return {
...base,
@@ -191,12 +182,7 @@ export async function probeProviderConnection(input: {
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, endpoint);
const headers = buildModelDiscoveryHeaders(
input.style,
input.apiKey,
input.customHeaders,
baseURL,
);
const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders);
const result = await bridge.aiFetch(
url,
"GET",
+3 -16
View File
@@ -5,7 +5,6 @@ import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
import type { ProviderConfig, ProviderStyle } from '../types';
import { resolveOpenAIApi, resolveProviderStyle } from '../types';
import { normalizeAnthropicSdkBaseURL } from '../anthropicCompatBaseUrl';
import { isCustomAnthropicBaseURL } from '../modelDiscoveryHeaders';
import { buildSdkRequestHeaders } from '../providerRequestHeaders';
import { normalizeOllamaSdkBaseURL } from '../ollamaCompatBaseUrl';
import { normalizeOpenAIChatCacheUsage } from '../openAIChatCacheUsage';
@@ -775,25 +774,13 @@ function createProviderModel(
: openai.chat(modelId);
}
case 'anthropic': {
// Official api.anthropic.com keeps x-api-key only. Custom Anthropic-compat
// gateways (e.g. Volcengine Ark Agent Plan, Claude Code proxies) may require
// Authorization: Bearer (ANTHROPIC_AUTH_TOKEN) or x-api-key, so send both.
// @ai-sdk/anthropic rejects passing apiKey and authToken together, so pass
// authToken for Bearer and retain x-api-key in headers unless overridden.
const useCustomBearer = Boolean(apiKey && isCustomAnthropicBaseURL(baseURL));
const hasCustomXApiKey = Object.keys(sdkHeaders).some(
(key) => key.toLowerCase() === 'x-api-key',
);
case 'anthropic':
return createAnthropic({
...(useCustomBearer ? { authToken: apiKey } : { apiKey }),
apiKey,
baseURL,
fetch: customFetch,
headers: useCustomBearer && !hasCustomXApiKey
? { 'x-api-key': apiKey!, ...sdkHeaders }
: sdkHeaders,
headers: sdkHeaders,
})(modelId);
}
case 'google':
return createGoogle({
-72
View File
@@ -323,75 +323,3 @@ test("OpenAI Chat sends inline image attachments as data URLs through the bridge
}
assert.equal(requests.length, 4);
});
test("Anthropic SDK sends x-api-key only on official host and adds Bearer on custom bases", async (t) => {
const browserGlobal = globalThis as typeof globalThis & { window?: unknown };
const originalWindow = browserGlobal.window;
t.after(() => { browserGlobal.window = originalWindow; });
const requests: Array<{ url: string; headers: Headers }> = [];
Reflect.set(globalThis, "window", {
netcatty: {
aiFetch: async (url: string, _method: string, headers: Record<string, string>) => {
requests.push({ url, headers: new Headers(headers) });
return { ok: false, status: 400, data: '{"error":{"message":"captured anthropic request"}}' };
},
},
});
const prompt = [{ role: "user" as const, content: [{ type: "text" as const, text: "hello" }] }];
for (const baseURL of [undefined, "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
const model = createModelFromConfig(makeConfig({
providerId: "anthropic",
style: "anthropic",
apiKey: "test-key",
baseURL,
}));
await assert.rejects(async () => await model.doGenerate({ prompt }));
const request = requests.at(-1)!;
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(request.headers.get("authorization"), null);
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
}
for (const baseURL of [
"https://ark.cn-beijing.volces.com/api/plan",
"https://gateway.example/v1",
]) {
const model = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL,
}));
await assert.rejects(async () => await model.doGenerate({ prompt }));
const request = requests.at(-1)!;
assert.equal(request.url, baseURL.endsWith("/api/plan")
? baseURL + "/v1/messages"
: baseURL + "/messages");
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(request.headers.get("authorization"), "Bearer __IPC_SECURED__");
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
}
const overridden = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
customHeaders: { Authorization: "Bearer custom-override" },
}));
await assert.rejects(async () => await overridden.doGenerate({ prompt }));
const overriddenReq = requests.at(-1)!;
assert.equal(overriddenReq.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(overriddenReq.headers.get("authorization"), "Bearer custom-override");
const overriddenApiKey = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
customHeaders: { "X-API-Key": "custom-x-api-key" },
}));
await assert.rejects(async () => await overriddenApiKey.doGenerate({ prompt }));
const overriddenApiKeyReq = requests.at(-1)!;
assert.equal(overriddenApiKeyReq.headers.get("x-api-key"), "custom-x-api-key");
assert.equal(overriddenApiKeyReq.headers.get("authorization"), "Bearer __IPC_SECURED__");
});