Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(desktop): connect directly to private AI model endpoints

tianma-ifb3d0c4797735
diff --git a/apps/desktop/src/main/ai-direct.mjs b/apps/desktop/src/main/ai-direct.mjs
index 664f4cf4..4ccb18a2 100644
--- a/apps/desktop/src/main/ai-direct.mjs
+++ b/apps/desktop/src/main/ai-direct.mjs
@@ -1,32 +1,18 @@
-import { nodePublicFetch, publicLookup } from "@edgeever/public-network/node";
-import { validatePublicUrl } from "@edgeever/public-network/policy";
-
const MAX_BODY_BYTES = 12 * 1024 * 1024;
const MAX_AUDIO_REQUEST_BYTES = 25_000_000;
const MAX_CONCURRENT = 2;
+// AI endpoints are user-configured and may be on the client's private network.
+// Keep this separate from the public-only policy used by plugin requests.
export const validateAiProviderUrl = (value) => {
- const url = validatePublicUrl(value);
- if (url.protocol !== "https:" || url.username || url.password || url.hash) {
- throw new Error("AI provider requests must use HTTPS without credentials.");
+ const url = new URL(value);
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) {
+ throw new Error("AI provider requests must use HTTP or HTTPS without URL credentials or fragments.");
}
- if (url.port && url.port !== "443") throw new Error("AI provider requests must use port 443.");
return url;
};
-export const canUseAiProviderUrl = async (value, lookupImpl = publicLookup) => {
- try {
- const url = validateAiProviderUrl(value);
- await new Promise((resolve, reject) => {
- lookupImpl(url.hostname, { all: true }, error => error ? reject(error) : resolve());
- });
- return true;
- } catch {
- return false;
- }
-};
-
-export const createAiDirectRuntime = ({ fetchImpl = nodePublicFetch, maxConcurrent = MAX_CONCURRENT } = {}) => {
+export const createAiDirectRuntime = ({ fetchImpl = globalThis.fetch, maxConcurrent = MAX_CONCURRENT } = {}) => {
const active = new Map();
return {
async open(requestId, input, { onData, onEnd, onError }) {
diff --git a/apps/desktop/src/main/ai-direct.test.mjs b/apps/desktop/src/main/ai-direct.test.mjs
index 65a43f52..1aa2cd62 100644
--- a/apps/desktop/src/main/ai-direct.test.mjs
+++ b/apps/desktop/src/main/ai-direct.test.mjs
@@ -1,30 +1,59 @@
import { expect, test } from "bun:test";
-import { canUseAiProviderUrl, createAiDirectRuntime, validateAiProviderUrl } from "./ai-direct.mjs";
-import { createPublicLookup } from "@edgeever/public-network/node";
+import { createAiDirectRuntime, validateAiProviderUrl } from "./ai-direct.mjs";
+import { createServer } from "node:http";
+import { once } from "node:events";
-test("desktop AI eligibility checks URL and DNS policy without calling the provider", async () => {
- for (const addresses of [
- [{ address: "93.184.216.34", family: 4 }],
- [{ address: "10.20.30.40", family: 4 }],
- [{ address: "93.184.216.34", family: 4 }, { address: "192.168.1.20", family: 4 }],
- [{ address: "::ffff:127.0.0.1", family: 6 }],
- [],
- ]) {
- let lookups = 0;
- const lookup = createPublicLookup((_host, _options, callback) => {
- lookups++;
- callback(null, addresses);
+test("desktop AI permits user-configured private hosts, HTTP, IPv6 and custom ports", () => {
+ for (const value of [
+ "http://192.168.1.20:11434/v1", "http://localhost:11434/v1",
+ "https://127.0.0.1/v1", "http://[::1]:11434/v1",
+ "https://model.lan/v1", "https://model.example.com:8443/v1",
+ "https://model.intranet.example.com/v1", "https://api.openai.com/v1",
+ ]) expect(validateAiProviderUrl(value).href).toBe(value);
+ for (const value of [
+ "file:///etc/passwd", "ftp://model.lan/v1", "data:text/plain,hello",
+ "https://user:[email protected]/v1", "http://model.lan/v1#fragment", "invalid",
+ ]) expect(() => validateAiProviderUrl(value)).toThrow();
+});
+
+test("desktop AI streams from a real local HTTP model without following redirects", async () => {
+ const requests = [];
+ const server = createServer(async (request, response) => {
+ let body = "";
+ for await (const chunk of request) body += chunk;
+ requests.push({ path: request.url, method: request.method, auth: request.headers.authorization, body });
+ if (request.url === "/redirect") {
+ response.writeHead(307, { location: "/should-not-be-called" });
+ response.end();
+ return;
+ }
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write('data: {"text":"local reply"}\n\n');
+ response.end("data: [DONE]\n\n");
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ try {
+ const runtime = createAiDirectRuntime();
+ const baseUrl = `http://127.0.0.1:${server.address().port}`;
+ const chunks = [];
+ await new Promise((resolve, reject) => {
+ runtime.open("local-model-1", {
+ url: `${baseUrl}/v1/chat/completions`, method: "POST",
+ headers: { authorization: "Bearer local-key" }, body: '{"stream":true}',
+ }, { onData: bytes => chunks.push(new TextDecoder().decode(bytes)), onEnd: resolve, onError: reject }).catch(reject);
});
- expect(await canUseAiProviderUrl("https://model.example.com/v1", lookup)).toBe(addresses.length === 1 && addresses[0].address === "93.184.216.34");
- expect(lookups).toBe(1);
- }
- expect(await canUseAiProviderUrl("https://model.example.com/v1", createPublicLookup((_host, _options, callback) => callback(new Error("DNS unavailable"))))).toBe(false);
- let lookups = 0;
- const lookup = () => { lookups++; };
- for (const url of ["http://model.example.com/v1", "https://127.0.0.1/v1", "https://model.lan/v1", "https://model.example.com:8443/v1"]) {
- expect(await canUseAiProviderUrl(url, lookup)).toBe(false);
+ expect(chunks.join("")).toContain("local reply");
+ expect(requests).toEqual([{ path: "/v1/chat/completions", method: "POST", auth: "Bearer local-key", body: '{"stream":true}' }]);
+ await expect(runtime.open("local-redirect", {
+ url: `${baseUrl}/redirect`, body: "{}",
+ }, { onData() {}, onEnd() {}, onError() {} })).rejects.toThrow();
+ expect(requests.map(request => request.path)).toEqual(["/v1/chat/completions", "/redirect"]);
+ expect(runtime.activeCount).toBe(0);
+ } finally {
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
}
- expect(lookups).toBe(0);
});
test("desktop AI provider transport streams POST bodies to public HTTPS hosts", async () => {
@@ -60,9 +89,7 @@ test("desktop AI provider transport streams POST bodies to public HTTPS hosts",
expect(runtime.activeCount).toBe(0);
});
-test("desktop AI provider transport rejects private hosts and GET", async () => {
- expect(() => validateAiProviderUrl("http://api.openai.com/v1")).toThrow();
- expect(() => validateAiProviderUrl("https://127.0.0.1/v1")).toThrow();
+test("desktop AI provider transport rejects GET", async () => {
const runtime = createAiDirectRuntime({ fetchImpl: async () => new Response("no") });
await expect(runtime.open("req-12345", {
url: "https://integrate.api.nvidia.com/v1/chat/completions",
@@ -118,9 +145,7 @@ test("desktop preload and main process expose the AI provider stream pair", asyn
Bun.file(new URL("../preload/index.cjs", import.meta.url)).text(),
]);
expect(main).toContain('ipcMain.handle("desktop:ai-direct-open"');
- expect(main).toContain('ipcMain.handle("desktop:ai-direct-check"');
expect(main).toContain('ipcMain.on("desktop:ai-direct-cancel"');
expect(preload).toContain('openAiProviderStream: (requestId, input) => ipcRenderer.invoke("desktop:ai-direct-open"');
- expect(preload).toContain('canUseAiProviderUrl: url => ipcRenderer.invoke("desktop:ai-direct-check", url)');
expect(preload).toContain('ipcRenderer.send("desktop:ai-direct-cancel"');
});
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 3c04fb90..e2255eb9 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -56,7 +56,7 @@ import { normalizeUpdateProgress } from "./update-progress.mjs";
import { inspectWindowsTaskbarShortcuts } from "./windows-taskbar-diagnostics.mjs";
import { testPicGoConnection, createPicGoUploadQueue } from "./picgo.mjs";
import { createPluginPublicNetworkRuntime } from "./plugin-public-network.mjs";
-import { canUseAiProviderUrl, createAiDirectRuntime } from "./ai-direct.mjs";
+import { createAiDirectRuntime } from "./ai-direct.mjs";
import { createAcpPathStore, validateTrustedAcpPath } from "./acp-path-store.mjs";
import { createAcpHostRuntime, registerAcpIpc } from "./acp-host.mjs";
import { shouldQuitAfterAllWindowsClosed } from "./window-lifecycle.mjs";
@@ -155,7 +155,9 @@ let rendererStartupFailureDialogOpen = false;
let rendererStartupGuard = null;
let rendererUnresponsiveTimer = null;
const pluginPublicNetwork = createPluginPublicNetworkRuntime();
-const aiDirect = createAiDirectRuntime();
+const aiDirect = createAiDirectRuntime({
+ fetchImpl: (url, init) => net.fetch(url, { ...init, credentials: "omit" }),
+});
let rendererUnresponsiveDialogOpen = false;
let recoveredAfterAbnormalExit = false;
let usePrivateAppProtocol = false;
@@ -1814,12 +1816,8 @@ const startApplication = async () => {
ipcMain.on("desktop:cancel-public-network-fetch", (event, requestId) => {
if (event.sender === mainWindow?.webContents && typeof requestId === "string") pluginPublicNetwork.cancel(requestId);
});
- ipcMain.handle("desktop:ai-direct-check", async (event, url) => {
- if (event.sender !== mainWindow?.webContents) throw new Error("AI provider requests must come from the main window");
- return canUseAiProviderUrl(url);
- });
ipcMain.handle("desktop:ai-direct-open", async (event, requestId, input) => {
- if (event.sender !== mainWindow?.webContents) throw new Error("AI provider requests must come from the main window");
+ if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) throw new Error("AI provider requests must come from the main window");
const sender = event.sender;
return aiDirect.open(requestId, input, {
onData: (bytes) => {
@@ -1840,7 +1838,7 @@ const startApplication = async () => {
});
});
ipcMain.on("desktop:ai-direct-cancel", (event, requestId) => {
- if (event.sender === mainWindow?.webContents && typeof requestId === "string") aiDirect.cancel(requestId);
+ if (event.sender === mainWindow?.webContents && event.senderFrame === event.sender.mainFrame && typeof requestId === "string") aiDirect.cancel(requestId);
});
const acpRuntime = registerAcpIpc(ipcMain, createAcpHostRuntime({
adapterStore: join(app.getPath("userData"), "acp-adapters"),
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 6a6851bc..38f12b0d 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -56,7 +56,6 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
uploadPicGoImage: (input) => ipcRenderer.invoke("desktop:picgo-upload", input),
publicNetworkFetch: (requestId, input) => ipcRenderer.invoke("desktop:public-network-fetch", requestId, input),
cancelPublicNetworkFetch: async (requestId) => { ipcRenderer.send("desktop:cancel-public-network-fetch", requestId); },
- canUseAiProviderUrl: url => ipcRenderer.invoke("desktop:ai-direct-check", url),
openAiProviderStream: (requestId, input) => ipcRenderer.invoke("desktop:ai-direct-open", requestId, input),
cancelAiProviderStream: (requestId) => { ipcRenderer.send("desktop:ai-direct-cancel", requestId); },
onAiProviderStreamChunk: (callback) => {
diff --git a/apps/web/src/lib/api.test.mjs b/apps/web/src/lib/api.test.mjs
index 63fa89d1..69c46c97 100644
--- a/apps/web/src/lib/api.test.mjs
+++ b/apps/web/src/lib/api.test.mjs
@@ -1,6 +1,5 @@
import { afterAll, describe, expect, test } from "bun:test";
-import { canUseAiProviderUrl, createAiDirectRuntime } from "../../../desktop/src/main/ai-direct.mjs";
-import { createPublicLookup } from "../../../../packages/public-network/src/node.mjs";
+import { createAiDirectRuntime } from "../../../desktop/src/main/ai-direct.mjs";
const storage = new Map();
const calls = [];
@@ -10,9 +9,6 @@ let secureSessionToken = "";
let failSecureSessionWrite = false;
let aiRuntime;
const aiStreamListeners = new Set();
-const aiLookup = createPublicLookup((host, _options, callback) => callback(null, [
- { address: host === "model.intranet.example.com" ? "10.20.30.40" : "93.184.216.34", family: 4 },
-]));
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const originalFetch = Object.getOwnPropertyDescriptor(globalThis, "fetch");
@@ -22,7 +18,6 @@ globalThis.window = {
edgeeverDesktop: {
isAvailable: true,
apiBaseUrl: "",
- canUseAiProviderUrl: url => canUseAiProviderUrl(url, aiLookup),
openAiProviderStream: (requestId, input) => aiRuntime.open(requestId, input, {
onData: bytes => { for (const listener of aiStreamListeners) listener(requestId, { type: "data", bytes }); },
onEnd: () => { for (const listener of aiStreamListeners) listener(requestId, { type: "end" }); },
@@ -90,6 +85,7 @@ const {
ApiRequestError,
DESKTOP_API_BASE_URL_STORAGE_KEY,
api,
+ directProviderFetch,
cacheDesktopSession,
clearCachedDesktopSession,
getConfiguredDesktopApiBaseUrl,
@@ -98,106 +94,52 @@ const {
} = await import("./api.ts?desktop-ai-routing-test");
describe("desktop AI routing", () => {
- for (const baseUrl of [
- "http://192.168.1.20:11434/v1",
- "https://192.168.1.20/v1",
- "https://127.0.0.1/v1",
- "https://[::1]/v1",
- "https://model.lan/v1",
- "https://model.example.com:8443/v1",
- "https://model.intranet.example.com/v1",
- ]) {
- test(`proxies ${baseUrl} without fetching credentials or contacting the model`, async () => {
- const paths = [];
- let providerRequests = 0;
- aiRuntime = createAiDirectRuntime({ fetchImpl: async () => {
- providerRequests++;
- throw new Error("The model must only be called by the instance");
- } });
- globalThis.fetch = async url => {
- const path = new URL(String(url), "https://notes.example.com").pathname;
- paths.push(path);
- if (path === "/api/v1/ai/direct-target") {
- return Response.json({ provider: "openai-compatible", baseUrl, modelId: "local-model" });
- }
- if (path === "/api/v1/companion/turns") {
- return new Response('data: {"type":"text-delta","text":"server reply"}\n\n');
- }
- throw new Error(`Unexpected request: ${path}`);
- };
- const received = [];
- await api.streamCompanion({ id: crypto.randomUUID(), message: "hi" }, { onEvent: event => received.push(event) });
- expect(paths).toEqual(["/api/v1/ai/direct-target", "/api/v1/companion/turns"]);
- expect(providerRequests).toBe(0);
- expect(received).toEqual([{ type: "text-delta", text: "server reply" }]);
- expect(aiStreamListeners.size).toBe(0);
- });
- }
-
- for (const operation of ["resume", "generate"]) {
- test(`proxies local-model ${operation} without preparing another generation`, async () => {
- const turnId = crypto.randomUUID();
- const proxyPath = operation === "resume" ? `/api/v1/companion/turns/${turnId}/resume` : "/api/v1/ai/generate";
- const paths = [];
- aiRuntime = createAiDirectRuntime({ fetchImpl: async () => { throw new Error("Unexpected model request"); } });
- globalThis.fetch = async (url, init) => {
- const path = new URL(String(url), "https://notes.example.com").pathname;
- paths.push(path);
- if (path === "/api/v1/ai/direct-target") {
- return Response.json({ provider: "openai-compatible", baseUrl: "http://10.20.30.40:11434/v1", modelId: "local-model" });
- }
- if (path === proxyPath) {
- if (operation === "resume") expect(JSON.parse(init.body)).toEqual({ answers: [] });
- return new Response('data: {"type":"text-delta","text":"server reply"}\n\n');
- }
- throw new Error(`Unexpected request: ${path}`);
- };
- const received = [];
- const streamOptions = { onEvent: event => received.push(event) };
- if (operation === "resume") await api.resumeCompanionTurn(turnId, { answers: [] }, streamOptions);
- else await api.streamAiGeneration({ action: "summarize", title: "Note", contentMarkdown: "Body" }, streamOptions);
- expect(paths).toEqual(["/api/v1/ai/direct-target", proxyPath]);
- expect(received).toEqual([{ type: "text-delta", text: "server reply" }]);
- expect(aiStreamListeners.size).toBe(0);
- });
- }
+ test("an already cancelled generation does not prepare or contact the provider", async () => {
+ const paths = [];
+ globalThis.fetch = async url => { paths.push(String(url)); throw new Error("Unexpected request"); };
+ await expect(api.streamCompanion({ id: crypto.randomUUID(), message: "hi" }, {
+ signal: AbortSignal.abort(), onEvent() {},
+ })).rejects.toThrow();
+ expect(paths).toEqual([]);
+ });
- test("cancelling during DNS eligibility does not prepare a turn or start a generation", async () => {
- const bridge = window.edgeeverDesktop;
- const originalCheck = bridge.canUseAiProviderUrl;
+ test("cancelling a desktop provider stream rejects a pending read and releases the transport", async () => {
const controller = new AbortController();
- let releaseCheck;
- let checkStarted;
- const started = new Promise(resolve => { checkStarted = resolve; });
- const paths = [];
- bridge.canUseAiProviderUrl = async () => {
- checkStarted();
- return new Promise(resolve => { releaseCheck = resolve; });
- };
- globalThis.fetch = async url => {
- paths.push(new URL(String(url), "https://notes.example.com").pathname);
- return Response.json({ provider: "openai-compatible", baseUrl: "https://provider.example.com/v1", modelId: "model" });
- };
- try {
- const generation = api.streamCompanion({ id: crypto.randomUUID(), message: "hi" }, { signal: controller.signal, onEvent: () => {} });
- await started;
- controller.abort();
- releaseCheck(true);
- await expect(generation).rejects.toThrow();
- expect(paths).toEqual(["/api/v1/ai/direct-target"]);
- } finally {
- bridge.canUseAiProviderUrl = originalCheck;
- }
+ let providerSignal;
+ aiRuntime = createAiDirectRuntime({ fetchImpl: async (_url, init) => {
+ providerSignal = init.signal;
+ return new Response(new ReadableStream({
+ start(stream) {
+ init.signal.addEventListener("abort", () => stream.error(init.signal.reason), { once: true });
+ },
+ }));
+ } });
+ const response = await directProviderFetch("http://127.0.0.1:11434/v1/chat/completions", {
+ method: "POST", body: "{}", signal: controller.signal,
+ });
+ const reader = response.body.getReader();
+ const reading = reader.read();
+ controller.abort();
+ await expect(reading).rejects.toMatchObject({ name: "AbortError" });
+ expect(providerSignal.aborted).toBe(true);
+ expect(aiRuntime.activeCount).toBe(0);
+ expect(aiStreamListeners.size).toBe(0);
});
- for (const status of [200, 401, "network", "stream-network"]) {
- test(`keeps public models direct with HTTP ${status}, without retrying generation on the instance`, async () => {
- const baseUrl = `https://provider-${status}.example.com/v1`;
+ for (const baseUrl of [
+ "http://192.168.1.20:11434/v1", "https://192.168.1.20/v1",
+ "https://127.0.0.1/v1", "http://[::1]:11434/v1", "https://model.lan/v1",
+ "https://model.example.com:8443/v1", "https://model.intranet.example.com/v1",
+ "https://provider.example.com/v1",
+ ]) for (const operation of ["new", "resume"]) for (const status of [200, 401, "network", "stream-network"]) {
+ test(`${operation} calls ${baseUrl} directly with ${status}, without instance generation`, async () => {
const paths = [];
const providerAuth = [];
const completed = [];
const turn = { id: crypto.randomUUID(), threadId: crypto.randomUUID(), response: "", process: "", tools: [], todos: [], questions: [] };
- aiRuntime = createAiDirectRuntime({ fetchImpl: async (_url, init) => {
+ const preparePath = operation === "new" ? "/api/v1/companion/turns/prepare" : `/api/v1/companion/turns/${turn.id}/resume/prepare`;
+ aiRuntime = createAiDirectRuntime({ fetchImpl: async (url, init) => {
+ expect(url).toBe(`${baseUrl}/chat/completions`);
const auth = new Headers(init.headers).get("Authorization");
providerAuth.push(auth);
if (status === "network") throw new TypeError("NetworkError during provider request");
@@ -218,10 +160,7 @@ describe("desktop AI routing", () => {
globalThis.fetch = async (url, init) => {
const path = new URL(String(url), "https://notes.example.com").pathname;
paths.push(path);
- if (path === "/api/v1/ai/direct-target") {
- return Response.json({ provider: "openai-compatible", baseUrl, modelId: "public-model" });
- }
- if (path === "/api/v1/companion/turns/prepare") {
+ if (path === preparePath) {
return Response.json({
turn, provider: "openai-compatible", baseUrl, modelId: "public-model", apiKey: "provider-key",
instructions: "Reply briefly", messages: [{ role: "user", content: "hi" }], tools: [], maxSteps: 1, maxOutputTokens: 32,
@@ -236,11 +175,14 @@ describe("desktop AI routing", () => {
};
const received = [];
const requestFailure = status === "network";
- const generation = api.streamCompanion({ id: turn.id, message: "hi" }, { onEvent: event => received.push(event) });
+ const streamOptions = { onEvent: event => received.push(event) };
+ const generation = operation === "new"
+ ? api.streamCompanion({ id: turn.id, message: "hi" }, streamOptions)
+ : api.resumeCompanionTurn(turn.id, { answers: [] }, streamOptions);
if (requestFailure) await expect(generation).rejects.toThrow(/NetworkError/);
else await generation;
expect(paths).toEqual([
- "/api/v1/ai/direct-target", "/api/v1/companion/turns/prepare",
+ preparePath,
...(requestFailure ? [] : [`/api/v1/companion/turns/${turn.id}/complete`]),
]);
expect(providerAuth).toEqual(["Bearer provider-key"]);
@@ -252,6 +194,72 @@ describe("desktop AI routing", () => {
expect(aiStreamListeners.size).toBe(0);
});
}
+
+ for (const operation of ["companion", "resume", "generate", "tags", "plugin", "discovery"]) {
+ test(`${operation} fails on old instances without falling back to server generation`, async () => {
+ const paths = [];
+ globalThis.fetch = async url => {
+ paths.push(new URL(String(url), "https://notes.example.com").pathname);
+ return new Response("{}", { status: 404 });
+ };
+ const streamOptions = { onEvent() {} };
+ const turnId = crypto.randomUUID();
+ const [preparePath, invoke] = {
+ companion: ["/api/v1/companion/turns/prepare", () => api.streamCompanion({ id: turnId, message: "hi" }, streamOptions)],
+ resume: [`/api/v1/companion/turns/${turnId}/resume/prepare`, () => api.resumeCompanionTurn(turnId, {}, streamOptions)],
+ generate: ["/api/v1/ai/generate/prepare", () => api.streamAiGeneration({ action: "summarize", title: "Note", contentMarkdown: "Body" }, streamOptions)],
+ tags: ["/api/v1/ai/tag-suggestions/prepare", () => api.suggestAiTags({ title: "Note", contentMarkdown: "Body", currentTags: [] })],
+ plugin: ["/api/v1/plugins/ai/generate/prepare", () => api.pluginAi.generate({ prompt: "hello", maxOutputTokens: 32 })],
+ discovery: ["/api/v1/companion/discovery/check/prepare", () => api.checkCompanionDiscoveries("en")],
+ }[operation];
+ await expect(invoke()).rejects.toMatchObject({ code: "ai_direct_unavailable" });
+ expect(paths).toEqual([preparePath]);
+ });
+ }
+
+ for (const operation of ["generate", "tags", "plugin"]) {
+ test(`${operation} uses the desktop bridge for a private HTTP model`, async () => {
+ const paths = [];
+ const providerRequests = [];
+ const baseUrl = "http://10.20.30.40:11434/v1";
+ const boundary = { start: "<edgeever-result-x>", end: "</edgeever-result-x>" };
+ aiRuntime = createAiDirectRuntime({ fetchImpl: async (url, init) => {
+ providerRequests.push({ url, auth: new Headers(init.headers).get("Authorization") });
+ if (operation === "generate") return new Response([
+ `data: ${JSON.stringify({ choices: [{ delta: { content: `${boundary.start}\nlocal reply${boundary.end}` } }] })}`,
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}', 'data: [DONE]', '',
+ ].join("\n\n"), { headers: { "content-type": "text/event-stream" } });
+ return Response.json({ choices: [{ message: { content: operation === "tags" ? "<edgeever-tags>\nReact\n</edgeever-tags>" : "local reply" }, finish_reason: "stop" }] });
+ } });
+ const preparePath = {
+ generate: "/api/v1/ai/generate/prepare",
+ tags: "/api/v1/ai/tag-suggestions/prepare",
+ plugin: "/api/v1/plugins/ai/generate/prepare",
+ }[operation];
+ globalThis.fetch = async url => {
+ const path = new URL(String(url), "https://notes.example.com").pathname;
+ paths.push(path);
+ if (path !== preparePath) throw new Error(`Unexpected instance generation: ${path}`);
+ return Response.json({ provider: "openai-compatible", baseUrl, modelId: "local-model", apiKey: "local-key",
+ system: "Reply briefly", prompt: "hello", maxOutputTokens: 32, resultBoundary: boundary,
+ currentTags: [], canonicalTags: { react: "React" },
+ });
+ };
+ if (operation === "generate") {
+ const events = [];
+ await api.streamAiGeneration({ action: "summarize", title: "Note", contentMarkdown: "Body" }, { onEvent: event => events.push(event) });
+ expect(events.filter(event => event.type === "text-delta").map(event => event.text).join("")).toBe("local reply");
+ } else if (operation === "tags") {
+ expect((await api.suggestAiTags({ title: "Note", contentMarkdown: "Body", currentTags: [] })).suggestions).toEqual([{ name: "React", existing: true }]);
+ } else {
+ expect(await api.pluginAi.generate({ prompt: "hello", maxOutputTokens: 32 })).toEqual({ text: "local reply" });
+ }
+ expect(paths).toEqual([preparePath]);
+ expect(providerRequests).toEqual([{ url: `${baseUrl}/chat/completions`, auth: "Bearer local-key" }]);
+ expect(aiStreamListeners.size).toBe(0);
+ });
+ }
+
});
describe("desktop instance setup", () => {
@@ -646,27 +654,6 @@ describe("desktop instance setup", () => {
}
});
- test("does not opt the web proxy into AI streaming", async () => {
- const requestBodies = [];
- globalThis.fetch = async (url, init) => {
- if (String(url).includes("/api/v1/ai/direct-target")) {
- return new Response("{}", { status: 404 });
- }
- requestBodies.push(JSON.parse(String(init?.body)));
- return new Response('data: {"type":"finish"}\n\n', {
- headers: { "Content-Type": "text/event-stream" },
- });
- };
-
- await api.streamAiGeneration(
- { action: "summarize", title: "Note", contentMarkdown: "Body" },
- { onEvent: () => {} },
- );
-
- expect(requestBodies).toHaveLength(1);
- expect(requestBodies[0].stream).toBeUndefined();
- });
-
test("streams infographic agent tool events through the authenticated client", async () => {
let requestPath = "";
let requestBody;
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 825e24bf..8069e8c0 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -234,6 +234,7 @@ const toUint8Array = (bytes: ArrayBuffer | Uint8Array | undefined) => {
};
const desktopProviderFetch: typeof fetch = async (input, init) => {
+ init?.signal?.throwIfAborted();
const bridge = window.edgeeverDesktop;
if (!bridge?.openAiProviderStream || !bridge.onAiProviderStreamChunk) {
throw new TypeError("Desktop AI transport is unavailable.");
@@ -253,6 +254,7 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {
multipart.headers.forEach((value, key) => { headers[key] = value; });
bodyBytes = new Uint8Array(await multipart.arrayBuffer());
}
+ init?.signal?.throwIfAborted();
const requestId = crypto.randomUUID();
const pending: Array<{ type: "data" | "end" | "error"; bytes?: ArrayBuffer | Uint8Array; message?: string }> = [];
let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;
@@ -272,6 +274,9 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {
});
const abort = () => {
bridge.cancelAiProviderStream(requestId);
+ const reason = init?.signal?.reason ?? new DOMException("The operation was aborted.", "AbortError");
+ if (streamController) streamController.error(reason);
+ else pending.push({ type: "error", message: String(reason) });
cleanup();
};
cleanup = () => {
@@ -287,6 +292,7 @@ const desktopProviderFetch: typeof fetch = async (input, init) => {
body: typeof init?.body === "string" ? init.body : "",
...(bodyBytes ? { bodyBytes } : {}),
});
+ init?.signal?.throwIfAborted();
const body = new ReadableStream<Uint8Array>({
start(controller) {
streamController = controller;
@@ -328,7 +334,6 @@ const client = createEdgeEverClient({
shouldAttachToken: (path) => path !== "/api/v1/auth/login",
onUnauthorized: handleUnauthorized,
directAiGeneration: desktopAiDirectEnabled,
- canDirectAiGeneration: target => window.edgeeverDesktop?.canUseAiProviderUrl?.(target.baseUrl) ?? false,
tryDirectAiGeneration: !desktopAiDirectEnabled,
providerFetch: desktopAiDirectEnabled ? desktopProviderFetch : undefined,
});
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 84d9b835..80e6c065 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -48,7 +48,6 @@ interface EdgeEverDesktopBridge {
}): Promise<{ url: string } | { fallback: true }>;
publicNetworkFetch(requestId: string, input: import("@edgeever/shared").PluginPublicFetchRequest): Promise<import("@edgeever/shared").PluginPublicFetchResponse>;
cancelPublicNetworkFetch(requestId: string): Promise<void>;
- canUseAiProviderUrl?(url: string): Promise<boolean>;
openAiProviderStream(requestId: string, input: {
url: string;
method?: string;
diff --git a/packages/client/src/ai-direct-stream.test.mjs b/packages/client/src/ai-direct-stream.test.mjs
index 502e3a23..3d10ead7 100644
--- a/packages/client/src/ai-direct-stream.test.mjs
+++ b/packages/client/src/ai-direct-stream.test.mjs
@@ -154,7 +154,7 @@ describe("direct AI generation client", () => {
expect(events.filter((event) => event.type === "text-delta").map((event) => event.text).join("")).toBe("Hello");
});
- test("falls back to the instance proxy when prepare is missing", async () => {
+ test("fails without instance generation when direct prepare is missing", async () => {
const urls = [];
const client = createEdgeEverClient({
baseUrl: "https://notes.example",
@@ -168,15 +168,12 @@ describe("direct AI generation client", () => {
},
});
const events = [];
- await client.streamAiGeneration(
+ await expect(client.streamAiGeneration(
{ action: "summarize", title: "Note", contentMarkdown: "Body" },
{ onEvent: (event) => events.push(event) },
- );
- expect(urls).toEqual([
- "https://notes.example/api/v1/ai/generate/prepare",
- "https://notes.example/api/v1/ai/generate",
- ]);
- expect(events).toEqual([{ type: "text-delta", text: "proxied" }]);
+ )).rejects.toMatchObject({ code: "ai_direct_unavailable" });
+ expect(urls).toEqual(["https://notes.example/api/v1/ai/generate/prepare"]);
+ expect(events).toEqual([]);
});
});
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 0c2ebe1b..e5d9aa14 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -110,10 +110,8 @@ export type EdgeEverClientOptions = {
baseUrl?: string | (() => string);
token?: string | null | (() => string | null | undefined);
fetch?: typeof fetch;
- /** Native/desktop note AI and Agent calls the model API directly after a short prepare hop. */
+ /** Native/desktop AI calls providers directly; missing prepare support fails without proxy fallback. */
directAiGeneration?: boolean;
- /** Decide native transport eligibility from key-free target metadata before preparing a generation. */
- canDirectAiGeneration?: (target: import("@edgeever/shared").AiDirectTarget) => boolean | Promise<boolean>;
/**
* Browser-only: probe whether the model host allows CORS, then direct-connect.
* Falls back to the instance proxy without using a prepared API key when CORS is blocked.
@@ -699,17 +697,11 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
});
};
- const useDirectAiGeneration = async (signal?: AbortSignal) => {
- signal?.throwIfAborted();
- if (!options.canDirectAiGeneration) return true;
- const { context, response } = await send("/api/v1/ai/direct-target", { signal });
- if (response.status === 404 || response.status === 409) return false;
- if (!response.ok) await throwRequestError(context, response);
- const target = parseAiDirectTarget(await response.json());
- const allowed = target !== null && await options.canDirectAiGeneration(target);
- signal?.throwIfAborted();
- return allowed;
- };
+ const directAiUnavailable = () => new ApiRequestError(
+ "This instance does not support direct AI preparation. Update the instance before using AI.",
+ 409,
+ "ai_direct_unavailable",
+ );
const runCompanionDirect = async (
preparePath: string,
@@ -733,14 +725,13 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
};
if (options.directAiGeneration) {
- if (!await useDirectAiGeneration(streamOptions.signal)) return proxy();
+ streamOptions.signal?.throwIfAborted();
const prepared = await prepare();
if (prepared) {
await runPreparedCompanion(prepared, streamOptions);
return;
}
- await proxy();
- return;
+ throw directAiUnavailable();
}
if (options.tryDirectAiGeneration) {
@@ -788,7 +779,10 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
recover?: (prepared: P) => Promise<T>;
}): Promise<T> => {
const attemptPrepare = async () => {
- if (options.directAiGeneration) return await useDirectAiGeneration(args.signal) ? args.prepare() : null;
+ if (options.directAiGeneration) {
+ args.signal?.throwIfAborted();
+ return args.prepare();
+ }
if (!options.tryDirectAiGeneration) return null;
const { context, response } = await send("/api/v1/ai/direct-target", { signal: args.signal });
if (!response.ok) {
@@ -812,7 +806,10 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
}
};
const prepared = await attemptPrepare();
- if (prepared == null) return args.proxy();
+ if (prepared == null) {
+ if (options.directAiGeneration) throw directAiUnavailable();
+ return args.proxy();
+ }
try {
return await args.run(prepared);
} catch (error) {
@@ -1272,10 +1269,9 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
};
if (options.directAiGeneration) {
- if (!await useDirectAiGeneration(streamOptions.signal)) return proxyGenerate();
+ streamOptions.signal?.throwIfAborted();
if (await prepareAndDirect()) return;
- await proxyGenerate();
- return;
+ throw directAiUnavailable();
}
if (options.tryDirectAiGeneration) {