diff --git a/.claude/skills/nexus-llm-adapters/references/local-providers.md b/.claude/skills/nexus-llm-adapters/references/local-providers.md index 1e3c67637..4591a6272 100644 --- a/.claude/skills/nexus-llm-adapters/references/local-providers.md +++ b/.claude/skills/nexus-llm-adapters/references/local-providers.md @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`. ## Verification Local servers are not covered by the live smoke lane. Verify them by hand through all three paths in `protocols/verify-adapter.md`. + +## Where an OpenAI-compatible server says its context +`/v1/models` has no standard limit field. Read, in order: `max_model_len` +(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost), +`context_window` (Groq, Bifrost's OpenAI route), `max_context_length` +(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's +`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is +`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under +it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare +`{id, created, owned_by}`, so a user-entered value must always be possible. + +Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's +maximum context length is N tokens". llama.cpp: HTTP 400 with +`error.type: exceed_context_size_error`, `error.n_ctx`, and the message +"request (X tokens) exceeds the available context size (N tokens)". A server +that truncates instead of refusing shows up only as a low +`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp +runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer +it as the size. Ollama's `/v1/models` reports no context at all, and its MLX +runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts` +exercises all of this against a real server; for Ollama set +`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`. + +A chat stores its budget beside the model's whole window at that time +(`chatSettings.modelContextWindow`). When the window later grows, a budget equal +to the old window follows it, on reopen and in an open chat; a smaller one stays. +Chats saved before that field existed are treated as "whole window" only at the +OpenAI-compatible 4,096 fallback. diff --git a/.cline/skills/nexus-llm-adapters/references/local-providers.md b/.cline/skills/nexus-llm-adapters/references/local-providers.md index 1e3c67637..4591a6272 100644 --- a/.cline/skills/nexus-llm-adapters/references/local-providers.md +++ b/.cline/skills/nexus-llm-adapters/references/local-providers.md @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`. ## Verification Local servers are not covered by the live smoke lane. Verify them by hand through all three paths in `protocols/verify-adapter.md`. + +## Where an OpenAI-compatible server says its context +`/v1/models` has no standard limit field. Read, in order: `max_model_len` +(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost), +`context_window` (Groq, Bifrost's OpenAI route), `max_context_length` +(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's +`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is +`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under +it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare +`{id, created, owned_by}`, so a user-entered value must always be possible. + +Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's +maximum context length is N tokens". llama.cpp: HTTP 400 with +`error.type: exceed_context_size_error`, `error.n_ctx`, and the message +"request (X tokens) exceeds the available context size (N tokens)". A server +that truncates instead of refusing shows up only as a low +`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp +runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer +it as the size. Ollama's `/v1/models` reports no context at all, and its MLX +runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts` +exercises all of this against a real server; for Ollama set +`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`. + +A chat stores its budget beside the model's whole window at that time +(`chatSettings.modelContextWindow`). When the window later grows, a budget equal +to the old window follows it, on reopen and in an open chat; a smaller one stays. +Chats saved before that field existed are treated as "whole window" only at the +OpenAI-compatible 4,096 fallback. diff --git a/.codex/skills/nexus-llm-adapters/references/local-providers.md b/.codex/skills/nexus-llm-adapters/references/local-providers.md index 1e3c67637..4591a6272 100644 --- a/.codex/skills/nexus-llm-adapters/references/local-providers.md +++ b/.codex/skills/nexus-llm-adapters/references/local-providers.md @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`. ## Verification Local servers are not covered by the live smoke lane. Verify them by hand through all three paths in `protocols/verify-adapter.md`. + +## Where an OpenAI-compatible server says its context +`/v1/models` has no standard limit field. Read, in order: `max_model_len` +(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost), +`context_window` (Groq, Bifrost's OpenAI route), `max_context_length` +(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's +`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is +`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under +it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare +`{id, created, owned_by}`, so a user-entered value must always be possible. + +Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's +maximum context length is N tokens". llama.cpp: HTTP 400 with +`error.type: exceed_context_size_error`, `error.n_ctx`, and the message +"request (X tokens) exceeds the available context size (N tokens)". A server +that truncates instead of refusing shows up only as a low +`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp +runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer +it as the size. Ollama's `/v1/models` reports no context at all, and its MLX +runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts` +exercises all of this against a real server; for Ollama set +`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`. + +A chat stores its budget beside the model's whole window at that time +(`chatSettings.modelContextWindow`). When the window later grows, a budget equal +to the old window follows it, on reopen and in an open chat; a smaller one stays. +Chats saved before that field existed are treated as "whole window" only at the +OpenAI-compatible 4,096 fallback. diff --git a/.skills/nexus-llm-adapters/references/local-providers.md b/.skills/nexus-llm-adapters/references/local-providers.md index 1e3c67637..4591a6272 100644 --- a/.skills/nexus-llm-adapters/references/local-providers.md +++ b/.skills/nexus-llm-adapters/references/local-providers.md @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`. ## Verification Local servers are not covered by the live smoke lane. Verify them by hand through all three paths in `protocols/verify-adapter.md`. + +## Where an OpenAI-compatible server says its context +`/v1/models` has no standard limit field. Read, in order: `max_model_len` +(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost), +`context_window` (Groq, Bifrost's OpenAI route), `max_context_length` +(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's +`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is +`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under +it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare +`{id, created, owned_by}`, so a user-entered value must always be possible. + +Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's +maximum context length is N tokens". llama.cpp: HTTP 400 with +`error.type: exceed_context_size_error`, `error.n_ctx`, and the message +"request (X tokens) exceeds the available context size (N tokens)". A server +that truncates instead of refusing shows up only as a low +`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp +runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer +it as the size. Ollama's `/v1/models` reports no context at all, and its MLX +runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts` +exercises all of this against a real server; for Ollama set +`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`. + +A chat stores its budget beside the model's whole window at that time +(`chatSettings.modelContextWindow`). When the window later grows, a budget equal +to the old window follows it, on reopen and in an open chat; a smaller one stays. +Chats saved before that field existed are treated as "whole window" only at the +OpenAI-compatible 4,096 fallback. diff --git a/docs/plans/openai-compatible-provider-plan.md b/docs/plans/openai-compatible-provider-plan.md index 33bb33e14..476732826 100644 --- a/docs/plans/openai-compatible-provider-plan.md +++ b/docs/plans/openai-compatible-provider-plan.md @@ -90,6 +90,8 @@ Model discovery commonly gives IDs without reliable limits or prices. Keep this Use one internal metadata resolver keyed by endpoint and model. Accept only validated, documented server metadata with the correct meaning: for example, vLLM's `max_model_len` describes its configured limit, whereas llama.cpp's `meta.n_ctx_train` describes training context, not necessarily the allocated runtime context. Otherwise use an internal budget assumption of 4096 context tokens and 1024 maximum output tokens. These are heuristics, not guaranteed server limits; the tested Ollama process itself reported a 4096-token runtime context. Keep fallback budgeting consistent across dropdowns, pre-send budgeting and compaction rather than inheriting an unrelated static 128K fallback. Output budgeting does not require sending a token-limit field unless normal generation settings request one. +**Revised November 2026 for [#439](https://github.com/ProfSynapse/nexus/issues/439).** A fixed 4096 fallback cannot be raised, and gateways such as Bifrost strip the metadata above, so a 128K model was compacted at about 4K. Each saved model now carries an optional context window. The user's value wins, then the server's report (refreshed on every Connect), then 4096. Discovery reads `max_model_len`, `context_length`, `context_window`, `max_context_length` and `top_provider.context_length`. For a single-model llama.cpp server, which marks its entry with `meta`, discovery asks `/props` for the allocated `n_ctx` rather than using `n_ctx_train`. A **Check** button sends one prompt of the chosen size with `max_tokens: 1` and reports one of: fits, refused (with the limit the server named), or silently shortened (detected from `usage.prompt_tokens`). It never runs automatically, because a prompt that fits is read in full, which takes time locally and is billed by hosted endpoints. The 1024 output assumption is unchanged. + The generic contract supports standard text and tool calling and prefers streaming. Optional image/structured-output capabilities use reliable metadata or existing established capability rules; do not invent support from model names. Unsupported requests fail visibly. Reasoning display follows the normal chat path, with no endpoint-specific control. Unknown pricing remains unknown, not zero. Preserve token usage and adapt touched cost consumers to tolerate missing prices without inventing a custom pricing editor. Keep this change narrow; existing known-price providers retain their behavior. diff --git a/src/components/openai-compatible/OpenAICompatibleEditSession.ts b/src/components/openai-compatible/OpenAICompatibleEditSession.ts index b595fe1b2..346241f61 100644 --- a/src/components/openai-compatible/OpenAICompatibleEditSession.ts +++ b/src/components/openai-compatible/OpenAICompatibleEditSession.ts @@ -1,9 +1,17 @@ -import type { LLMProviderConfig } from '../../types/llm/ProviderTypes'; +import type { LLMProviderConfig, OpenAICompatibleModelDefinition } from '../../types/llm/ProviderTypes'; import { discoverOpenAICompatibleModels, + isOpenAICompatibleContextWindow, isOpenAICompatibleModelId, normalizeOpenAICompatibleBaseUrl, + OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW, + OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW, + resolveOpenAICompatibleContextWindow, } from '../../services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; +import { + checkOpenAICompatibleContextWindow, + type OpenAICompatibleContextCheckResult, +} from '../../services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck'; export type CompatibleEndpointConfig = LLMProviderConfig & { driverKind: 'openai-compatible'; @@ -11,7 +19,7 @@ export type CompatibleEndpointConfig = LLMProviderConfig & { schemaVersion: 1; displayName: string; baseUrl: string; - models: Record; + models: Record; }; }; @@ -42,6 +50,7 @@ export class OpenAICompatibleEditSession { config: CompatibleEndpointConfig, private readonly persist: (id: string, config: CompatibleEndpointConfig) => Promise, private readonly discover = discoverOpenAICompatibleModels, + private readonly check = checkOpenAICompatibleContextWindow, ) { this.draft = copyEndpoint(config); } @@ -67,6 +76,43 @@ export class OpenAICompatibleEditSession { this.draft.models = { ...this.draft.models, [id]: { ...this.draft.models?.[id], enabled } }; } + /** Undefined clears the user's value, so the server's report or the default applies again. */ + setContextWindow(id: string, value: number | undefined): void { + const definition = this.draft.openaiCompatible.models[id]; + if (!definition) throw new Error('This model is not in the list.'); + if (value !== undefined && !isOpenAICompatibleContextWindow(value)) { + throw new Error(`Enter a whole number of tokens from ${OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW.toLocaleString()} to ${OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW.toLocaleString()}.`); + } + const next = { ...definition }; + if (value === undefined) delete next.contextWindow; + else next.contextWindow = value; + this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: next }; + } + + /** + * Adopts a size a check revealed. When the server reports that same size, + * the user's value is cleared so the model follows the server's report + * instead of pinning a copy that would outlive a later server change. + * Returns the value the field should show ('' when following the server). + */ + useContextWindow(id: string, value: number): string { + const followsServer = this.draft.openaiCompatible.models[id]?.reportedContextWindow === value; + this.setContextWindow(id, followsServer ? undefined : value); + return followsServer ? '' : String(value); + } + + /** Sends one prompt of the model's current context size; the caller saves nothing on its behalf. */ + async checkContextWindow(id: string, signal?: AbortSignal): Promise { + const error = this.validationError(); + if (error) throw new Error(error); + const definition = this.draft.openaiCompatible.models[id]; + if (!definition) throw new Error('This model is not in the list.'); + return this.check({ + baseUrl: this.draft.openaiCompatible.baseUrl, apiKey: this.draft.apiKey, model: id, + contextWindow: resolveOpenAICompatibleContextWindow(definition).contextWindow, signal, + }); + } + validationError(): string | null { if (!this.draft.openaiCompatible.displayName.trim()) return 'Enter a name for this endpoint.'; try { @@ -106,17 +152,21 @@ export class OpenAICompatibleEditSession { const baseUrl = normalizeOpenAICompatibleBaseUrl(this.draft.openaiCompatible.baseUrl); const key = this.draft.apiKey; try { - const ids = await this.discover(baseUrl, key); + const discovered = await this.discover(baseUrl, key); if (this.closed || revision !== this.revision) return 'stale'; - for (const id of new Set(ids)) { - if (!Object.prototype.hasOwnProperty.call(this.draft.openaiCompatible.models, id)) { - this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: { source: 'discovered' } }; - this.setModelEnabled(id, true); - } + for (const { id, contextWindow } of discovered) { + const existing = Object.prototype.hasOwnProperty.call(this.draft.openaiCompatible.models, id) + ? this.draft.openaiCompatible.models[id] : undefined; + // The report is refreshed on every Connect; the user's own value is never touched. + const next = { ...(existing ?? { source: 'discovered' as const }) }; + if (contextWindow === undefined) delete next.reportedContextWindow; + else next.reportedContextWindow = contextWindow; + this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: next }; + if (!existing) this.setModelEnabled(id, true); } - if (ids.length > 0) this.draft.enabled = true; + if (discovered.length > 0) this.draft.enabled = true; await this.save(); - return this.closed || revision !== this.revision ? 'stale' : ids.length ? 'connected' : 'empty'; + return this.closed || revision !== this.revision ? 'stale' : discovered.length ? 'connected' : 'empty'; } catch (error) { if (this.closed || revision !== this.revision) return 'stale'; throw error; diff --git a/src/components/openai-compatible/OpenAICompatibleModal.ts b/src/components/openai-compatible/OpenAICompatibleModal.ts index f82f35055..99785b21f 100644 --- a/src/components/openai-compatible/OpenAICompatibleModal.ts +++ b/src/components/openai-compatible/OpenAICompatibleModal.ts @@ -1,6 +1,9 @@ import { App, ButtonComponent, Modal, Notice, Setting } from 'obsidian'; import type { LLMProviderConfig } from '../../types/llm/ProviderTypes'; import { generateUUID } from '../../utils/uuid'; +import { resolveOpenAICompatibleContextWindow } from '../../services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; +import type { OpenAICompatibleContextCheckResult } from '../../services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck'; +import type { OpenAICompatibleModelDefinition } from '../../types/llm/ProviderTypes'; import { CompatibleEndpointConfig, copyEndpoint, @@ -8,6 +11,48 @@ import { OpenAICompatibleEditSession, } from './OpenAICompatibleEditSession'; +interface ContextNote { + text: string; + warning: boolean; + /** A size the server named or revealed, offered as a one-click replacement. */ + suggestion?: number; +} + +const tokens = (value: number): string => value.toLocaleString(); + +export function describeContextWindow(definition: OpenAICompatibleModelDefinition | undefined): string { + const { contextWindow, source } = resolveOpenAICompatibleContextWindow(definition); + if (source === 'server') return `Context window: ${tokens(contextWindow)} tokens, reported by your server.`; + if (source === 'default') { + return `Context window: ${tokens(contextWindow)} tokens. Your server did not report one, so this is the default. Enter your model's real size to raise it.`; + } + const reported = definition?.reportedContextWindow; + return `Context window: ${tokens(contextWindow)} tokens, set by you.` + + (reported && reported !== contextWindow ? ` Your server reports ${tokens(reported)}.` : ''); +} + +export function describeContextCheck(result: OpenAICompatibleContextCheckResult): ContextNote { + switch (result.kind) { + case 'fits': + return { text: `Checked: the server read ${tokens(result.promptTokens)} tokens without trouble.`, warning: false }; + case 'fits-unmeasured': + return { text: 'The server accepted a prompt of this size, but it does not report token counts, so Nexus cannot confirm it read the whole prompt.', warning: false }; + case 'truncated': + // No "Use" button: servers that shorten prompts may keep less than they + // hold. Ollama keeps about half its context, so this count understates it. + return { + text: `The server read only ${tokens(result.promptTokens)} tokens of the prompt. It shortens long prompts instead of refusing them, so its context is smaller than this size. Servers such as Ollama keep less than their full context when they shorten a prompt, so enter the size your server runs the model with.`, + warning: true, + }; + case 'too-large': + return result.serverLimit + ? { text: `Too large: the server says its limit is ${tokens(result.serverLimit)} tokens.`, warning: true, suggestion: result.serverLimit } + : { text: `Too large: the server refused a prompt of this size. It said: ${result.message}`, warning: true }; + case 'failed': + return { text: `Check failed. ${result.message}`, warning: true }; + } +} + export interface OpenAICompatibleModalOptions { getProviders: () => Record; save: (id: string, config: CompatibleEndpointConfig) => Promise; @@ -26,6 +71,7 @@ export class OpenAICompatibleModal extends Modal { private saveVersion = 0; private saveQueue: Promise = Promise.resolve(); private closing = false; + private readonly checks = new Set(); constructor(app: App, private readonly options: OpenAICompatibleModalOptions) { super(app); @@ -40,6 +86,7 @@ export class OpenAICompatibleModal extends Modal { onClose(): void { this.opened = false; this.clearSaveTimer(); + this.abortChecks(); // Escape and the native X also flush the latest valid draft. The save queue // outlives the DOM; closing cannot drop a debounced change or resurrect a key. if (this.editor && this.dirty) { @@ -77,6 +124,7 @@ export class OpenAICompatibleModal extends Modal { } private renderList(): void { + this.abortChecks(); this.editor?.close(); this.editor = null; this.dirty = false; @@ -122,6 +170,7 @@ export class OpenAICompatibleModal extends Modal { } private renderEditor(id: string, config: CompatibleEndpointConfig): void { + this.abortChecks(); this.editor?.close(); const editor = new OpenAICompatibleEditSession(id, config, (endpointId, snapshot) => this.persist(endpointId, snapshot)); this.editor = editor; @@ -207,14 +256,93 @@ export class OpenAICompatibleModal extends Modal { const models = Object.keys(editor.draft.openaiCompatible.models); if (!models.length) return; this.models.createEl('h2', { text: 'Available models' }); - for (const model of models) { - new Setting(this.models).setName(model).addToggle(toggle => { - toggle.setValue(editor.draft.models?.[model]?.enabled !== false).onChange(enabled => { - editor.setModelEnabled(model, enabled); - this.changed(); + this.models.createEl('p', { + cls: 'setting-item-description', + text: 'Each model uses the context window your server reports. If it reports none, enter the size your server runs the model with. Check sends one prompt of that size to confirm the server accepts it.', + }); + for (const model of models) this.renderModel(editor, model); + } + + private renderModel(editor: OpenAICompatibleEditSession, model: string): void { + const setting = new Setting(this.models).setName(model); + setting.settingEl.addClass('nexus-compatible-model'); + let note: ContextNote | null = null; + let input: HTMLInputElement | null = null; + const describe = (): void => { + setting.descEl.empty(); + setting.descEl.createDiv({ text: describeContextWindow(editor.draft.openaiCompatible.models[model]) }); + if (!note) return; + const line = setting.descEl.createDiv({ cls: note.warning ? 'nexus-compatible-check mod-warning' : 'nexus-compatible-check', text: note.text }); + line.setAttribute('role', 'status'); + const suggestion = note.suggestion; + if (suggestion === undefined) return; + new ButtonComponent(line).setButtonText(`Use ${tokens(suggestion)}`).setClass('nexus-compatible-use-limit').onClick(() => { + if (this.editor !== editor) return; + const shown = editor.useContextWindow(model, suggestion); + if (input) input.value = shown; + note = null; + this.changed(); + describe(); + }); + }; + setting.addText(text => { + input = text.inputEl; + text.inputEl.type = 'number'; + text.inputEl.setAttr('min', '256'); + text.inputEl.setAttr('step', '1'); + text.inputEl.setAttr('aria-label', `Context window for ${model}, in tokens`); + text.inputEl.addClass('nexus-compatible-context-input'); + const definition = editor.draft.openaiCompatible.models[model]; + text.setPlaceholder(String(resolveOpenAICompatibleContextWindow({ ...definition, contextWindow: undefined }).contextWindow)) + .setValue(definition?.contextWindow ? String(definition.contextWindow) : '') + .onChange(value => { + const trimmed = value.trim(); + try { + editor.setContextWindow(model, trimmed === '' ? undefined : Number(trimmed)); + note = null; + this.changed(); + } catch (error) { + note = { text: error instanceof Error ? error.message : 'Enter a whole number of tokens.', warning: true }; + } + describe(); + }); + }); + setting.addButton(button => { + button.setButtonText('Check') + .setTooltip('Sends one prompt of this size to your server. Large sizes can take minutes on local hardware, and hosted endpoints bill the input tokens.') + .onClick(async () => { + const size = resolveOpenAICompatibleContextWindow(editor.draft.openaiCompatible.models[model]).contextWindow; + const controller = new AbortController(); + this.checks.add(controller); + button.setDisabled(true).setButtonText('Checking…'); + note = { text: `Sending a prompt of about ${tokens(size)} tokens…`, warning: false }; + describe(); + try { + const result = await editor.checkContextWindow(model, controller.signal); + if (controller.signal.aborted || this.editor !== editor) return; + note = describeContextCheck(result); + } catch (error) { + if (controller.signal.aborted || this.editor !== editor) return; + note = { text: `Check failed. ${error instanceof Error ? error.message : 'The server could not be reached.'}`, warning: true }; + } finally { + this.checks.delete(controller); + button.setDisabled(false).setButtonText('Check'); + } + describe(); }); + }); + setting.addToggle(toggle => { + toggle.setValue(editor.draft.models?.[model]?.enabled !== false).onChange(enabled => { + editor.setModelEnabled(model, enabled); + this.changed(); }); - } + }); + describe(); + } + + private abortChecks(): void { + for (const controller of this.checks) controller.abort(); + this.checks.clear(); } private changed(): void { diff --git a/src/services/llm/adapters/openai-compatible/OpenAICompatibleAdapter.ts b/src/services/llm/adapters/openai-compatible/OpenAICompatibleAdapter.ts index 84a41a73c..59814470a 100644 --- a/src/services/llm/adapters/openai-compatible/OpenAICompatibleAdapter.ts +++ b/src/services/llm/adapters/openai-compatible/OpenAICompatibleAdapter.ts @@ -137,7 +137,7 @@ export class OpenAICompatibleAdapter extends BaseAdapter { return { supportsStreaming: true, streamingMode: 'streaming', supportsFunctions: true, supportsThinking: true, supportsJSON: false, supportsImages: false, - maxContextWindow: OPENAI_COMPATIBLE_CONTEXT_WINDOW, + maxContextWindow: Math.max(OPENAI_COMPATIBLE_CONTEXT_WINDOW, ...this.savedModels.map(model => model.contextWindow)), supportedFeatures: ['messages', 'streaming', 'function_calling'], }; } diff --git a/src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig.ts b/src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig.ts index 140ef1e38..6836cd8ae 100644 --- a/src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig.ts +++ b/src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig.ts @@ -1,23 +1,85 @@ import type { LLMProviderConfig } from '../../../../types'; +import type { OpenAICompatibleModelDefinition } from '../../../../types/llm/ProviderTypes'; import { ProviderHttpClient } from '../shared/ProviderHttpClient'; +import { getContextWindowOverrideKey } from '../../../../ui/chat/utils/ContextWindowSettings'; import type { ModelInfo } from '../types'; export const OPENAI_COMPATIBLE_GENERATION_TIMEOUT_MS = 600_000; +/** Used only when neither the user nor the server has given a context window. */ export const OPENAI_COMPATIBLE_CONTEXT_WINDOW = 4096; export const OPENAI_COMPATIBLE_MAX_OUTPUT_TOKENS = 1024; +export const OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW = 256; +/** Rejects typos such as an extra digit group; no current model is near this. */ +export const OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW = 16_777_216; + +export function isOpenAICompatibleContextWindow(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) + && value >= OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW && value <= OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW; +} + +export type OpenAICompatibleContextSource = 'user' | 'server' | 'default'; + +/** The user's value wins, then what the server reported, then the conservative default. */ +export function resolveOpenAICompatibleContextWindow( + definition: OpenAICompatibleModelDefinition | undefined, +): { contextWindow: number; source: OpenAICompatibleContextSource } { + if (isOpenAICompatibleContextWindow(definition?.contextWindow)) return { contextWindow: definition.contextWindow, source: 'user' }; + if (isOpenAICompatibleContextWindow(definition?.reportedContextWindow)) { + return { contextWindow: definition.reportedContextWindow, source: 'server' }; + } + return { contextWindow: OPENAI_COMPATIBLE_CONTEXT_WINDOW, source: 'default' }; +} /** Persisted model IDs remain available even when the server is offline. */ export function buildOpenAICompatibleModels(config: LLMProviderConfig): ModelInfo[] { - return Object.keys(config.openaiCompatible?.models ?? {}) + const definitions = config.openaiCompatible?.models ?? {}; + return Object.keys(definitions) .filter(id => isOpenAICompatibleModelId(id) && config.models?.[id]?.enabled !== false) .map(id => ({ - id, name: id, contextWindow: OPENAI_COMPATIBLE_CONTEXT_WINDOW, + id, name: id, contextWindow: resolveOpenAICompatibleContextWindow(definitions[id]).contextWindow, maxOutputTokens: OPENAI_COMPATIBLE_MAX_OUTPUT_TOKENS, supportsStreaming: true, supportsFunctions: true, supportsThinking: true, supportsImages: false, supportsJSON: false, pricing: null, })); } +export interface ContextOverrideRelease { + map: Record; + key: string; + value: number; +} + +/** + * Saving chat settings stores the model's whole window as its override, so a + * model that sat at the 4,096 fallback carries an override of exactly 4,096. + * When an endpoint save raises a model's window, an override equal to the old + * maximum meant "use all of it" and would otherwise pin the chat at the old + * size; it is removed. Smaller overrides were deliberate and stay. Returns what + * was removed so a failed save can put it back. + */ +export function releaseRaisedContextOverrides( + providerId: string, + previous: LLMProviderConfig | undefined, + next: LLMProviderConfig, + overrideMaps: Array | undefined>, +): ContextOverrideRelease[] { + const released: ContextOverrideRelease[] = []; + const before = previous?.openaiCompatible?.models; + if (!before) return released; + for (const [model, definition] of Object.entries(next.openaiCompatible?.models ?? {})) { + if (!Object.prototype.hasOwnProperty.call(before, model)) continue; + const oldMaximum = resolveOpenAICompatibleContextWindow(before[model]).contextWindow; + if (resolveOpenAICompatibleContextWindow(definition).contextWindow <= oldMaximum) continue; + const key = getContextWindowOverrideKey(providerId, model); + for (const map of overrideMaps) { + if (map?.[key] !== oldMaximum) continue; + released.push({ map, key, value: oldMaximum }); + delete map[key]; + } + } + return released; +} + export function normalizeOpenAICompatibleBaseUrl(value: string): string { const url = new URL(value.trim()); const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname); @@ -61,10 +123,62 @@ export function validateOpenAICompatibleConfig(config: LLMProviderConfig): strin return normalizeOpenAICompatibleBaseUrl(endpoint.baseUrl); } +export interface DiscoveredOpenAICompatibleModel { + id: string; + /** Present only when the server reported the context it actually serves. */ + contextWindow?: number; +} + +function positiveInteger(value: unknown): number | undefined { + const parsed = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value; + return isOpenAICompatibleContextWindow(parsed) ? parsed : undefined; +} + +function record(value: unknown): Record | undefined { + return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; +} + +/** + * Field names servers use for the context they serve, most specific first: + * vLLM/SGLang `max_model_len`; OpenRouter, Together and Bifrost `context_length`; + * Groq and Bifrost's OpenAI route `context_window`; Mistral and LM Studio + * `max_context_length`; OpenRouter `top_provider.context_length`. + * llama.cpp's `meta.n_ctx_train` is deliberately absent: it is the trained + * maximum, not what the server allocated, so it comes from `/props` instead. + */ +export function readReportedContextWindow(entry: unknown): number | undefined { + const item = record(entry); + if (!item) return undefined; + for (const key of ['max_model_len', 'context_length', 'context_window', 'max_context_length']) { + const value = positiveInteger(item[key]); + if (value !== undefined) return value; + } + return positiveInteger(record(item.top_provider)?.context_length); +} + +/** llama.cpp serves `/props` beside `/v1`; its slot context is what one request can use. */ +async function readLlamaCppContextWindow(baseUrl: string, apiKey: string): Promise { + try { + const url = new URL(baseUrl); + url.pathname = url.pathname.replace(/\/v1$/i, ''); + const response = await ProviderHttpClient.request({ + url: `${url.href.replace(/\/+$/, '')}/props`, + provider: 'openai-compatible', operation: 'context discovery', method: 'GET', + headers: openAICompatibleHeaders(apiKey), timeoutMs: 10_000, retries: 0, + }); + if (!response.ok) return undefined; + const props = record(response.json); + return positiveInteger(record(props?.default_generation_settings)?.n_ctx) ?? positiveInteger(props?.n_ctx); + } catch { + return undefined; + } +} + /** Discovery only: never sends a generation request or invents a model identifier. */ -export async function discoverOpenAICompatibleModels(baseUrl: string, apiKey: string): Promise { +export async function discoverOpenAICompatibleModels(baseUrl: string, apiKey: string): Promise { + const normalized = normalizeOpenAICompatibleBaseUrl(baseUrl); const response = await ProviderHttpClient.request({ - url: `${normalizeOpenAICompatibleBaseUrl(baseUrl)}/models`, + url: `${normalized}/models`, provider: 'openai-compatible', operation: 'model discovery', method: 'GET', headers: openAICompatibleHeaders(apiKey), timeoutMs: 30_000, retries: 0, }); @@ -73,10 +187,19 @@ export async function discoverOpenAICompatibleModels(baseUrl: string, apiKey: st if (!data || typeof data !== 'object' || !Array.isArray((data as Record).data)) { throw new Error('Model discovery did not return a data array. Add a model ID manually.'); } - const ids = (data as { data: unknown[] }).data.flatMap(item => { - if (!item || typeof item !== 'object') return []; - const id = (item as Record).id; - return isOpenAICompatibleModelId(id) ? [id] : []; - }); - return [...new Set(ids)]; + const entries = (data as { data: unknown[] }).data; + const models = new Map(); + for (const entry of entries) { + const id = record(entry)?.id; + if (!isOpenAICompatibleModelId(id) || models.has(id)) continue; + const contextWindow = readReportedContextWindow(entry); + models.set(id, contextWindow === undefined ? { id } : { id, contextWindow }); + } + // A single-model llama.cpp server marks its entry with `meta`; ask it what it allocated. + const only = models.size === 1 ? [...models.values()][0] : undefined; + if (only && only.contextWindow === undefined && entries.some(entry => record(record(entry)?.meta))) { + const contextWindow = await readLlamaCppContextWindow(normalized, apiKey); + if (contextWindow !== undefined) only.contextWindow = contextWindow; + } + return [...models.values()]; } diff --git a/src/services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck.ts b/src/services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck.ts new file mode 100644 index 000000000..4f1f498e3 --- /dev/null +++ b/src/services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck.ts @@ -0,0 +1,146 @@ +import { ProviderHttpClient } from '../shared/ProviderHttpClient'; +import { TokenUsageExtractor } from '../../utils/TokenUsageExtractor'; +import { + isOpenAICompatibleContextWindow, normalizeOpenAICompatibleBaseUrl, + OPENAI_COMPATIBLE_GENERATION_TIMEOUT_MS, openAICompatibleHeaders, +} from './OpenAICompatibleConfig'; + +/** + * Asks the server whether a prompt of the chosen context size fits, because most + * OpenAI-compatible servers never say. Runs only when the user presses Check: + * a prompt that fits is read in full, which takes time locally and is billed by + * hosted endpoints. + */ +export type OpenAICompatibleContextCheckResult = + /** The server read about `promptTokens` tokens without complaint. */ + | { kind: 'fits'; promptTokens: number } + /** Accepted, but the server reports no token counts, so silent truncation cannot be ruled out. */ + | { kind: 'fits-unmeasured' } + /** Accepted, but the server read far fewer tokens than were sent: it cut the prompt down. */ + | { kind: 'truncated'; promptTokens: number } + /** Refused as too long; `serverLimit` is the size the server named, when it named one. */ + | { kind: 'too-large'; serverLimit?: number; message: string } + | { kind: 'failed'; message: string }; + +export interface OpenAICompatibleContextCheckRequest { + baseUrl: string; + apiKey: string; + model: string; + contextWindow: number; + signal?: AbortSignal; +} + +/** Ordinary prose tokenizes predictably; about ten tokens per repeat in common vocabularies. */ +const FILLER = 'The quick brown fox jumps over the lazy dog. '; +const ASSUMED_TOKENS_PER_FILLER = 10; +const CALIBRATION_SMALL = 4; +const CALIBRATION_LARGE = 16; +/** Leaves room for one output token and rounding in the calibration. */ +const RESERVED_TOKENS = 8; +/** A count this far under the prediction means the server dropped part of the prompt. */ +const TRUNCATION_RATIO = 0.9; + +const CONTEXT_ERROR = /context|too long|too large|exceed|maximum.{0,40}(length|tokens)|max_model_len|n_ctx|prompt is too/i; +const LIMIT_PATTERNS = [ + /maximum context length is (\d[\d,]*)/i, + /max_model_len\D{0,5}(\d[\d,]*)/i, + /\bn_ctx\b\D{0,5}(\d[\d,]*)/i, + // llama.cpp: "exceeds the available context size (2048 tokens)". + /context (?:length|size|window)(?: of| is|:)? \(?(\d[\d,]*)/i, +]; + +interface Attempt { + ok: boolean; + status: number; + promptTokens?: number; + detail: string; + json: unknown; +} + +function errorDetail(json: unknown, text: string): string { + const body = json && typeof json === 'object' ? json as Record : undefined; + const error = body?.error; + if (typeof error === 'string') return error; + if (error && typeof error === 'object' && typeof (error as Record).message === 'string') { + return (error as Record).message as string; + } + for (const key of ['message', 'detail']) { + const value = body?.[key]; + if (typeof value === 'string') return value; + } + return text.slice(0, 500); +} + +/** The limit a refusal names: llama.cpp sends `n_ctx` as a field, others put it in the sentence. */ +export function readContextLimitFromError(json: unknown, detail: string, tested: number): number | undefined { + const body = json && typeof json === 'object' ? json as Record : undefined; + const nested = body?.error && typeof body.error === 'object' ? body.error as Record : undefined; + const candidates: unknown[] = [nested?.n_ctx, body?.n_ctx]; + for (const pattern of LIMIT_PATTERNS) { + const match = pattern.exec(detail); + if (match) candidates.push(Number(match[1].replace(/,/g, ''))); + } + return candidates.find((value): value is number => isOpenAICompatibleContextWindow(value) && value < tested); +} + +async function send(request: OpenAICompatibleContextCheckRequest, repeats: number): Promise { + const response = await ProviderHttpClient.request({ + url: `${normalizeOpenAICompatibleBaseUrl(request.baseUrl)}/chat/completions`, + provider: 'openai-compatible', operation: 'context check', method: 'POST', + headers: openAICompatibleHeaders(request.apiKey), + body: JSON.stringify({ + model: request.model, stream: false, max_tokens: 1, temperature: 0, + messages: [{ role: 'user', content: FILLER.repeat(repeats) }], + }), + timeoutMs: OPENAI_COMPATIBLE_GENERATION_TIMEOUT_MS, signal: request.signal, retries: 0, + }); + const body = response.json && typeof response.json === 'object' ? response.json as Record : undefined; + const promptTokens = TokenUsageExtractor.normalize(body?.usage)?.promptTokens; + return { + ok: response.ok, status: response.status, json: response.json, + promptTokens: typeof promptTokens === 'number' && promptTokens > 0 ? promptTokens : undefined, + detail: response.ok ? '' : errorDetail(response.json, response.text), + }; +} + +function failure(attempt: Attempt): OpenAICompatibleContextCheckResult { + return { kind: 'failed', message: `The server returned HTTP ${attempt.status}${attempt.detail ? `: ${attempt.detail}` : '.'}` }; +} + +export async function checkOpenAICompatibleContextWindow( + request: OpenAICompatibleContextCheckRequest, +): Promise { + if (!isOpenAICompatibleContextWindow(request.contextWindow)) { + return { kind: 'failed', message: 'Enter a context window before checking it.' }; + } + // Two small prompts measure this tokenizer: tokens per repeat, and the fixed + // cost of the chat template around the message. + const small = await send(request, CALIBRATION_SMALL); + if (!small.ok) return failure(small); + const large = await send(request, CALIBRATION_LARGE); + if (!large.ok) return failure(large); + + const measured = small.promptTokens !== undefined && large.promptTokens !== undefined + && large.promptTokens > small.promptTokens; + const perRepeat = measured + ? (large.promptTokens! - small.promptTokens!) / (CALIBRATION_LARGE - CALIBRATION_SMALL) + : ASSUMED_TOKENS_PER_FILLER; + const overhead = measured ? Math.max(0, small.promptTokens! - CALIBRATION_SMALL * perRepeat) : 0; + const target = request.contextWindow - RESERVED_TOKENS; + const repeats = Math.max(CALIBRATION_LARGE, Math.floor((target - overhead) / perRepeat)); + const expected = overhead + repeats * perRepeat; + + const full = await send(request, repeats); + if (!full.ok) { + const refusedForSize = full.status === 413 || CONTEXT_ERROR.test(full.detail); + if (!refusedForSize) return failure(full); + return { + kind: 'too-large', + serverLimit: readContextLimitFromError(full.json, full.detail, request.contextWindow), + message: full.detail || `The server refused the prompt (HTTP ${full.status}).`, + }; + } + if (!measured || full.promptTokens === undefined) return { kind: 'fits-unmeasured' }; + if (full.promptTokens < expected * TRUNCATION_RATIO) return { kind: 'truncated', promptTokens: full.promptTokens }; + return { kind: 'fits', promptTokens: full.promptTokens }; +} diff --git a/src/settings/tabs/ProvidersTab.ts b/src/settings/tabs/ProvidersTab.ts index e276eb84f..46e59f530 100644 --- a/src/settings/tabs/ProvidersTab.ts +++ b/src/settings/tabs/ProvidersTab.ts @@ -28,6 +28,7 @@ import { GeminiCliAuthService } from '../../services/external/GeminiCliAuthServi import { BRAND_NAME } from '../../constants/branding'; import { OpenAICompatibleModal } from '../../components/openai-compatible/OpenAICompatibleModal'; import { isCompatibleEndpoint } from '../../components/openai-compatible/OpenAICompatibleEditSession'; +import { releaseRaisedContextOverrides } from '../../services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; import { getDeviceOAuthState, usesDeviceOAuthTokens } from '../../services/oauth/DeviceOAuthState'; /** @@ -654,6 +655,8 @@ export class ProvidersTab { save: async (id, config) => { const settings = this.getSettings(); const previous = settings.providers[id]; + const released = releaseRaisedContextOverrides(id, previous, config, + [settings.contextWindowOverrides, settings.agentContextWindowOverrides]); settings.providers[id] = config; try { await this.saveSettings(); @@ -661,6 +664,7 @@ export class ProvidersTab { } catch (error) { if (previous) settings.providers[id] = previous; else delete settings.providers[id]; + for (const { map, key, value } of released) map[key] = value; throw error; } }, diff --git a/src/types/chat/ChatTypes.ts b/src/types/chat/ChatTypes.ts index e700e872d..e8b419fb7 100644 --- a/src/types/chat/ChatTypes.ts +++ b/src/types/chat/ChatTypes.ts @@ -161,6 +161,8 @@ export interface Conversation { modelId?: string; /** Budget committed together with this chat's model and compaction boundary. */ effectiveContextWindow?: number; + /** The model's whole window when that budget was committed. */ + modelContextWindow?: number; systemPrompt?: string; workspaceId?: string; sessionId?: string; diff --git a/src/types/llm/ProviderTypes.ts b/src/types/llm/ProviderTypes.ts index 9582d6c79..0c8c1675c 100644 --- a/src/types/llm/ProviderTypes.ts +++ b/src/types/llm/ProviderTypes.ts @@ -38,6 +38,15 @@ export interface ModelConfig { description?: string; // Optional user-defined description (for backwards compatibility) } +/** One saved model on an OpenAI-compatible endpoint. */ +export interface OpenAICompatibleModelDefinition { + source: 'discovered' | 'manual'; + /** Context window the user entered; it wins over anything the server reports. */ + contextWindow?: number; + /** Context window the server reported during discovery; refreshed on each Connect. */ + reportedContextWindow?: number; +} + /** * LLM provider configuration */ @@ -48,7 +57,7 @@ export interface LLMProviderConfig { schemaVersion: 1; displayName: string; baseUrl: string; - models: Record; + models: Record; }; apiKey: string; userDescription?: string; diff --git a/src/ui/chat/ChatView.ts b/src/ui/chat/ChatView.ts index bedc41b9e..fe329c1ce 100644 --- a/src/ui/chat/ChatView.ts +++ b/src/ui/chat/ChatView.ts @@ -67,6 +67,7 @@ import type { ToolEventData as ChatServiceToolEventData } from '../../services/c import type { BranchViewContext } from './components/BranchHeader'; import type { OverloadRetryNotice } from '../../services/llm/adapters/types'; import { describeOverloadRetry } from '../../services/llm/adapters/shared/ProviderErrorMessages'; +import { LLMSettingsNotifier } from '../../services/llm/LLMSettingsNotifier'; export const CHAT_VIEW_TYPE = CHAT_VIEW_TYPES.current; type ChatToolEventData = Parameters[2]; @@ -839,6 +840,14 @@ export class ChatView extends ItemView { }) ); + // A provider save can change the selected model's window, e.g. an + // OpenAI-compatible model raised from its 4,096 fallback. + this.registerEvent(LLMSettingsNotifier.onSettingsChanged(() => { + void this.modelAgentManager.followModelWindowChange() + .then(() => this.updateContextProgress()) + .catch(error => console.error('[ChatView] Failed to refresh the model window:', error)); + })); + // Refresh conversation list / active conversation when Obsidian Sync // lands JSONL updates from another device. The adapter has already // reconciled SQLite by the time this fires — we just re-query. diff --git a/src/ui/chat/services/ModelAgentConversationSettingsStore.ts b/src/ui/chat/services/ModelAgentConversationSettingsStore.ts index 5255edde4..26dd04312 100644 --- a/src/ui/chat/services/ModelAgentConversationSettingsStore.ts +++ b/src/ui/chat/services/ModelAgentConversationSettingsStore.ts @@ -15,6 +15,8 @@ export interface ConversationSettingsMetadata { modelId?: string; /** Committed budget for this conversation, independent of later global defaults. */ effectiveContextWindow?: number; + /** The model's whole window when that budget was committed; tells "all of it" from a smaller choice. */ + modelContextWindow?: number; promptId?: string | null; workspaceId?: string | null; sessionId?: string | null; @@ -146,7 +148,8 @@ export class ModelAgentConversationSettingsStore { ...latestMetadata.chatSettings, providerId: metadata.chatSettings?.providerId ?? sourceSettings?.providerId, modelId: metadata.chatSettings?.modelId ?? sourceSettings?.modelId, - effectiveContextWindow: metadata.chatSettings?.effectiveContextWindow ?? sourceSettings?.effectiveContextWindow + effectiveContextWindow: metadata.chatSettings?.effectiveContextWindow ?? sourceSettings?.effectiveContextWindow, + modelContextWindow: metadata.chatSettings?.modelContextWindow ?? sourceSettings?.modelContextWindow }, compaction: metadata.compaction ?? { frontier: [] } }; diff --git a/src/ui/chat/services/ModelAgentManager.ts b/src/ui/chat/services/ModelAgentManager.ts index dd9dec462..d0c10b489 100644 --- a/src/ui/chat/services/ModelAgentManager.ts +++ b/src/ui/chat/services/ModelAgentManager.ts @@ -29,7 +29,8 @@ import { type ModelAgentPromptContextSnapshot, } from './ModelAgentPromptContextAssembler'; import { ModelSelectionUtility } from '../utils/ModelSelectionUtility'; -import { getContextWindowOverrideKey, resolveContextWindowLimit } from '../utils/ContextWindowSettings'; +import { followRaisedContextWindow, getContextWindowOverrideKey, resolveContextWindowLimit } from '../utils/ContextWindowSettings'; +import { OPENAI_COMPATIBLE_CONTEXT_WINDOW } from '../../../services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; import { PromptConfigurationUtility } from '../utils/PromptConfigurationUtility'; import { WorkspaceIntegrationService } from './WorkspaceIntegrationService'; import { StaticModelsService } from '../../../services/StaticModelsService'; @@ -300,7 +301,10 @@ export class ModelAgentManager { if (model) { this.selectedModel = model; this.committedContextWindow = typeof settings.effectiveContextWindow === 'number' - ? resolveContextWindowLimit(model.contextWindow, settings.effectiveContextWindow) + ? followRaisedContextWindow( + settings.effectiveContextWindow, + settings.modelContextWindow ?? this.legacyCommittedMaximum(model.providerId), + model.contextWindow) : this.resolveConfiguredContextWindow(model); this.updateCompactionFrontierPolicy(model); this.updateContextTokenTracker(model.providerId); @@ -637,9 +641,15 @@ export class ModelAgentManager { try { metadata = await this.conversationSettingsStore.commitHandoff( conversationId, - { providerId: model.providerId, modelId: model.modelId, effectiveContextWindow: window, sessionId: this.pendingSessionId }, + { + providerId: model.providerId, modelId: model.modelId, effectiveContextWindow: window, + modelContextWindow: model.contextWindow, sessionId: this.pendingSessionId + }, frontier, - { providerId: source?.providerId, modelId: source?.modelId, effectiveContextWindow: source?.contextWindow, sessionId: this.pendingSessionId } + { + providerId: source?.providerId, modelId: source?.modelId, effectiveContextWindow: source?.contextWindow, + modelContextWindow: sourceModel?.contextWindow, sessionId: this.pendingSessionId + } ); } catch (error) { if (error instanceof ContextHandoffRecoveryError) { @@ -779,6 +789,36 @@ export class ModelAgentManager { return resolveContextWindowLimit(model.contextWindow, override); } + /** + * Chats saved before the model's whole window was recorded. On an + * OpenAI-compatible endpoint the only window they could commit was the + * 4,096 fallback, so that value meant "all of it". Elsewhere it is unknown. + */ + private legacyCommittedMaximum(providerId: string): number | undefined { + return providerId.startsWith('openai-compatible-') ? OPENAI_COMPATIBLE_CONTEXT_WINDOW : undefined; + } + + /** + * Re-read the selected model after provider settings change. When its window + * grew and this chat was using all of the old window, the chat follows the + * new one; a smaller budget the user chose is kept. Nothing is persisted + * here: the next save records it, and a reload reaches the same answer. + */ + async followModelWindowChange(): Promise { + const current = this.selectedModel; + if (!current || this.contextHandoffPromise) return; + const generation = this.modelSelectionGeneration; + const refreshed = await this.resolveModelOption(current.providerId, current.modelId); + if (!refreshed || this.contextHandoffPromise || generation !== this.modelSelectionGeneration + || this.selectedModel !== current || refreshed.contextWindow === current.contextWindow) return; + const budget = this.getEffectiveContextWindow(); + this.selectedModel = refreshed; + this.committedContextWindow = followRaisedContextWindow(budget, current.contextWindow, refreshed.contextWindow); + this.updateCompactionFrontierPolicy(refreshed); + this.updateContextTokenTracker(refreshed.providerId); + this.events.onModelChanged(refreshed); + } + refreshContextWindowLimit(): void { // Global settings are defaults for future conversations. An active budget // changes only through requestContextChange and its durable handoff. @@ -1343,6 +1383,7 @@ export class ModelAgentManager { providerId: this.selectedModel?.providerId, modelId: this.selectedModel?.modelId, effectiveContextWindow: this.getEffectiveContextWindow(), + modelContextWindow: this.selectedModel?.contextWindow, promptId: this.selectedPrompt?.id ?? null, workspaceId: this.selectedWorkspaceId, sessionId: this.pendingSessionId, diff --git a/src/ui/chat/utils/ContextWindowSettings.ts b/src/ui/chat/utils/ContextWindowSettings.ts index 26d823bd3..547caa266 100644 --- a/src/ui/chat/utils/ContextWindowSettings.ts +++ b/src/ui/chat/utils/ContextWindowSettings.ts @@ -10,3 +10,17 @@ export function resolveContextWindowLimit(advertised: number, override?: number) if (typeof override !== 'number' || !Number.isFinite(override) || override <= 0) return maximum; return Math.max(Math.min(1024, maximum), Math.min(maximum, Math.floor(override))); } + +/** + * A chat budget saved at the model's whole window meant "use all of it", so it + * follows the window when the window later grows (an OpenAI-compatible model + * raised from its 4,096 fallback). A smaller budget was the user's choice and + * stays, clamped to the current window. + */ +export function followRaisedContextWindow(budget: number, maximumWhenSaved: number | undefined, maximum: number): number { + if (typeof maximumWhenSaved === 'number' && budget >= maximumWhenSaved + && Number.isFinite(maximum) && maximum > budget) { + return Math.floor(maximum); + } + return resolveContextWindowLimit(maximum, budget); +} diff --git a/styles.css b/styles.css index 8072d8ad2..d5adc238f 100644 --- a/styles.css +++ b/styles.css @@ -3506,6 +3506,34 @@ body.is-mobile .nexus-remote-agent-modal button { margin-top: var(--space-l); } +.nexus-compatible-modal .nexus-compatible-context-input { + width: 120px; + max-width: 100%; +} + +/* The field, Check and toggle keep their width; the description wraps beside them. */ +.nexus-compatible-modal .nexus-compatible-model .setting-item-control { + flex-shrink: 0; +} + +/* Keep the window line and the check note stacked even when a theme or another + plugin makes every setting description a flex row. */ +.nexus-compatible-modal .nexus-compatible-model .setting-item-description { + display: block; +} + +.nexus-compatible-check { + margin-top: var(--space-xs); +} + +.nexus-compatible-check.mod-warning { + color: var(--text-warning); +} + +.nexus-compatible-check .nexus-compatible-use-limit { + margin-left: var(--space-s); +} + .nexus-compatible-manual summary { cursor: pointer; color: var(--text-muted); @@ -3519,7 +3547,8 @@ body.is-mobile .nexus-remote-agent-modal button { margin-top: var(--space-l); } -body.is-mobile .nexus-compatible-modal > .provider-modal-content > .setting-item { +body.is-mobile .nexus-compatible-modal > .provider-modal-content > .setting-item, +body.is-mobile .nexus-compatible-modal .nexus-compatible-model { flex-wrap: wrap; } diff --git a/tests/debug/openai-compatible-context-live.test.ts b/tests/debug/openai-compatible-context-live.test.ts new file mode 100644 index 000000000..d8f70597f --- /dev/null +++ b/tests/debug/openai-compatible-context-live.test.ts @@ -0,0 +1,55 @@ +/** RUN_COMPATIBLE_CONTEXT_LIVE=1 COMPATIBLE_CONTEXT_BASE_URL=http://127.0.0.1:8080/v1 \ + * COMPATIBLE_CONTEXT_SERVED=2048 npx jest tests/debug/openai-compatible-context-live.test.ts --runInBand --no-coverage + * + * Context discovery and the Check request against a real, already-running server + * started with a known context (llama.cpp `-c 2048`, vLLM `--max-model-len 2048`). + * Set COMPATIBLE_CONTEXT_OVERSIZE=truncated for servers that shorten long prompts + * instead of refusing them (Ollama), and COMPATIBLE_CONTEXT_REPORTED=none for + * servers whose model list carries no context size (Ollama's /v1). Ollama: + * COMPATIBLE_CONTEXT_BASE_URL=http://127.0.0.1:11434/v1 COMPATIBLE_CONTEXT_MODEL= + * COMPATIBLE_CONTEXT_SERVED= COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none + * requestUrl is bridged to fetch; not in-app proof. + */ +import { __setRequestUrlMock } from '../mocks/obsidian'; +import { discoverOpenAICompatibleModels } from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; +import { checkOpenAICompatibleContextWindow } from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck'; + +const describeLive = process.env.RUN_COMPATIBLE_CONTEXT_LIVE === '1' ? describe : describe.skip; +describeLive('OpenAI-compatible context window against a live server', () => { + const baseUrl = process.env.COMPATIBLE_CONTEXT_BASE_URL || 'http://127.0.0.1:8080/v1'; + const apiKey = process.env.COMPATIBLE_CONTEXT_API_KEY || ''; + const served = Number(process.env.COMPATIBLE_CONTEXT_SERVED || '2048'); + const oversize = process.env.COMPATIBLE_CONTEXT_OVERSIZE || 'too-large'; + const reported = process.env.COMPATIBLE_CONTEXT_REPORTED === 'none' ? undefined : served; + let model = process.env.COMPATIBLE_CONTEXT_MODEL || ''; + + beforeAll(async () => { + __setRequestUrlMock(async request => { + const response = await fetch(request.url!, { method: request.method, headers: request.headers, body: request.body }); + const text = await response.text(); + let json: unknown = null; + try { json = JSON.parse(text); } catch { /* not JSON */ } + return { status: response.status, text, json, headers: {}, arrayBuffer: new ArrayBuffer(0) }; + }); + if (!model) model = (await discoverOpenAICompatibleModels(baseUrl, apiKey))[0].id; + }); + + test('discovery reports the served context, or none when the server reports none', async () => { + const found = (await discoverOpenAICompatibleModels(baseUrl, apiKey)).find(entry => entry.id === model); + expect(found).toBeDefined(); + expect(found?.contextWindow).toBe(reported); + }, 60_000); + + test('a Check at the served size fits', async () => { + const result = await checkOpenAICompatibleContextWindow({ baseUrl, apiKey, model, contextWindow: served }); + expect(result.kind).toBe('fits'); + }, 600_000); + + test('a Check at four times the served size is caught', async () => { + const result = await checkOpenAICompatibleContextWindow({ baseUrl, apiKey, model, contextWindow: served * 4 }); + expect(result.kind).toBe(oversize); + if (result.kind === 'too-large' && result.serverLimit !== undefined) expect(result.serverLimit).toBe(served); + // eslint-disable-next-line no-console -- the live lane's evidence is the server's own words + console.log(JSON.stringify(result)); + }, 600_000); +}); diff --git a/tests/unit/ModelAgentManagerRaisedWindow.test.ts b/tests/unit/ModelAgentManagerRaisedWindow.test.ts new file mode 100644 index 000000000..f5543316a --- /dev/null +++ b/tests/unit/ModelAgentManagerRaisedWindow.test.ts @@ -0,0 +1,120 @@ +/** + * Issue #439: a chat that was using a model's whole window must follow the + * window when it grows (an OpenAI-compatible model raised from its 4,096 + * fallback), while a smaller budget the user chose stays put. + */ +import { ModelAgentManager } from '../../src/ui/chat/services/ModelAgentManager'; +import type { ModelOption } from '../../src/ui/chat/types/SelectionTypes'; +import type { ConversationMetadataWithCompaction } from '../../src/ui/chat/services/ModelAgentConversationSettingsStore'; +import { followRaisedContextWindow } from '../../src/ui/chat/utils/ContextWindowSettings'; + +const COMPATIBLE = 'openai-compatible-home'; + +const option = (providerId: string, contextWindow: number): ModelOption => ({ + providerId, providerName: providerId, modelId: 'qwen', modelName: 'qwen', contextWindow +}); + +function persistence(chatSettings: NonNullable) { + let metadata: ConversationMetadataWithCompaction = { chatSettings: { modelId: 'qwen', sessionId: 'session', ...chatSettings }, compaction: { frontier: [] } }; + return { + store: { + getConversation: jest.fn(async () => ({ metadata })), + updateConversationMetadata: jest.fn(async (_id: string, next: Record) => { + metadata = next as ConversationMetadataWithCompaction; + }) + }, + read: () => metadata + }; +} + +const events = () => ({ onModelChanged: jest.fn(), onPromptChanged: jest.fn(), onSystemPromptChanged: jest.fn() }); + +/** Opens the conversation with the model now reporting `currentWindow`. */ +async function reopen(chatSettings: NonNullable, currentWindow: number) { + const { store } = persistence(chatSettings); + const manager = new ModelAgentManager({}, events(), store, 'conversation'); + jest.spyOn(manager, 'resolveModelOption').mockImplementation(async provider => option(provider, currentWindow)); + await manager.initializeFromConversation('conversation'); + return manager; +} + +describe('followRaisedContextWindow', () => { + test('a budget at the old whole window takes the new one', () => { + expect(followRaisedContextWindow(4096, 4096, 32_768)).toBe(32_768); + }); + + test('a smaller budget stays, and every budget is clamped to a smaller window', () => { + expect(followRaisedContextWindow(2048, 4096, 32_768)).toBe(2048); + expect(followRaisedContextWindow(65_536, 65_536, 32_768)).toBe(32_768); + }); + + test('without a record of the old window the budget stays', () => { + expect(followRaisedContextWindow(8192, undefined, 32_768)).toBe(8192); + }); +}); + +describe('a chat reopened after its model window was raised', () => { + test('follows the new window when it was using all of the old one', async () => { + const manager = await reopen({ providerId: COMPATIBLE, effectiveContextWindow: 8192, modelContextWindow: 8192 }, 32_768); + expect(manager.getEffectiveContextWindow()).toBe(32_768); + }); + + test('keeps a smaller budget the user chose', async () => { + const manager = await reopen({ providerId: COMPATIBLE, effectiveContextWindow: 2048, modelContextWindow: 8192 }, 32_768); + expect(manager.getEffectiveContextWindow()).toBe(2048); + }); + + test('follows when an older chat was stuck at the 4,096 fallback', async () => { + // Saved before the whole window was recorded: on an OpenAI-compatible + // endpoint 4,096 was the only window a chat could have. + const manager = await reopen({ providerId: COMPATIBLE, effectiveContextWindow: 4096 }, 32_768); + expect(manager.getEffectiveContextWindow()).toBe(32_768); + }); + + test('keeps an older budget on other providers, where its meaning is unknown', async () => { + const manager = await reopen({ providerId: 'openai-codex', effectiveContextWindow: 4096 }, 200_000); + expect(manager.getEffectiveContextWindow()).toBe(4096); + }); +}); + +describe('an open chat when provider settings raise the window', () => { + function openChat(committedWindow?: number) { + const { store, read } = persistence({ providerId: COMPATIBLE, effectiveContextWindow: 4096 }); + const listeners = events(); + const manager = new ModelAgentManager({}, listeners, store, 'conversation'); + manager.handleModelChange(option(COMPATIBLE, 4096), committedWindow); + const resolve = jest.spyOn(manager, 'resolveModelOption').mockImplementation(async provider => option(provider, 32_768)); + return { manager, listeners, resolve, read }; + } + + test('follows the new window and tells the view', async () => { + const { manager, listeners } = openChat(); + expect(manager.getEffectiveContextWindow()).toBe(4096); + await manager.followModelWindowChange(); + expect(manager.getEffectiveContextWindow()).toBe(32_768); + expect(manager.getSelectedModel()?.contextWindow).toBe(32_768); + expect(listeners.onModelChanged).toHaveBeenLastCalledWith(expect.objectContaining({ contextWindow: 32_768 })); + }); + + test('keeps a smaller budget the user chose', async () => { + const { manager } = openChat(2048); + await manager.followModelWindowChange(); + expect(manager.getEffectiveContextWindow()).toBe(2048); + }); + + test('does nothing when the window did not change', async () => { + const { manager, listeners, resolve } = openChat(); + resolve.mockImplementation(async provider => option(provider, 4096)); + listeners.onModelChanged.mockClear(); + await manager.followModelWindowChange(); + expect(manager.getEffectiveContextWindow()).toBe(4096); + expect(listeners.onModelChanged).not.toHaveBeenCalled(); + }); + + test('records the whole window beside the budget when the chat is next saved', async () => { + const { manager, read } = openChat(); + manager.configureContextHandoff({ prepare: async () => undefined }); + await manager.requestContextChange({ providerId: COMPATIBLE, modelId: 'qwen', contextWindowOverride: 2048 }); + expect(read().chatSettings).toMatchObject({ effectiveContextWindow: 2048, modelContextWindow: 32_768 }); + }); +}); diff --git a/tests/unit/OpenAICompatibleAdapter.test.ts b/tests/unit/OpenAICompatibleAdapter.test.ts index 92741d718..0649cab8f 100644 --- a/tests/unit/OpenAICompatibleAdapter.test.ts +++ b/tests/unit/OpenAICompatibleAdapter.test.ts @@ -32,7 +32,7 @@ describe('OpenAI-compatible configuration', () => { test('discovery sends only GET, deduplicates valid IDs and keeps exact identifiers', async () => { const requests: CapturedRequest[] = []; __setRequestUrlMock(async request => { requests.push(request); return jsonResponse(200, { data: [{ id: 'a/b:latest' }, { id: 'a/b:latest' }, { id: '' }, { id: 'bad\n' }, null, { id: 'manual' }] }); }); - expect(await discoverOpenAICompatibleModels('https://example.test/prefix/v1/', '')).toEqual(['a/b:latest', 'manual']); + expect(await discoverOpenAICompatibleModels('https://example.test/prefix/v1/', '')).toEqual([{ id: 'a/b:latest' }, { id: 'manual' }]); expect(requests).toHaveLength(1); expect(requests[0]).toMatchObject({ url: 'https://example.test/prefix/v1/models', method: 'GET' }); expect(requests[0].body).toBeUndefined(); diff --git a/tests/unit/OpenAICompatibleContextWindow.test.ts b/tests/unit/OpenAICompatibleContextWindow.test.ts new file mode 100644 index 000000000..500f03d30 --- /dev/null +++ b/tests/unit/OpenAICompatibleContextWindow.test.ts @@ -0,0 +1,307 @@ +/** + * Issue #439: OpenAI-compatible models were stuck at 4,096 tokens of context. + * Covers where the context window comes from (user, server report, default), + * that the chat limit can now reach it, and the opt-in Check request. + * + * Fake servers mimic each runtime's real wire shape, including the part that + * matters: vLLM's refusal sentence, llama.cpp's error object with `n_ctx`, and + * Ollama-style silent truncation. Their tokenizer deliberately differs from the + * check's built-in assumption, so a passing "fits" proves calibration ran. + */ +import { __setRequestUrlMock } from '../mocks/obsidian'; +jest.mock('../../src/utils/platform', () => ({ + ...jest.requireActual('../../src/utils/platform'), hasNodeRuntime: () => false, +})); +import type { LLMProviderConfig } from '../../src/types'; +import type { OpenAICompatibleModelDefinition } from '../../src/types/llm/ProviderTypes'; +import { OpenAICompatibleAdapter } from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleAdapter'; +import { + buildOpenAICompatibleModels, discoverOpenAICompatibleModels, readReportedContextWindow, + releaseRaisedContextOverrides, resolveOpenAICompatibleContextWindow, +} from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; +import { + checkOpenAICompatibleContextWindow, readContextLimitFromError, +} from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck'; +import { CompatibleEndpointConfig, OpenAICompatibleEditSession } from '../../src/components/openai-compatible/OpenAICompatibleEditSession'; +import { describeContextCheck, describeContextWindow } from '../../src/components/openai-compatible/OpenAICompatibleModal'; +import { getContextWindowOverrideKey, resolveContextWindowLimit } from '../../src/ui/chat/utils/ContextWindowSettings'; +import { jsonResponse, type CapturedRequest } from './helpers/llmAdapterTestHarness'; + +function endpoint(models: Record): CompatibleEndpointConfig { + return { + apiKey: '', enabled: true, driverKind: 'openai-compatible', models: {}, + openaiCompatible: { schemaVersion: 1, displayName: 'Gateway', baseUrl: 'https://gateway.example/v1', models }, + }; +} + +describe('context window source', () => { + test('the user value wins, then the server report, then 4,096', () => { + expect(resolveOpenAICompatibleContextWindow({ source: 'manual', contextWindow: 32_768, reportedContextWindow: 131_072 })) + .toEqual({ contextWindow: 32_768, source: 'user' }); + expect(resolveOpenAICompatibleContextWindow({ source: 'discovered', reportedContextWindow: 131_072 })) + .toEqual({ contextWindow: 131_072, source: 'server' }); + expect(resolveOpenAICompatibleContextWindow({ source: 'manual' })).toEqual({ contextWindow: 4096, source: 'default' }); + expect(resolveOpenAICompatibleContextWindow(undefined)).toEqual({ contextWindow: 4096, source: 'default' }); + }); + + test('a corrupt saved value falls through instead of breaking the endpoint', () => { + for (const bad of [0, -5, 1.5, Number.NaN, 10 ** 12, '131072' as unknown as number]) { + expect(resolveOpenAICompatibleContextWindow({ source: 'manual', contextWindow: bad }).source).toBe('default'); + } + }); + + test('the reported #439 case: a 128k model can now be given a 100k chat limit', () => { + const config = endpoint({ 'qwen-128k': { source: 'manual', contextWindow: 131_072 } }); + const [model] = buildOpenAICompatibleModels(config); + expect(model.contextWindow).toBe(131_072); + // The chat slider clamps overrides to the model's window; before the fix that was 4,096. + expect(resolveContextWindowLimit(model.contextWindow, 100_000)).toBe(100_000); + }); + + test('the adapter advertises its largest saved model', () => { + const config = endpoint({ + small: { source: 'manual' }, + large: { source: 'discovered', reportedContextWindow: 262_144 }, + }) as LLMProviderConfig; + expect(new OpenAICompatibleAdapter(config, 'endpoint-a').getCapabilities().maxContextWindow).toBe(262_144); + }); +}); + +describe('chat overrides saved at the old ceiling', () => { + const key = (model: string) => getContextWindowOverrideKey('endpoint-a', model); + + test('raising a window frees overrides pinned at the old maximum and keeps deliberate ones', () => { + const before = endpoint({ pinned: { source: 'manual' }, chosen: { source: 'manual' }, other: { source: 'manual' } }); + const after = endpoint({ + pinned: { source: 'manual', contextWindow: 131_072 }, + chosen: { source: 'manual', contextWindow: 131_072 }, + other: { source: 'manual' }, + }); + // What ChatSettingsModal writes on save: the whole 4,096 window, or a smaller choice. + const chat = { [key('pinned')]: 4096, [key('chosen')]: 2048, [key('other')]: 4096, [getContextWindowOverrideKey('anthropic', 'pinned')]: 4096 }; + const agent = { [key('pinned')]: 4096 }; + const released = releaseRaisedContextOverrides('endpoint-a', before, after, [chat, agent, undefined]); + expect(chat).toEqual({ [key('chosen')]: 2048, [key('other')]: 4096, [getContextWindowOverrideKey('anthropic', 'pinned')]: 4096 }); + expect(agent).toEqual({}); + // A failed save restores exactly what was removed. + for (const { map, key: entry, value } of released) map[entry] = value; + expect(chat[key('pinned')]).toBe(4096); + expect(agent[key('pinned')]).toBe(4096); + }); + + test('lowering a window or adding a model leaves overrides alone', () => { + const before = endpoint({ a: { source: 'discovered', reportedContextWindow: 32_768 } }); + const after = endpoint({ a: { source: 'discovered', contextWindow: 16_384, reportedContextWindow: 32_768 }, b: { source: 'manual', contextWindow: 65_536 } }); + const chat = { [key('a')]: 32_768, [key('b')]: 4096 }; + expect(releaseRaisedContextOverrides('endpoint-a', before, after, [chat])).toEqual([]); + expect(releaseRaisedContextOverrides('endpoint-a', undefined, after, [chat])).toEqual([]); + expect(chat).toEqual({ [key('a')]: 32_768, [key('b')]: 4096 }); + }); +}); + +describe('reading what servers report', () => { + test.each([ + ['vLLM / SGLang', { id: 'm', max_model_len: 32_768 }, 32_768], + ['OpenRouter / Together / Bifrost', { id: 'm', context_length: 131_072 }, 131_072], + ['Groq / Bifrost OpenAI route', { id: 'm', context_window: 8192 }, 8192], + ['Mistral / LM Studio', { id: 'm', max_context_length: 65_536 }, 65_536], + ['OpenRouter top provider only', { id: 'm', top_provider: { context_length: 200_000 } }, 200_000], + ['numeric string', { id: 'm', context_length: '40960' }, 40_960], + ])('%s', (_name, entry, expected) => { + expect(readReportedContextWindow(entry)).toBe(expected); + }); + + test('ignores the trained maximum, absent fields and nonsense', () => { + expect(readReportedContextWindow({ id: 'm', meta: { n_ctx_train: 131_072 } })).toBeUndefined(); + expect(readReportedContextWindow({ id: 'm', object: 'model', owned_by: 'bifrost' })).toBeUndefined(); + expect(readReportedContextWindow({ id: 'm', max_model_len: 0, context_length: -1, context_window: 'big' })).toBeUndefined(); + }); + + test('discovery keeps per-model reports and leaves a bare gateway list unreported', async () => { + const requests: CapturedRequest[] = []; + __setRequestUrlMock(async request => { + requests.push(request); + return jsonResponse(200, { data: [ + { id: 'vllm-model', object: 'model', max_model_len: 32_768 }, + { id: 'bare-model', object: 'model', owned_by: 'bifrost' }, + ] }); + }); + expect(await discoverOpenAICompatibleModels('https://gateway.example/v1', '')).toEqual([ + { id: 'vllm-model', contextWindow: 32_768 }, + { id: 'bare-model' }, + ]); + expect(requests).toHaveLength(1); + }); + + test('a llama.cpp server is asked for its allocated context, not its trained maximum', async () => { + const urls: string[] = []; + __setRequestUrlMock(async request => { + urls.push(request.url!); + if (request.url!.endsWith('/v1/models')) { + return jsonResponse(200, { object: 'list', data: [{ id: 'qwen.gguf', object: 'model', owned_by: 'llamacpp', meta: { n_ctx_train: 131_072, n_vocab: 151_936 } }] }); + } + return jsonResponse(200, { default_generation_settings: { n_ctx: 16_384 }, total_slots: 1 }); + }); + expect(await discoverOpenAICompatibleModels('http://127.0.0.1:8080/v1', '')).toEqual([{ id: 'qwen.gguf', contextWindow: 16_384 }]); + expect(urls).toEqual(['http://127.0.0.1:8080/v1/models', 'http://127.0.0.1:8080/props']); + }); + + test('a failing /props never fails discovery', async () => { + __setRequestUrlMock(async request => request.url!.endsWith('/props') + ? jsonResponse(404, { error: 'not found' }) + : jsonResponse(200, { data: [{ id: 'qwen.gguf', meta: { n_ctx_train: 131_072 } }] })); + expect(await discoverOpenAICompatibleModels('http://127.0.0.1:8080/v1', '')).toEqual([{ id: 'qwen.gguf' }]); + }); +}); + +describe('editing the context window', () => { + test('stores, clears and rejects values without touching other models', () => { + const session = new OpenAICompatibleEditSession('id-1', endpoint({ a: { source: 'manual' }, b: { source: 'manual' } }), jest.fn()); + session.setContextWindow('a', 131_072); + expect(session.draft.openaiCompatible.models).toEqual({ a: { source: 'manual', contextWindow: 131_072 }, b: { source: 'manual' } }); + session.setContextWindow('a', undefined); + expect(session.draft.openaiCompatible.models.a).toEqual({ source: 'manual' }); + for (const bad of [0, 100, 1.5, Number.NaN, 10 ** 12]) expect(() => session.setContextWindow('a', bad)).toThrow('whole number'); + expect(() => session.setContextWindow('missing', 4096)).toThrow('not in the list'); + }); + + test('Connect refreshes the server report but never overwrites the user value', async () => { + const reports = [ + [{ id: 'a', contextWindow: 65_536 }, { id: 'b', contextWindow: 32_768 }], + [{ id: 'a', contextWindow: 131_072 }, { id: 'b' }], + ]; + const persist = jest.fn(async () => undefined); + const session = new OpenAICompatibleEditSession('id-1', endpoint({ a: { source: 'manual', contextWindow: 16_384 } }), persist, async () => reports.shift()!); + await session.connect(); + expect(session.draft.openaiCompatible.models).toEqual({ + a: { source: 'manual', contextWindow: 16_384, reportedContextWindow: 65_536 }, + b: { source: 'discovered', reportedContextWindow: 32_768 }, + }); + await session.connect(); + expect(session.draft.openaiCompatible.models).toEqual({ + a: { source: 'manual', contextWindow: 16_384, reportedContextWindow: 131_072 }, + b: { source: 'discovered' }, + }); + expect(persist).toHaveBeenLastCalledWith('id-1', expect.objectContaining({ + openaiCompatible: expect.objectContaining({ models: session.draft.openaiCompatible.models }), + })); + }); + + test('Check uses the draft address, key and the size the model would actually get', async () => { + const check = jest.fn(async () => ({ kind: 'fits-unmeasured' as const })); + const config = endpoint({ a: { source: 'discovered', reportedContextWindow: 32_768 } }); + const session = new OpenAICompatibleEditSession('id-1', config, jest.fn(), jest.fn(), check); + session.setApiKey('draft-key'); + await session.checkContextWindow('a'); + session.setContextWindow('a', 65_536); + await session.checkContextWindow('a'); + expect(check.mock.calls.map(([request]) => request)).toEqual([ + expect.objectContaining({ baseUrl: 'https://gateway.example/v1', apiKey: 'draft-key', model: 'a', contextWindow: 32_768 }), + expect.objectContaining({ contextWindow: 65_536 }), + ]); + }); +}); + +/** + * A fake chat server. Its tokenizer spends 11 tokens per filler sentence plus a + * 23-token chat template, so the check must measure rather than assume. + */ +type ServerReply = (promptTokens: number) => ReturnType; +const SENTENCE = 'The quick brown fox jumps over the lazy dog. '; +function fakeServer(reply: ServerReply): { bodies: Array> } { + const bodies: Array> = []; + __setRequestUrlMock(async request => { + const body = JSON.parse(request.body!) as { messages: Array<{ content: string }> }; + bodies.push(body); + const sentences = body.messages[0].content.split(SENTENCE).length - 1; + return reply(23 + sentences * 11); + }); + return { bodies }; +} +const accepted = (promptTokens: number) => jsonResponse(200, { + choices: [{ message: { content: 'x' }, finish_reason: 'length' }], usage: { prompt_tokens: promptTokens, completion_tokens: 1 }, +}); +const request = (contextWindow: number) => ({ baseUrl: 'https://gateway.example/v1', apiKey: '', model: 'm', contextWindow }); + +describe('Check: sending a prompt of the chosen size', () => { + test('a prompt that fits is filled close to the window, with one output token', async () => { + const { bodies } = fakeServer(accepted); + const result = await checkOpenAICompatibleContextWindow(request(8192)); + expect(result.kind).toBe('fits'); + const sent = (result as { promptTokens: number }).promptTokens; + expect(sent).toBeLessThanOrEqual(8192 - 1); + expect(sent).toBeGreaterThan(8192 * 0.97); + expect(bodies).toHaveLength(3); + expect(bodies[2]).toMatchObject({ model: 'm', stream: false, max_tokens: 1 }); + }); + + test('vLLM-style refusal reports the limit from its sentence', async () => { + fakeServer(tokens => tokens + 1 > 4096 + ? jsonResponse(400, { object: 'error', type: 'BadRequestError', code: 400, + message: `This model's maximum context length is 4096 tokens. However, you requested ${tokens + 1} tokens (${tokens} in the messages, 1 in the completion). Please reduce the length of the messages or completion.` }) + : accepted(tokens)); + expect(await checkOpenAICompatibleContextWindow(request(131_072))).toEqual(expect.objectContaining({ kind: 'too-large', serverLimit: 4096 })); + }); + + test('llama.cpp-style refusal reports n_ctx from its error object', async () => { + fakeServer(tokens => tokens >= 16_384 + // Captured from llama.cpp's server image, 2026-11-12. + ? jsonResponse(400, { error: { code: 400, message: `request (${tokens} tokens) exceeds the available context size (16384 tokens), try increasing it`, + type: 'exceed_context_size_error', n_prompt_tokens: tokens, n_ctx: 16_384 } }) + : accepted(tokens)); + expect(await checkOpenAICompatibleContextWindow(request(65_536))).toEqual(expect.objectContaining({ kind: 'too-large', serverLimit: 16_384 })); + }); + + test('a refusal without a number is still reported as too large', async () => { + fakeServer(tokens => tokens > 2048 ? jsonResponse(400, { error: { message: 'Prompt is too long' } }) : accepted(tokens)); + expect(await checkOpenAICompatibleContextWindow(request(8192))).toEqual({ kind: 'too-large', serverLimit: undefined, message: 'Prompt is too long' }); + }); + + test('a server that silently cuts the prompt is caught by its own token count', async () => { + fakeServer(tokens => accepted(Math.min(tokens, 2048))); + expect(await checkOpenAICompatibleContextWindow(request(32_768))).toEqual({ kind: 'truncated', promptTokens: 2048 }); + }); + + test('a server with no token counts cannot be confirmed', async () => { + fakeServer(() => jsonResponse(200, { choices: [{ message: { content: 'x' }, finish_reason: 'length' }] })); + expect(await checkOpenAICompatibleContextWindow(request(8192))).toEqual({ kind: 'fits-unmeasured' }); + }); + + test('an unrelated error is a failure, not a size verdict', async () => { + fakeServer(() => jsonResponse(401, { error: { message: 'Invalid API key' } })); + expect(await checkOpenAICompatibleContextWindow(request(8192))).toEqual({ kind: 'failed', message: 'The server returned HTTP 401: Invalid API key' }); + }); + + test('the limit survives a gateway that passes on only the message', () => { + expect(readContextLimitFromError(null, 'request (6031 tokens) exceeds the available context size (2048 tokens), try increasing it', 8192)).toBe(2048); + }); + + test('a named limit at or above the tested size is not offered', () => { + expect(readContextLimitFromError(null, "This model's maximum context length is 8192 tokens.", 8192)).toBeUndefined(); + expect(readContextLimitFromError(null, 'context length of 1,000,000 exceeded', 2_000_000)).toBe(1_000_000); + }); +}); + +describe('what the settings row says', () => { + test('names where the number came from', () => { + expect(describeContextWindow({ source: 'manual' })).toMatch(/4,096 tokens.*did not report/); + expect(describeContextWindow({ source: 'discovered', reportedContextWindow: 131_072 })).toBe('Context window: 131,072 tokens, reported by your server.'); + expect(describeContextWindow({ source: 'discovered', contextWindow: 65_536, reportedContextWindow: 131_072 })) + .toBe('Context window: 65,536 tokens, set by you. Your server reports 131,072.'); + }); + + test('offers the size a refusal named', () => { + expect(describeContextCheck({ kind: 'too-large', serverLimit: 4096, message: 'x' })).toMatchObject({ suggestion: 4096, warning: true }); + expect(describeContextCheck({ kind: 'fits', promptTokens: 8100 })).toMatchObject({ warning: false }); + expect(describeContextCheck({ kind: 'too-large', message: 'Prompt is too long' }).suggestion).toBeUndefined(); + }); + + test('does not offer the count a shortening server read, which can be half its real context', () => { + // Ollama with num_ctx 32,768 read 16,386 tokens of a 65,536-token check. + const note = describeContextCheck({ kind: 'truncated', promptTokens: 16_386 }); + expect(note.warning).toBe(true); + expect(note.suggestion).toBeUndefined(); + expect(note.text).toMatch(/16,386 tokens/); + expect(note.text).toMatch(/enter the size your server runs the model with/); + }); +}); diff --git a/tests/unit/OpenAICompatibleEditSession.test.ts b/tests/unit/OpenAICompatibleEditSession.test.ts index d9b694613..9ad0b5984 100644 --- a/tests/unit/OpenAICompatibleEditSession.test.ts +++ b/tests/unit/OpenAICompatibleEditSession.test.ts @@ -3,6 +3,7 @@ import { CompatibleEndpointConfig, OpenAICompatibleEditSession, } from '../../src/components/openai-compatible/OpenAICompatibleEditSession'; +import type { DiscoveredOpenAICompatibleModel } from '../../src/services/llm/adapters/openai-compatible/OpenAICompatibleConfig'; function config(): CompatibleEndpointConfig { return { @@ -23,13 +24,13 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { describe('OpenAI-compatible endpoint editor', () => { it('ignores discovery after the key changes, including an explicit clear', async () => { - const response = deferred(); + const response = deferred(); const persist = jest.fn(async () => undefined); const session = new OpenAICompatibleEditSession('id-1', config(), persist, () => response.promise); const discovery = session.connect(); session.setApiKey(''); await session.save(); - response.resolve(['stale-model']); + response.resolve([{ id: 'stale-model' }]); expect(await discovery).toBe('stale'); expect(session.draft.openaiCompatible.models).not.toHaveProperty('stale-model'); expect(persist).toHaveBeenCalledTimes(1); @@ -68,7 +69,7 @@ describe('OpenAI-compatible endpoint editor', () => { }); it('retains manually entered models and disabled choices during discovery', async () => { - const session = new OpenAICompatibleEditSession('id-1', config(), jest.fn(async () => undefined), async () => ['existing', 'new-model', 'new-model']); + const session = new OpenAICompatibleEditSession('id-1', config(), jest.fn(async () => undefined), async () => [{ id: 'existing' }, { id: 'new-model' }, { id: 'new-model' }]); expect(await session.connect()).toBe('connected'); expect(session.draft.openaiCompatible.models).toEqual({ existing: { source: 'manual' }, 'new-model': { source: 'discovered' } }); expect(session.draft.models?.existing.enabled).toBe(false); @@ -116,13 +117,25 @@ describe('OpenAI-compatible endpoint editor', () => { }); it('ignores discovery after the editor closes', async () => { - const response = deferred(); + const response = deferred(); const persist = jest.fn(async () => undefined); const session = new OpenAICompatibleEditSession('id-1', config(), persist, () => response.promise); const pending = session.connect(); session.close(); - response.resolve(['late-model']); + response.resolve([{ id: 'late-model' }]); expect(await pending).toBe('stale'); expect(persist).not.toHaveBeenCalled(); }); + + it('follows the server report when a check suggests the size the server already reports', () => { + const session = new OpenAICompatibleEditSession('id-1', config(), jest.fn(async () => undefined)); + session.draft.openaiCompatible.models = { + reported: { source: 'discovered', reportedContextWindow: 8192, contextWindow: 32_768 }, + unreported: { source: 'manual', contextWindow: 65_536 }, + }; + expect(session.useContextWindow('reported', 8192)).toBe(''); + expect(session.draft.openaiCompatible.models.reported).toEqual({ source: 'discovered', reportedContextWindow: 8192 }); + expect(session.useContextWindow('unreported', 32_768)).toBe('32768'); + expect(session.draft.openaiCompatible.models.unreported).toEqual({ source: 'manual', contextWindow: 32_768 }); + }); });