mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-07 18:27:47 +08:00
fix: what the third round broke, and the first batch's review
MCP preview after the server lost a session (it expired, or the MCP process restarted): - Every server state has an id, made when the state is created. The tab notices a new id even when the version numbers happen to match, and every push names the state it was based on, so one based on a lost state is refused, also when it comes before the tab's first poll (the server recovers the saved file first). - The tab keeps the newest canvas XML, saved or not. When the server knows nothing (no file) or exactly what the tab last saved, the canvas wins and is saved, so edits made while the server was down are kept. Otherwise the server's diagram (an AI write the tab missed, a cleared document that was saved) is shown and the tab's copy goes to History. - Late answers to an old state's push or poll are dropped; a failed push says the server is unreachable; Download as .drawio saves the canvas. Settings and server: - Saved providers this version does not know stay in storage with their keys, and sending no longer trips over them. - The desktop "Ollama (Local)" preset with a key goes to local Ollama again; a server model's Ollama URL variable is read; the admin panel writes Ollama Cloud's URL for a key without one. - Provider error texts show again in the desktop app and for EdgeOne. - .env: a quoted value followed by a comment ending in a quote is read as dotenv reads it; unquoted values are unchanged. - Desktop app: the next launch opens the port where a chat was last saved; a launch elsewhere that saves nothing does not move it, and a page with no chats lets the next launch try the other port once. - The Test button no longer stays busy after another tab changed the key. - A completed append_diagram is no longer undone by an earlier failed edit's preview; a file read once in vain is saved again once it is read or gone. From the first batch's review: - The admin panel's Test of an entry without a URL now tests the server's <P>_BASE_URL, where chat sends the entry's key; chat is unchanged (the first fix rerouted working setups). - The model list ends downloads that are too large, accepts answers without a body, and keeps the "redirects are not allowed" explanation. - A test covers the preview's History rendering.
This commit is contained in:
@@ -213,17 +213,12 @@ export function adminProvidersToConfig(
|
||||
indexByProvider.set(p.provider, index + 1)
|
||||
if (p.models.length === 0) continue
|
||||
const env = credEnvNames(p.provider, index)
|
||||
// An entry with its own key also names its own URL variable, unset
|
||||
// when the URL is empty: the global <P>_BASE_URL may be a proxy for
|
||||
// another key, and the Test used the official endpoint. An Azure
|
||||
// key belongs to one resource, so it keeps the server's.
|
||||
const ownUrl = !!p.baseUrl || (!!p.apiKey && p.provider !== "azure")
|
||||
config.providers.push({
|
||||
name: displayName(p),
|
||||
provider: p.provider,
|
||||
models: p.models,
|
||||
...(env.key && p.apiKey ? { apiKeyEnv: env.key } : {}),
|
||||
...(env.url && ownUrl ? { baseUrlEnv: env.url } : {}),
|
||||
...(env.url && p.baseUrl ? { baseUrlEnv: env.url } : {}),
|
||||
...(p.isDefault ? { default: true } : {}),
|
||||
})
|
||||
}
|
||||
@@ -262,7 +257,12 @@ export function deriveEnvUpdates(
|
||||
if (p.baseUrl) updates.GOOGLE_VERTEX_BASE_URL = p.baseUrl
|
||||
} else if (p.provider === "ollama") {
|
||||
if (p.apiKey) updates.OLLAMA_API_KEY = p.apiKey
|
||||
if (p.baseUrl) updates.OLLAMA_BASE_URL = p.baseUrl
|
||||
// A key without a URL is an Ollama Cloud key, as its Test sends
|
||||
// it; chat sends a server key to OLLAMA_BASE_URL or local Ollama
|
||||
if (p.baseUrl || p.apiKey) {
|
||||
updates.OLLAMA_BASE_URL =
|
||||
p.baseUrl || PROVIDER_INFO.ollama.defaultBaseUrl || null
|
||||
}
|
||||
} else {
|
||||
const env = credEnvNames(p.provider, index)
|
||||
if (env.key && p.apiKey) updates[env.key] = p.apiKey
|
||||
|
||||
+25
-14
@@ -997,17 +997,15 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
? overrides?.apiKey || undefined
|
||||
: resolveApiKey(overrides, "OLLAMA_API_KEY")
|
||||
// Like other providers, a user's key never goes to the server's
|
||||
// base URL. A key without a base URL is an Ollama Cloud key
|
||||
// (local Ollama has no keys); without either, the SDK's local
|
||||
// default.
|
||||
// base URL: without a URL of their own it goes to Ollama Cloud.
|
||||
// The server's key goes to OLLAMA_BASE_URL (or a server model's
|
||||
// own variable), else to the SDK's local default: the desktop
|
||||
// app's "Ollama (Local)" preset puts its key field there too.
|
||||
const baseURL =
|
||||
overrides?.baseUrl ||
|
||||
(overrides?.apiKey
|
||||
? PROVIDER_INFO.ollama.defaultBaseUrl
|
||||
: process.env.OLLAMA_BASE_URL ||
|
||||
(apiKey
|
||||
? PROVIDER_INFO.ollama.defaultBaseUrl
|
||||
: undefined))
|
||||
: resolveBaseUrlEnv(overrides, "OLLAMA_BASE_URL"))
|
||||
model = createOllama({
|
||||
...(baseURL && { baseURL }),
|
||||
...(apiKey && {
|
||||
@@ -1043,9 +1041,8 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
: `${provider.toUpperCase()}_BASE_URL`
|
||||
// A local default (SGLang's 127.0.0.1) only fills the settings
|
||||
// form; the server must not call its own machine for it. With a
|
||||
// user's key, or an admin entry's own (empty) URL variable, the
|
||||
// OpenAI SDK would read the server's OPENAI_BASE_URL, so name
|
||||
// the official endpoint.
|
||||
// user's key the OpenAI SDK would read the server's
|
||||
// OPENAI_BASE_URL, so name the official endpoint.
|
||||
const defaultUrl = PROVIDER_INFO[provider].defaultBaseUrl
|
||||
const publicDefault = defaultUrl?.startsWith("https://")
|
||||
? defaultUrl
|
||||
@@ -1058,10 +1055,7 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
const baseURL =
|
||||
configuredBaseURL ||
|
||||
(SDK_KNOWS_ENDPOINT.has(provider) &&
|
||||
!(
|
||||
provider === "openai" &&
|
||||
(overrides?.apiKey || overrides?.baseUrlEnv)
|
||||
)
|
||||
!(provider === "openai" && overrides?.apiKey)
|
||||
? undefined
|
||||
: publicDefault)
|
||||
// With a user's Azure key the SDK would read the server's
|
||||
@@ -1097,6 +1091,23 @@ export function getAIModel(clientOverrides?: ClientOverrides): ModelConfig {
|
||||
return { model, providerOptions, modelId, provider }
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's <P>_BASE_URL for a provider, which getAIModel uses for a
|
||||
* server model without a URL variable of its own (an admin panel entry
|
||||
* without a URL). Bedrock, EdgeOne and Ollama (the panel writes
|
||||
* OLLAMA_BASE_URL itself) have none.
|
||||
*/
|
||||
export function globalBaseUrl(provider: ProviderName): string | undefined {
|
||||
if (["bedrock", "edgeone", "ollama"].includes(provider)) return undefined
|
||||
const name =
|
||||
provider === "vertexai"
|
||||
? "GOOGLE_VERTEX_BASE_URL"
|
||||
: provider === "gateway"
|
||||
? "AI_GATEWAY_BASE_URL"
|
||||
: `${provider.toUpperCase()}_BASE_URL`
|
||||
return process.env[name] || undefined
|
||||
}
|
||||
|
||||
/** The provider of the server's own config: AI_PROVIDER, or the one with a key */
|
||||
export function getServerProvider(): ProviderName | null {
|
||||
return (process.env.AI_PROVIDER as ProviderName) || detectProvider()
|
||||
|
||||
+11
-2
@@ -78,16 +78,25 @@ const MAX_LIST_BYTES = 2 * 1024 * 1024
|
||||
/** A fetch that reads at most MAX_LIST_BYTES of each response */
|
||||
function sizeLimitedFetch(fetchFn: typeof fetch): typeof fetch {
|
||||
return async (input, init) => {
|
||||
const response = await fetchFn(input, init)
|
||||
// Ends a download that is too large (the Gateway SDK passes no
|
||||
// signal of its own)
|
||||
const download = new AbortController()
|
||||
const signal = init?.signal
|
||||
? AbortSignal.any([init.signal, download.signal])
|
||||
: download.signal
|
||||
const response = await fetchFn(input, { ...init, signal })
|
||||
const body = await readLimitedBody(response, MAX_LIST_BYTES)
|
||||
if (body === null) {
|
||||
download.abort()
|
||||
throw new ModelListError("The model list is too large.")
|
||||
}
|
||||
// The body is already decoded and has its own length now
|
||||
const headers = new Headers(response.headers)
|
||||
headers.delete("content-encoding")
|
||||
headers.delete("content-length")
|
||||
return new Response(body, {
|
||||
// Some statuses must have no body at all
|
||||
const noBody = [101, 204, 205, 304].includes(response.status)
|
||||
return new Response(noBody ? null : body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Read a response body, giving up once it passes maxBytes, so a huge
|
||||
* download from a URL the client chose can't exhaust server memory.
|
||||
* Returns null when it is too large.
|
||||
* Returns null when it is too large; the caller then aborts the request,
|
||||
* which ends the download.
|
||||
*/
|
||||
export async function readLimitedBody(
|
||||
response: Response,
|
||||
@@ -20,7 +21,9 @@ export async function readLimitedBody(
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel()
|
||||
// Not awaited: a copy of the body that Next.js keeps (its fetch
|
||||
// dedupe) can hold the cancel back until it is read
|
||||
reader.cancel().catch(() => {})
|
||||
return null
|
||||
}
|
||||
chunks.push(value)
|
||||
|
||||
@@ -176,6 +176,8 @@ export async function saveSession(session: ChatSession): Promise<boolean> {
|
||||
try {
|
||||
const db = await getDB()
|
||||
await db.put(STORE_NAME, session)
|
||||
// The desktop app opens this port (this origin's chats) next launch
|
||||
window.electronAPI?.chatSaved?.().catch(() => {})
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error("Failed to save session:", error)
|
||||
|
||||
@@ -116,6 +116,14 @@ export function allowPrivateUrls(): boolean {
|
||||
return process.env.ALLOW_PRIVATE_URLS !== "false"
|
||||
}
|
||||
|
||||
/** A redirect the guard below refused; its text is safe to show */
|
||||
export class RedirectRefusedError extends Error {
|
||||
constructor() {
|
||||
super("Redirects are not allowed for custom base URLs")
|
||||
this.name = "RedirectRefusedError"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A fetch for requests to a base URL the client chose. With private URLs
|
||||
* blocked, a public URL could still redirect the request to an internal
|
||||
@@ -126,7 +134,7 @@ export function redirectGuardedFetch(): typeof fetch | undefined {
|
||||
return async (input, init) => {
|
||||
const response = await fetch(input, { ...init, redirect: "manual" })
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
throw new Error("Redirects are not allowed for custom base URLs")
|
||||
throw new RedirectRefusedError()
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user