Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

read each model's real context window from the provider catalog instead of assuming 128K

[._.]/ Adam Eivyb6958887ba88
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index f343035200..26e86ad5a1 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -14,8 +14,8 @@
import { Link } from 'react-router';
import { Terminal } from 'lucide-react';
import {
+ CONTEXT_WINDOW_SOURCE,
PROVIDER_CARD_STATE,
- effectiveModelContextWindow,
isApiProvider,
isGrokBuildCli,
gatewayForProvider,
@@ -25,6 +25,7 @@ import {
isTuiProvider,
isLaunchableTuiProvider,
providerTypeClass,
+ resolveModelContextWindow,
supportsModelRefresh,
} from '../../utils/providers';
import { formatContextLength } from '../../utils/formatters';
@@ -346,13 +347,36 @@ export default function ProviderCard({
<p className="break-words">Default effort: <code className="text-gray-300">{provider.effort}</code></p>
)}
{(() => {
- const windowLabel = formatContextLength(effectiveModelContextWindow(provider, provider.defaultModel));
- return windowLabel ? (
+ // The window AND where it came from: the last rung of the ladder is
+ // a blanket 128K guess, and printing that bare made a 1M-context
+ // model look like PortOS had capped it. A reported window prints
+ // plain; a guess says so and names the way to replace it.
+ const { tokens, source } = resolveModelContextWindow(provider, provider.defaultModel);
+ const windowLabel = formatContextLength(tokens);
+ if (!windowLabel) return null;
+ // Only offer Refresh Models when this card HAS that button —
+ // `assumed` is reached by every process provider with an
+ // unrecognized model, including ones with no model-list capability
+ // at all, and pointing those at a button that is not on screen is
+ // worse than saying nothing.
+ const assumed = source === CONTEXT_WINDOW_SOURCE.ASSUMED;
+ const assumedFix = supportsModelRefresh(provider)
+ ? 'assumed — Refresh Models to read the real one'
+ : 'assumed — set a context window when editing this provider';
+ return (
<p className="text-xs">
Context: <span className="text-gray-300">{windowLabel}</span>
- {provider.contextWindow ? <span className="text-gray-500"> override</span> : null}
+ {source === CONTEXT_WINDOW_SOURCE.OVERRIDE && <span className="text-gray-500"> override</span>}
+ {assumed && (
+ <span
+ className="text-gray-500"
+ title="PortOS has not been told this model’s real window, so prompt budgeting assumes a conservative 128K rather than the model’s own ceiling."
+ >
+ {" "}{assumedFix}
+ </span>
+ )}
</p>
- ) : null;
+ );
})()}
{(provider.lightModel || provider.mediumModel || provider.heavyModel) && (
<p className="text-xs">
diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsx
new file mode 100644
index 0000000000..e425e031d8
--- /dev/null
+++ b/client/src/components/providers/ProviderCard.test.jsx
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import ProviderCard from './ProviderCard';
+import { PROVIDER_CARD_STATE } from '../../utils/providers';
+
+const wrapper = (overrides = {}) => ({
+ id: 'opencode-openrouter-tui',
+ name: 'OpenCode OpenRouter TUI',
+ type: 'tui',
+ command: 'opencode',
+ endpoint: 'https://openrouter.ai/api/v1',
+ models: ['openrouter/auto', 'stealth/ox-alpha'],
+ defaultModel: 'stealth/ox-alpha',
+ enabled: true,
+ ...overrides,
+});
+
+const renderCard = (provider) => render(
+ <MemoryRouter>
+ <ProviderCard
+ provider={provider}
+ cardState={{ state: PROVIDER_CARD_STATE.READY }}
+ runtime={null}
+ status={null}
+ isDefault={false}
+ providersById={{}}
+ runnerAllowedCommands={[]}
+ testResult={null}
+ />
+ </MemoryRouter>
+);
+
+describe('ProviderCard context window', () => {
+ it('labels the blanket 128K as an assumption, not a measured window', () => {
+ // Printing it bare made a 1M-context model look like PortOS had capped it,
+ // with nothing on screen to say the number was a guess or how to fix it.
+ renderCard(wrapper({ canRefreshModels: true }));
+ expect(screen.getByText('128K ctx')).toBeTruthy();
+ expect(screen.getByText(/assumed — Refresh Models to read the real one/)).toBeTruthy();
+ });
+
+ it('points a provider with no model-list capability at the editor instead', () => {
+ // `assumed` is reached by every process provider with an unrecognized
+ // model, but the Refresh Models button is gated on canRefreshModels —
+ // advising a button that is not on the card is worse than saying nothing.
+ renderCard(wrapper());
+ expect(screen.getByText(/assumed — set a context window when editing this provider/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Refresh Models' })).toBeNull();
+ });
+
+ it('prints the catalog window plainly once model refresh has recorded it', () => {
+ renderCard(wrapper({ modelContextWindows: { 'stealth/ox-alpha': 1_000_000 } }));
+ expect(screen.getByText('1M ctx')).toBeTruthy();
+ expect(screen.queryByText(/assumed/)).toBeNull();
+ });
+
+ it('marks a hand-entered window as an override', () => {
+ renderCard(wrapper({ contextWindow: 250_000 }));
+ expect(screen.getByText('250K ctx')).toBeTruthy();
+ expect(screen.getByText('override')).toBeTruthy();
+ expect(screen.queryByText(/assumed/)).toBeNull();
+ });
+});
diff --git a/client/src/components/providers/ProviderNotices.jsx b/client/src/components/providers/ProviderNotices.jsx
index 6874950992..812de063c8 100644
--- a/client/src/components/providers/ProviderNotices.jsx
+++ b/client/src/components/providers/ProviderNotices.jsx
@@ -34,8 +34,33 @@ disable_codebase_upload = true`}</pre>
export function GatewayKeyHint({ gateway, sibling, className = '', onEdit }) {
if (!gateway) return null;
const hasKey = Boolean(sibling?.hasApiKey);
+ const shellClass = `text-xs rounded-md border border-port-border bg-port-bg/60 px-2.5 py-2 leading-relaxed ${className}`;
+ const editLink = sibling && onEdit && (
+ <button
+ type="button"
+ onClick={() => onEdit(sibling)}
+ className="text-port-accent hover:text-port-accent/80 underline underline-offset-2"
+ >
+ Edit {gateway.label} API provider
+ </button>
+ );
+
+ // Once the key is there, the three paragraphs explaining WHERE to put it are
+ // answering a question the user no longer has — they read as an unresolved
+ // setup step on a provider that is fully configured. Collapse to the status
+ // plus the same edit link, which is the only part still worth acting on.
+ if (hasKey) {
+ return (
+ <div className={`${shellClass} flex flex-wrap items-center gap-2`}>
+ <span className="text-port-success">{gateway.label} API key configured</span>
+ <span className="text-gray-500">— inherited by this wrapper at run time</span>
+ {editLink}
+ </div>
+ );
+ }
+
return (
- <div className={`text-xs rounded-md border border-port-border bg-port-bg/60 px-2.5 py-2 leading-relaxed ${className}`}>
+ <div className={shellClass}>
<span className="text-gray-300">
API key is inherited from the <code className="font-mono">{gateway.label}</code> API provider
{" "}at run time — this wrapper has no key field of its own.
@@ -45,20 +70,8 @@ export function GatewayKeyHint({ gateway, sibling, className = '', onEdit }) {
<code className="font-mono">{gateway.apiKeyEnv}</code> to OpenCode automatically.
</p>
<div className="mt-2 flex flex-wrap items-center gap-2">
- {hasKey ? (
- <span className="text-port-success">{gateway.label} key: set</span>
- ) : (
- <span className="text-port-warning">{gateway.label} key: not set</span>
- )}
- {sibling && onEdit && (
- <button
- type="button"
- onClick={() => onEdit(sibling)}
- className="text-port-accent hover:text-port-accent/80 underline underline-offset-2"
- >
- Edit {gateway.label} API provider
- </button>
- )}
+ <span className="text-port-warning">{gateway.label} key: not set</span>
+ {editLink}
</div>
</div>
);
diff --git a/client/src/components/providers/ProviderNotices.test.jsx b/client/src/components/providers/ProviderNotices.test.jsx
new file mode 100644
index 0000000000..1cb1dfdef3
--- /dev/null
+++ b/client/src/components/providers/ProviderNotices.test.jsx
@@ -0,0 +1,36 @@
+import { describe, it, expect, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { GatewayKeyHint } from './ProviderNotices';
+
+const gateway = { id: 'openrouter', label: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKeyEnv: 'OPENROUTER_API_KEY' };
+
+describe('GatewayKeyHint', () => {
+ it('collapses to a status line plus the edit link once the key is configured', () => {
+ // The three paragraphs explaining WHERE to put the key answer a question a
+ // configured user no longer has — they read as an unfinished setup step.
+ const onEdit = vi.fn();
+ const sibling = { id: 'openrouter', name: 'OpenRouter', hasApiKey: true };
+ render(<GatewayKeyHint gateway={gateway} sibling={sibling} onEdit={onEdit} />);
+
+ expect(screen.getByText('OpenRouter API key configured')).toBeTruthy();
+ expect(screen.queryByText(/no key field of its own/)).toBeNull();
+ expect(screen.queryByText(/OPENROUTER_API_KEY/)).toBeNull();
+
+ // The link survives the collapse — changing the key stays one click away.
+ fireEvent.click(screen.getByRole('button', { name: 'Edit OpenRouter API provider' }));
+ expect(onEdit).toHaveBeenCalledWith(sibling);
+ });
+
+ it('keeps the full explanation while the key is missing', () => {
+ render(<GatewayKeyHint gateway={gateway} sibling={{ id: 'openrouter', hasApiKey: false }} onEdit={vi.fn()} />);
+
+ expect(screen.getByText('OpenRouter key: not set')).toBeTruthy();
+ expect(screen.getByText(/no key field of its own/)).toBeTruthy();
+ expect(screen.getByText('OPENROUTER_API_KEY')).toBeTruthy();
+ });
+
+ it('renders nothing for a provider that fronts no gateway', () => {
+ const { container } = render(<GatewayKeyHint gateway={null} sibling={null} />);
+ expect(container.textContent).toBe('');
+ });
+});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index a5edc1aec6..9c16860363 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -959,7 +959,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
<option value={configuredDefault}>Use the CLI&apos;s configured default</option>
)}
{availableModels.map(model => (
- <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById, capabilityProvider)}</option>
))}
</>
);
@@ -975,8 +975,12 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
const fallbackModelOptions = filterGenerationModels(
mergeModelLists(selectedFallbackProvider?.models, liveModelsFor(selectedFallbackProvider)),
);
+ // `capabilityProvider`, not `formData`: the per-model windows model refresh
+ // recorded (`modelContextWindows`) live on the RECORD and are not form fields,
+ // so reading formData alone reported the assumed 128K for a model whose real
+ // window PortOS already knows.
const plannedContextLabel = formatContextLength(
- effectiveModelContextWindow(formData, formData.defaultModel)
+ effectiveModelContextWindow(capabilityProvider, formData.defaultModel)
);
// `num_ctx` is meaningful for any provider whose tokens come from Ollama, not
// just `api` ones: an `api` provider sends it on every request, while an
@@ -1541,7 +1545,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
>
<option value="">Use fallback provider's default</option>
{fallbackModelOptions.map(model => (
- <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById, selectedFallbackProvider)}</option>
))}
</select>
) : (
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 38ed97d90b..7130c1823a 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -1089,7 +1089,7 @@ describe('OpenCode OrcaRouter key hint', () => {
expect(screen.getByText(/ORCAROUTER_API_KEY/)).toBeInTheDocument();
});
- it('reports the inherited key as set when the sibling API provider has one', async () => {
+ it('collapses to a one-line confirmation when the sibling API provider has the key', async () => {
api.getProviders.mockResolvedValue({
providers: [
{
@@ -1109,8 +1109,11 @@ describe('OpenCode OrcaRouter key hint', () => {
renderPage();
- expect(await screen.findByText(/API key is inherited from/)).toBeInTheDocument();
- expect(screen.getByText('OrcaRouter key: set')).toBeInTheDocument();
+ // Configured providers state the fact and keep the link; the "where does
+ // the key go?" explanation is only shown while it is still unanswered.
+ expect(await screen.findByText('OrcaRouter API key configured')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Edit OrcaRouter API provider' })).toBeInTheDocument();
+ expect(screen.queryByText(/API key is inherited from/)).not.toBeInTheDocument();
});
// A non-orcarouter-backed provider must never see the inheritance hint.
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index a2aec2f6d0..07ad386d07 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -920,7 +920,7 @@ export default function PipelineManuscriptEditor() {
onChange={(e) => setOverrideModel(e.target.value)}
className="flex-1 min-w-0 px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white"
>
- {overrideModels.map((m) => <option key={m} value={m}>{modelOptionLabel(m, localModels.ctxById)}</option>)}
+ {overrideModels.map((m) => <option key={m} value={m}>{modelOptionLabel(m, localModels.ctxById, overrideProvider)}</option>)}
</select>
) : null}
</div>
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 7d2f621662..017789a63f 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -402,9 +402,18 @@ export function formatDownloadGb(gb) {
/**
* Format a model context window (in tokens) compactly, e.g. 32768 → "32K ctx",
- * 131072 → "128K ctx", 1048576 → "1M ctx". Returns null for missing/invalid
+ * 131072 → "128K ctx", 1000000 → "1M ctx". Returns null for missing/invalid
* values so callers can omit the label entirely.
*
+ * Two unit systems, picked per value, because model context windows are quoted
+ * in both and neither divisor is right for the other: local runtimes report
+ * BINARY windows (131072, 32768 — "128K", "32K"), while cloud vendors quote
+ * DECIMAL ones (128000, 1000000 — "128K", "1M"). Dividing a decimal window by
+ * 1024 is what rendered a 128,000-token provider as "125K ctx", a number no
+ * vendor publishes and which reads as a PortOS-imposed cap rather than the
+ * model's own spec. So: a value that divides evenly by 1000 is decimal, and
+ * everything else is binary.
+ *
* `suffix` is what follows the number. The default reads as a standalone badge;
* pass `''` when the surrounding prose already supplies the noun ("up to 32K
* tokens of context"), so the two spellings stay one implementation instead of
@@ -417,11 +426,12 @@ export function formatDownloadGb(gb) {
export function formatContextLength(tokens, { suffix = ' ctx' } = {}) {
const n = Number(tokens);
if (!Number.isFinite(n) || n <= 0) return null;
- if (n >= 1024 * 1024) {
- const m = n / (1024 * 1024);
+ const k = n % 1000 === 0 ? 1000 : 1024;
+ if (n >= k * k) {
+ const m = n / (k * k);
return `${parseFloat(m.toFixed(m % 1 ? 1 : 0))}M${suffix}`;
}
- if (n >= 1024) return `${Math.round(n / 1024)}K${suffix}`;
+ if (n >= k) return `${Math.round(n / k)}K${suffix}`;
return `${n}${suffix}`;
}
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index b3c8371165..70a78cf336 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -154,6 +154,19 @@ describe('formatContextLength', () => {
expect(formatContextLength(1048576)).toBe('1M ctx');
});
+ // Cloud vendors quote DECIMAL windows; local runtimes report BINARY ones.
+ // Dividing a decimal window by 1024 is what printed a 128,000-token provider
+ // as "125K ctx" — a number no vendor publishes, which reads as a PortOS cap.
+ it('formats decimal-quoted windows in decimal units', () => {
+ expect(formatContextLength(128000)).toBe('128K ctx');
+ expect(formatContextLength(200000)).toBe('200K ctx');
+ expect(formatContextLength(256000)).toBe('256K ctx');
+ expect(formatContextLength(400000)).toBe('400K ctx');
+ expect(formatContextLength(1000000)).toBe('1M ctx');
+ expect(formatContextLength(2000000)).toBe('2M ctx');
+ expect(formatContextLength(1500000)).toBe('1.5M ctx');
+ });
+
// Callers whose surrounding prose already says "tokens of context" drop the
// badge suffix rather than keeping a near-copy of this function.
it('drops the suffix when asked, across every magnitude bucket', () => {
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 2dab0961af..616c2a9a62 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -803,18 +803,74 @@ export const isLikelyLargeContextProvider = (provider) => {
return isApiProvider(provider) && !isLocalEndpoint(provider.endpoint);
};
-export const effectiveModelContextWindow = (provider, model) => {
+/**
+ * Where a resolved context window came from — three states, because that is
+ * what the UI actually distinguishes:
+ *
+ * - `REPORTED` — a real window for this model/provider (catalog, known-model
+ * table, vendor default, or Ollama's num_ctx). Which of those it was does not
+ * change what the card says, so they collapse into one state rather than
+ * growing an enum member per rung.
+ * - `OVERRIDE` — a number the user typed; worth labelling as theirs.
+ * - `ASSUMED` — nobody reported one, so the ladder GUESSED. This is the state
+ * that has to be visible: a card printing "128K ctx" for a model whose real
+ * window is 1M reads as a measured fact with nothing to say otherwise.
+ */
+export const CONTEXT_WINDOW_SOURCE = Object.freeze({
+ OVERRIDE: 'override',
+ REPORTED: 'reported',
+ ASSUMED: 'assumed',
+});
+
+/**
+ * The window this provider's own `/models` catalog reported for this model, or
+ * `null` when it never mentioned it. Recorded by model refresh — the serving
+ * side's own declaration, so it outranks the hand-maintained regex table.
+ * Mirror of `catalogModelContextWindow` in server/lib/stageRunner.js.
+ */
+export function catalogModelContextWindow(provider, model) {
+ const windows = provider?.modelContextWindows;
+ if (!windows || typeof windows !== 'object') return null;
+ if (typeof model !== 'string' || !model) return null;
+ const tokens = Number(windows[model]);
+ return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
+}
+
+/**
+ * The planning context window for a provider/model AND where it came from.
+ * Mirror of `effectiveContextWindow` in server/lib/stageRunner.js — the two
+ * must resolve identically, or the card promises a budget the budgeter won't use.
+ *
+ * `{ tokens: null, source: null }` means nothing is known (an unrecognized model
+ * on a local backend); the budgeter applies its own conservative floor there.
+ *
+ * @param {object|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @returns {{tokens: number|null, source: string|null}}
+ */
+export const resolveModelContextWindow = (provider, model) => {
const explicit = Number(provider?.contextWindow);
- if (Number.isFinite(explicit) && explicit > 0) return explicit;
+ if (Number.isFinite(explicit) && explicit > 0) {
+ return { tokens: explicit, source: CONTEXT_WINDOW_SOURCE.OVERRIDE };
+ }
+ const catalog = catalogModelContextWindow(provider, model);
+ if (catalog) return { tokens: catalog, source: CONTEXT_WINDOW_SOURCE.REPORTED };
const known = knownModelContextWindow(model);
- if (known) return known;
+ if (known) return { tokens: known, source: CONTEXT_WINDOW_SOURCE.REPORTED };
const providerKnown = knownProviderContextWindow(provider);
- if (providerKnown) return providerKnown;
+ if (providerKnown) return { tokens: providerKnown, source: CONTEXT_WINDOW_SOURCE.REPORTED };
const numCtx = Number(provider?.numCtx);
- if (Number.isFinite(numCtx) && numCtx > 0) return numCtx;
- return isLikelyLargeContextProvider(provider) ? DEFAULT_LARGE_CONTEXT_WINDOW : null;
+ if (Number.isFinite(numCtx) && numCtx > 0) {
+ return { tokens: numCtx, source: CONTEXT_WINDOW_SOURCE.REPORTED };
+ }
+ return isLikelyLargeContextProvider(provider)
+ ? { tokens: DEFAULT_LARGE_CONTEXT_WINDOW, source: CONTEXT_WINDOW_SOURCE.ASSUMED }
+ : { tokens: null, source: null };
};
+export const effectiveModelContextWindow = (provider, model) =>
+ resolveModelContextWindow(provider, model).tokens;
+
/**
* Union of one or more model-id lists, de-duplicated, order-preserving, falsy
* values dropped. Used to merge a provider's stored `models` with the live
@@ -835,15 +891,27 @@ export const mergeModelLists = (...lists) => {
/**
* Display label for a model `<option>`: the id plus a "(32K ctx)" parenthetical
- * when the model's context window is known (local models, via the `ctxById` map
- * from `useLocalModels`). The option's `value` stays the raw id — only the label
- * carries the annotation.
+ * when the model's context window is known. The option's `value` stays the raw
+ * id — only the label carries the annotation.
+ *
+ * Resolution is deliberately narrower than {@link resolveModelContextWindow}:
+ * only rungs that describe THIS model — the live local probe (`ctxById` from
+ * `useLocalModels`), the window `provider`'s catalog reported for it, then the
+ * known-model table. The provider-level and assumed rungs are excluded on
+ * purpose: they would stamp the same guessed number onto every option in the
+ * list, which says nothing and reads as fact.
+ *
+ * Take `provider` rather than a pre-merged map so every picker gets catalog
+ * windows for free — merging at the call site is what left the fallback-model
+ * and manuscript-override selects labelling a 1M model as if it were unknown.
+ *
* @param {string} id
- * @param {Record<string, number>} [ctxById]
+ * @param {Record<string, number>} [ctxById] — live windows for local models
+ * @param {object} [provider] — the provider whose catalog lists this model
* @returns {string}
*/
-export const modelOptionLabel = (id, ctxById) => {
- const ctx = ctxById?.[id] || knownModelContextWindow(id);
+export const modelOptionLabel = (id, ctxById, provider) => {
+ const ctx = ctxById?.[id] || catalogModelContextWindow(provider, id) || knownModelContextWindow(id);
const label = formatContextLength(ctx);
return label ? `${id} (${label})` : id;
};
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 0347927168..cd39eb1abe 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -25,7 +25,10 @@ import {
GROK_CONTEXT_WINDOW,
KIMI_CONTEXT_WINDOW,
KIMI_CONFIGURED_DEFAULT,
+ CONTEXT_WINDOW_SOURCE,
+ catalogModelContextWindow,
effectiveModelContextWindow,
+ resolveModelContextWindow,
mergeModelLists,
modelOptionLabel,
isTuiProvider,
@@ -1039,6 +1042,44 @@ describe('effectiveModelContextWindow', () => {
expect(effectiveModelContextWindow({ type: 'api', endpoint: 'https://api.example.test/v1' }, 'unknown')).toBe(128_000);
});
+ it('prefers the window the provider catalog reported for that model', () => {
+ // Mirrors the server ladder in stageRunner.js: catalog beats the regex
+ // table, and both beat the blanket 128K assumption that made a 1M-context
+ // model look capped.
+ const wrapper = { id: 'opencode-openrouter-tui', type: 'tui', command: 'opencode', modelContextWindows: { 'stealth/ox-alpha': 1_000_000 } };
+ expect(effectiveModelContextWindow(wrapper, 'stealth/ox-alpha')).toBe(1_000_000);
+ expect(effectiveModelContextWindow(wrapper, 'openrouter/auto')).toBe(128_000);
+ expect(effectiveModelContextWindow(
+ { type: 'api', endpoint: 'https://api.example.test/v1', modelContextWindows: { 'claude-sonnet-4-6': 200_000 } },
+ 'claude-sonnet-4-6'
+ )).toBe(200_000);
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 0 } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 1_000 } }, 'other')).toBeNull();
+ });
+
+ it('separates a reported window from a guessed one so the UI can flag it', () => {
+ const src = (p, m) => resolveModelContextWindow(p, m).source;
+ expect(src({ type: 'tui', contextWindow: 64_000 }, 'm')).toBe(CONTEXT_WINDOW_SOURCE.OVERRIDE);
+ // Every rung that reports a REAL window reads the same to the UI.
+ expect(src({ type: 'tui', modelContextWindows: { m: 1_000_000 } }, 'm')).toBe(CONTEXT_WINDOW_SOURCE.REPORTED);
+ expect(src({ type: 'tui' }, 'claude-opus-5')).toBe(CONTEXT_WINDOW_SOURCE.REPORTED);
+ expect(src({ id: 'codex-tui', type: 'tui', command: 'codex' }, CODEX_CONFIGURED_DEFAULT)).toBe(CONTEXT_WINDOW_SOURCE.REPORTED);
+ expect(src({ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 }, 'unknown')).toBe(CONTEXT_WINDOW_SOURCE.REPORTED);
+ // The only rung that is a guess rather than a report.
+ expect(src({ type: 'tui', command: 'opencode' }, 'unknown')).toBe(CONTEXT_WINDOW_SOURCE.ASSUMED);
+ expect(src({ type: 'api', endpoint: 'http://localhost:8000/v1' }, 'unknown')).toBeNull();
+ });
+
+ it('labels an option from the catalog, without stamping the assumed window on every option', () => {
+ const provider = { type: 'tui', command: 'opencode', modelContextWindows: { 'stealth/ox-alpha': 1_000_000 } };
+ expect(modelOptionLabel('stealth/ox-alpha', undefined, provider)).toBe('stealth/ox-alpha (1M ctx)');
+ // The provider-level/assumed rungs are deliberately excluded — they would
+ // annotate every option with the same guess.
+ expect(modelOptionLabel('openrouter/auto', undefined, provider)).toBe('openrouter/auto');
+ // A live local probe still wins: it is the window the model is loaded at.
+ expect(modelOptionLabel('stealth/ox-alpha', { 'stealth/ox-alpha': 32768 }, provider)).toBe('stealth/ox-alpha (32K ctx)');
+ });
+
it('uses explicit contextWindow and numCtx with server precedence', () => {
expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:11434/v1', contextWindow: 64_000, numCtx: 32_768 }, 'unknown')).toBe(64_000);
expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 }, 'unknown')).toBe(32_768);
diff --git a/server/lib/aiToolkit/internal/modelCatalog.js b/server/lib/aiToolkit/internal/modelCatalog.js
new file mode 100644
index 0000000000..a7abcd6491
--- /dev/null
+++ b/server/lib/aiToolkit/internal/modelCatalog.js
@@ -0,0 +1,164 @@
+/**
+ * Parse an OpenAI-compatible `/models` payload into the two things a provider
+ * record stores: the model ids, and each model's REAL context window when the
+ * catalog reports one.
+ *
+ * Why the second half exists: without it, every model a hosted gateway serves
+ * fell through to the hardcoded `KNOWN_MODEL_CONTEXT_WINDOWS` regex table and,
+ * failing that, to a blanket 128K assumption — so a 1M-context model reached by
+ * OpenRouter (`stealth/ox-alpha`) was budgeted and CHUNKED as if it were 128K.
+ * The catalog is the serving side's own declaration, so reading it is both more
+ * accurate than a regex table and free of the per-model maintenance that table
+ * demands.
+ *
+ * Kept in `internal/` (like `gateways.js` and `ollamaBacked.js`) because
+ * `providers.js` is the only caller and this directory stays self-contained —
+ * no imports out to other PortOS modules (see ../AGENTS.md).
+ */
+
+/**
+ * Keys under which an OpenAI-compatible catalog declares a context window.
+ * Different servers spell it differently and the union is small enough to just
+ * read all of them: OpenRouter (`context_length`), vLLM (`max_model_len`),
+ * LM Studio (`max_context_length` / `loaded_context_length`), llama.cpp
+ * (`n_ctx`), and the OpenAI-style `context_window` / `max_input_tokens`.
+ */
+const CONTEXT_WINDOW_KEYS = Object.freeze([
+ 'context_length',
+ 'context_window',
+ 'contextWindow',
+ 'max_context_length',
+ 'loaded_context_length',
+ 'max_model_len',
+ 'max_input_tokens',
+ 'n_ctx',
+]);
+
+const positiveInt = (value) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+};
+
+/**
+ * The context window one catalog entry declares, or `null` when it declares
+ * none. `null` is the "catalog didn't say" sentinel and must never collapse
+ * into a number — the caller falls back to its own heuristics for it, which is
+ * a different answer from "this model's window is small".
+ *
+ * When an entry declares SEVERAL windows the SMALLEST wins. OpenRouter is the
+ * case that forces this: its top-level `context_length` is the widest window
+ * any upstream offers for that model, while `top_provider.context_length` is
+ * what the default route actually serves. Budgeting to the wider number would
+ * build a prompt the served route rejects, so the conservative bound is the
+ * only safe read — and the same rule handles a local server that reports both a
+ * model's trained maximum and the smaller window it was loaded at.
+ *
+ * @param {unknown} entry
+ * @returns {number|null}
+ */
+export function catalogContextWindow(entry) {
+ if (!entry || typeof entry !== 'object') return null;
+ let smallest = null;
+ // One level of nesting, not a recursive walk: `top_provider` is the only
+ // nested shape any supported catalog uses, and a blind deep scan would sweep
+ // up unrelated numeric fields (pricing, quantization) that merely share a key.
+ for (const source of [entry, entry.top_provider]) {
+ if (!source || typeof source !== 'object') continue;
+ for (const key of CONTEXT_WINDOW_KEYS) {
+ const found = positiveInt(source[key]);
+ if (found && (smallest === null || found < smallest)) smallest = found;
+ }
+ }
+ return smallest;
+}
+
+/**
+ * Normalize a catalog array into `{ models, contextWindows }`.
+ *
+ * Entries are usually `{ id }` under `data` and bare strings under `models`,
+ * but servers mix all four shapes — hence the id fallbacks. An entry that
+ * resolves to no usable id THROWS rather than being dropped: a partially
+ * understood catalog persisted as a plausible-looking list is worse than a
+ * refresh that fails loudly (same posture as `_execCliModelList`).
+ *
+ * `contextWindows` carries an entry only for models whose window the catalog
+ * actually declared — a bare string list yields `{}`, which the caller must
+ * read as "unknown", never as "these models have no window".
+ *
+ * @param {unknown[]} entries
+ * @param {string} key — the payload key the entries came from, for the error text
+ * @returns {{ models: string[], contextWindows: Record<string, number> }}
+ */
+export function parseModelCatalog(entries, key) {
+ const models = [];
+ const contextWindows = {};
+ for (const entry of entries) {
+ const id = typeof entry === 'string' ? entry : (entry?.id || entry?.name || entry?.model);
+ if (typeof id !== 'string' || !id) {
+ throw new Error(`Model list response had "${key}" entries with no usable model id`);
+ }
+ models.push(id);
+ const window = catalogContextWindow(entry);
+ if (window) contextWindows[id] = window;
+ }
+ return { models, contextWindows };
+}
+
+/**
+ * Coerce whatever a model fetcher returned into the catalog shape, or `null`
+ * when it returned nothing usable.
+ *
+ * Most fetchers (every CLI probe, the Ollama `/api/tags` short-circuit) answer
+ * with a plain `string[]` and have no window information to offer; only the
+ * OpenAI-compatible `/models` parser returns the rich shape. Normalizing here
+ * keeps `fetchProviderModels`' historical `string[]` contract intact while the
+ * refresh path gets the windows.
+ *
+ * @param {unknown} result
+ * @returns {{ models: string[], contextWindows: Record<string, number> }|null}
+ */
+export function toModelCatalog(result) {
+ if (Array.isArray(result)) return { models: result, contextWindows: {} };
+ if (result && typeof result === 'object' && Array.isArray(result.models)) {
+ return { models: result.models, contextWindows: result.contextWindows || {} };
+ }
+ return null;
+}
+
+/**
+ * The one place that decides whether `modelContextWindows` is written at all:
+ * a non-empty map becomes a patch, an empty one writes nothing. Both the
+ * refresh path and `createProvider` go through this so the rule can't be
+ * relaxed on one side only.
+ */
+export const modelContextWindowPatch = (windows) =>
+ windows && Object.keys(windows).length > 0 ? { modelContextWindows: { ...windows } } : {};
+
+/**
+ * The `updateProvider` patch a probed catalog produces.
+ *
+ * The model list is always written — an empty list is a real answer (the user
+ * deleted their last local model). The window map is a MERGE, not a
+ * replacement, and that is the whole subtlety: catalogs are inconsistent about
+ * declaring `context_length`, so a listing that declares it for 3 of 50 models
+ * says nothing about the other 47. Replacing the map would drop them back to
+ * the assumed 128K — the exact bug this feature exists to fix, one refresh
+ * later. So: carry forward what earlier refreshes learned, let the fresh
+ * catalog overwrite it, and prune anything for a model the provider no longer
+ * lists (that entry can never be selected again, and keeping it grows the
+ * record forever).
+ *
+ * @param {{models: string[], contextWindows: Record<string, number>}} catalog
+ * @param {Record<string, number>} [previousWindows] — what the record already knew
+ * @returns {{models: string[], modelContextWindows?: Record<string, number>}}
+ */
+export function modelCatalogUpdate(catalog, previousWindows) {
+ const listed = new Set(catalog.models);
+ const merged = {};
+ for (const [id, tokens] of Object.entries(previousWindows || {})) {
+ const kept = positiveInt(tokens);
+ if (kept && listed.has(id)) merged[id] = kept;
+ }
+ Object.assign(merged, catalog.contextWindows || {});
+ return { models: [...catalog.models], ...modelContextWindowPatch(merged) };
+}
diff --git a/server/lib/aiToolkit/internal/modelCatalog.test.js b/server/lib/aiToolkit/internal/modelCatalog.test.js
new file mode 100644
index 0000000000..3e965b5798
--- /dev/null
+++ b/server/lib/aiToolkit/internal/modelCatalog.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect } from 'vitest';
+import { catalogContextWindow, modelCatalogUpdate, parseModelCatalog, toModelCatalog } from './modelCatalog.js';
+
+describe('catalogContextWindow', () => {
+ it('reads the spelling each vendor actually uses', () => {
+ expect(catalogContextWindow({ context_length: 1_000_000 })).toBe(1_000_000);
+ expect(catalogContextWindow({ max_model_len: 32_768 })).toBe(32_768);
+ expect(catalogContextWindow({ max_context_length: 8192 })).toBe(8192);
+ expect(catalogContextWindow({ n_ctx: 4096 })).toBe(4096);
+ expect(catalogContextWindow({ context_window: 200_000 })).toBe(200_000);
+ });
+
+ it('takes the SMALLEST declared window when an entry reports several', () => {
+ // OpenRouter's top-level `context_length` is the widest any upstream
+ // offers; `top_provider.context_length` is what the default route serves.
+ // Budgeting to the wider one builds a prompt the served route rejects.
+ expect(catalogContextWindow({
+ context_length: 1_000_000,
+ top_provider: { context_length: 256_000 },
+ })).toBe(256_000);
+ });
+
+ it('returns null — not zero — when the entry declares nothing', () => {
+ // `null` is the "catalog didn't say" sentinel: the caller falls back to its
+ // own heuristics for it, which is a different answer from a small window.
+ expect(catalogContextWindow({ id: 'some/model' })).toBeNull();
+ expect(catalogContextWindow('bare-string-entry')).toBeNull();
+ expect(catalogContextWindow(null)).toBeNull();
+ expect(catalogContextWindow({ context_length: 0 })).toBeNull();
+ expect(catalogContextWindow({ context_length: -1 })).toBeNull();
+ expect(catalogContextWindow({ context_length: 'lots' })).toBeNull();
+ });
+
+ it('ignores unrelated numbers nested elsewhere', () => {
+ expect(catalogContextWindow({ id: 'm', pricing: { prompt: 3 }, architecture: { n_ctx: 99 } })).toBeNull();
+ });
+});
+
+describe('parseModelCatalog', () => {
+ it('pairs ids with the windows the catalog declared, and only those', () => {
+ const { models, contextWindows } = parseModelCatalog([
+ { id: 'stealth/ox-alpha', context_length: 1_000_000 },
+ { id: 'openrouter/auto' },
+ 'bare-string-model',
+ ], 'data');
+
+ expect(models).toEqual(['stealth/ox-alpha', 'openrouter/auto', 'bare-string-model']);
+ // A model the catalog said nothing about must be ABSENT, not zero — an
+ // entry here would pin its budget to a made-up number.
+ expect(contextWindows).toEqual({ 'stealth/ox-alpha': 1_000_000 });
+ });
+
+ it('accepts every id spelling servers mix', () => {
+ const { models } = parseModelCatalog([{ id: 'a' }, { name: 'b' }, { model: 'c' }, 'd'], 'models');
+ expect(models).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('throws on an entry with no usable id rather than persisting a broken catalog', () => {
+ expect(() => parseModelCatalog([{ id: 'a' }, { size: 3 }], 'data'))
+ .toThrow('Model list response had "data" entries with no usable model id');
+ });
+
+ it('yields an empty catalog for an empty list', () => {
+ expect(parseModelCatalog([], 'data')).toEqual({ models: [], contextWindows: {} });
+ });
+});
+
+describe('toModelCatalog', () => {
+ it('lifts a plain id list into the catalog shape with no windows', () => {
+ expect(toModelCatalog(['a', 'b'])).toEqual({ models: ['a', 'b'], contextWindows: {} });
+ });
+
+ it('passes a catalog through', () => {
+ const catalog = { models: ['a'], contextWindows: { a: 128_000 } };
+ expect(toModelCatalog(catalog)).toEqual(catalog);
+ });
+
+ it('is null for anything that is not a usable catalog', () => {
+ expect(toModelCatalog(null)).toBeNull();
+ expect(toModelCatalog(undefined)).toBeNull();
+ expect(toModelCatalog({ models: 'nope' })).toBeNull();
+ });
+});
+
+describe('modelCatalogUpdate', () => {
+ const catalog = { models: ['a', 'b'], contextWindows: { a: 512_000 } };
+
+ it('merges per model rather than replacing the map', () => {
+ // A listing that declares a window for `a` says nothing about `b` — the
+ // window `b` was learned from an earlier refresh has to survive, or it
+ // drops back to the assumed 128K one refresh later.
+ expect(modelCatalogUpdate(catalog, { a: 128_000, b: 1_000_000 }))
+ .toEqual({ models: ['a', 'b'], modelContextWindows: { a: 512_000, b: 1_000_000 } });
+ });
+
+ it('prunes windows for models the provider no longer lists', () => {
+ // That entry can never be selected again, and keeping it grows the record
+ // by one dead key per model the upstream ever retired.
+ expect(modelCatalogUpdate(catalog, { gone: 64_000 }).modelContextWindows)
+ .toEqual({ a: 512_000 });
+ });
+
+ it('omits the key entirely when nothing is known', () => {
+ // Absent, not `{}` — a record that never refreshed stays clean.
+ expect(modelCatalogUpdate({ models: ['a'], contextWindows: {} })).toEqual({ models: ['a'] });
+ });
+
+ it('always writes the model list, including a legitimately empty one', () => {
+ expect(modelCatalogUpdate({ models: [], contextWindows: {} })).toEqual({ models: [] });
+ });
+
+ it('copies the list so batched members never share one instance', () => {
+ expect(modelCatalogUpdate(catalog).models).not.toBe(catalog.models);
+ });
+});
diff --git a/server/lib/aiToolkit/providers.batch.test.js b/server/lib/aiToolkit/providers.batch.test.js
index a816ec583e..a40bb9411d 100644
--- a/server/lib/aiToolkit/providers.batch.test.js
+++ b/server/lib/aiToolkit/providers.batch.test.js
@@ -217,15 +217,15 @@ describe('refreshProviderModelsBatch — one providers.json write per fan-out',
});
it('treats a probe that answers with no array as missing, not as an update', async () => {
- // `fetchProviderModels` promises an array or a throw, so this is a guard
- // against a future fetcher rather than a reachable path today — but the
- // failure mode it prevents is the whole batch dying on `[...undefined]`,
- // taking the healthy groups' write down with it.
+ // `fetchProviderModelCatalog` promises a catalog or a throw, so this is a
+ // guard against a future fetcher rather than a reachable path today — but
+ // the failure mode it prevents is the whole batch dying on
+ // `[...undefined]`, taking the healthy groups' write down with it.
stubOllama({ [LOCAL]: ['qwen2.5:7b'] });
const broken = await providerService.createProvider(ollamaProvider('Broken', { base: REMOTE }));
const healthy = await providerService.createProvider(ollamaProvider('Local One'));
- vi.spyOn(providerService, 'fetchProviderModels').mockImplementation(async (id) => (
- id === broken.id ? undefined : ['qwen2.5:7b']
+ vi.spyOn(providerService, 'fetchProviderModelCatalog').mockImplementation(async (id) => (
+ id === broken.id ? undefined : { models: ['qwen2.5:7b'], contextWindows: {} }
));
atomicWrite.mockClear();
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 8f923d6d2c..db65694636 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -23,6 +23,7 @@ import {
import { isOllamaBackedProvider, ollamaBaseFromProvider } from './internal/ollamaBacked.js';
import { gatewayForProvider, isGatewayBackedProvider } from './internal/gateways.js';
import { canRefreshModels, ollamaRefreshGroupKey, resolveModelFetcher } from './internal/modelFetchers.js';
+import { modelCatalogUpdate, modelContextWindowPatch, parseModelCatalog, toModelCatalog } from './internal/modelCatalog.js';
// Re-exported (rather than defined here) so the model-fetcher table can key its
// ollama row on the same predicate without importing back into this module.
@@ -603,6 +604,9 @@ export function createProviderService(config = {}) {
topP: providerData.topP,
thinking: providerData.thinking,
contextWindow: providerData.contextWindow || null,
+ // Per-model windows learned from the provider's own /models catalog.
+ // Same non-empty rule the refresh path uses, from one implementation.
+ ...modelContextWindowPatch(providerData.modelContextWindows),
timeout: providerData.timeout || 300000,
enabled: providerData.enabled !== false,
// Claude Ollama marker — preserve so adopting the sample via POST drives
@@ -815,10 +819,17 @@ export function createProviderService(config = {}) {
* Same contract as `refreshProviderModels` minus the write: `null` means
* ONLY "no such provider"; every other failure throws (with `.status`).
*
+ * Answers the CATALOG shape: the id list plus, for the fetchers whose
+ * upstream declares it, each model's real context window. A fetcher with no
+ * window information yields `contextWindows: {}` — which means "unknown",
+ * never "these models have no window", so the caller must not persist it
+ * over what a previous refresh learned. {@link fetchProviderModels} is the
+ * id-list-only view for callers that don't care.
+ *
* @param {string} id
- * @returns {Promise<string[]|null>}
+ * @returns {Promise<{models: string[], contextWindows: Record<string, number>}|null>}
*/
- async fetchProviderModels(id) {
+ async fetchProviderModelCatalog(id) {
const data = await loadProviders();
const provider = withGatewayApiKey(data.providers[id], data.providers);
@@ -827,13 +838,13 @@ export function createProviderService(config = {}) {
}
// `null` = no refreshable branch matched below (provider type/shape isn't
- // refreshable — the pre-existing no-op case); an array = a completed
+ // refreshable — the pre-existing no-op case); a result = a completed
// fetch, which may legitimately be empty (e.g. an Ollama-backed provider
// whose only installed model was just deleted). Only the `null` sentinel
// means "nothing to persist" — a `.length === 0` check here would also
// swallow that legitimate empty result and leave a deleted model stuck
// in the provider's persisted list.
- let models = null;
+ let fetched = null;
try {
// A TUI provider's model is normally fixed by its CLI/config, so only
@@ -845,15 +856,15 @@ export function createProviderService(config = {}) {
const tuiFetcher = provider.type === 'tui' ? resolveModelFetcher(provider) : null;
if (provider.type === 'api') {
- models = await this._refreshAPIProviderModels(provider);
+ fetched = await this._refreshAPIProviderModels(provider);
} else if (provider.type === 'cli') {
- models = await this._refreshCLIProviderModels(provider);
+ fetched = await this._refreshCLIProviderModels(provider);
} else if (tuiFetcher) {
- models = await this[tuiFetcher.fetch](provider);
+ fetched = await this[tuiFetcher.fetch](provider);
} else {
// No branch matched — this provider type/shape has no fetcher. Say so,
// the same 400 the CLI arm's own fall-through throws. Previously this
- // fell out as `models === null` and the route rendered it as
+ // fell out as `fetched === null` and the route rendered it as
// `404 Provider not found or not an API type`, which is exactly the
// false message the rethrow above set out to stop showing: a plain
// `codex-tui`/`grok-tui` provider exists and its type is fine, it just
@@ -881,30 +892,47 @@ export function createProviderService(config = {}) {
throw error;
}
- // Belt-and-braces: every branch above returns an array or throws, so this
- // is unreachable today — but a future fetcher that returns null must not
- // persist `models: null` over the user's list. Throws rather than
+ // Belt-and-braces: every branch above returns a list (or a catalog) or
+ // throws, so this is unreachable today — but a future fetcher that
+ // returns null must not persist `models: null` over the user's list. Throws rather than
// returning null so `null` keeps exactly ONE meaning out of this function:
// the provider does not exist. That is what lets the route's 404 say
// plainly "Provider not found" instead of guessing at a reason.
- if (models === null) {
+ const catalog = toModelCatalog(fetched);
+ if (catalog === null) {
const unsupported = new Error(`Model refresh returned nothing for provider '${provider.id}'`);
unsupported.status = 400;
throw unsupported;
}
- return models;
+ return catalog;
+ },
+
+ /**
+ * The id-list-only view of {@link fetchProviderModelCatalog}, kept as the
+ * historical `string[] | null` contract. Nothing in PortOS calls it today
+ * (the post-install Ollama fan-out goes through `refreshProviderModelsBatch`);
+ * it stays because this directory is vendored and its method surface is the
+ * contract an upstream sync merges against — see ../AGENTS.md.
+ *
+ * @param {string} id
+ * @returns {Promise<string[]|null>}
+ */
+ async fetchProviderModels(id) {
+ const catalog = await this.fetchProviderModelCatalog(id);
+ return catalog === null ? null : catalog.models;
},
/**
* Probe AND persist a provider's model list. Thin composition of
- * {@link fetchProviderModels} + `updateProvider` — keep it that way so the
- * two halves can't drift.
+ * {@link fetchProviderModelCatalog} + `updateProvider` — keep it that way so
+ * the two halves can't drift.
*/
async refreshProviderModels(id) {
- const models = await this.fetchProviderModels(id);
- if (models === null) return null;
- return this.updateProvider(id, { models });
+ const catalog = await this.fetchProviderModelCatalog(id);
+ if (catalog === null) return null;
+ const previous = (await this.getProviderById(id))?.modelContextWindows;
+ return this.updateProvider(id, modelCatalogUpdate(catalog, previous));
},
/**
@@ -933,16 +961,17 @@ export function createProviderService(config = {}) {
* outcome so the host can log group-level context (one line per group, not
* one per member) and decide what a failure means.
*
- * - `updated` — probed successfully; `models` was applied to every member
- * still present at save time. `[]` is a real answer (the user deleted
- * their last model) and IS persisted; only the two statuses below skip.
+ * - `updated` — probed successfully; the group's `catalog` was applied to
+ * every member still present at save time. An empty model list is a real
+ * answer (the user deleted their last model) and IS persisted; only the
+ * two statuses below skip.
* - `failed` — the probe threw; `error` carries it. The stored lists are
* left untouched.
* - `missing` — no such provider, or the lead was deleted between the
* grouping read and its probe.
*
* @param {string[]} ids
- * @returns {Promise<Array<{ ids: string[], leadId: string, status: 'updated'|'failed'|'missing', models?: string[], error?: Error }>>}
+ * @returns {Promise<Array<{ ids: string[], leadId: string, status: 'updated'|'failed'|'missing', catalog?: {models: string[], contextWindows: Record<string, number>}, error?: Error }>>}
*/
async refreshProviderModelsBatch(ids) {
const requested = [...new Set(Array.isArray(ids) ? ids : [])];
@@ -978,8 +1007,8 @@ export function createProviderService(config = {}) {
// install/delete, so nothing is waiting on the wall clock.
for (const group of groups) {
if (!data.providers[group.leadId]) continue;
- const probed = await this.fetchProviderModels(group.leadId).then(
- (models) => ({ models }),
+ const probed = await this.fetchProviderModelCatalog(group.leadId).then(
+ (catalog) => ({ catalog }),
(error) => ({ error })
);
if (probed.error) {
@@ -987,16 +1016,13 @@ export function createProviderService(config = {}) {
group.error = probed.error;
continue;
}
- // `null` here means the lead vanished mid-probe — the same `missing`
- // the group already carries, so leave the status alone. Validated as an
- // ARRAY rather than compared to `null`: `fetchProviderModels` promises
- // an array or a throw, but a future fetcher that leaks `undefined` must
- // land on `missing` too, not be persisted as an "updated" catalog (and
- // then crash the whole batch on the spread below). `[]` is an array, so
- // a legitimately empty catalog still passes.
- if (!Array.isArray(probed.models)) continue;
+ // A falsy catalog means the lead vanished mid-probe — the same
+ // `missing` the group already carries, so leave the status alone.
+ // Anything truthy has been through `toModelCatalog`, so its shape is
+ // already guaranteed; a legitimately empty catalog still passes.
+ if (!probed.catalog) continue;
group.status = 'updated';
- group.models = probed.models;
+ group.catalog = probed.catalog;
}
const updated = groups.filter((g) => g.status === 'updated');
@@ -1014,9 +1040,14 @@ export function createProviderService(config = {}) {
// Deleted between the grouping read and now — nothing to write, and
// re-adding it here would resurrect a provider the user removed.
if (!provider) continue;
- // Copy the list per provider so members of one group don't end up
- // sharing (and later mutating) a single array instance.
- fresh.providers[id] = { ...provider, models: [...group.models], id };
+ // Built per member rather than once per group: `modelCatalogUpdate`
+ // merges against THAT provider's previously-learned windows, and it
+ // copies the list, so members never share a mutable instance.
+ fresh.providers[id] = {
+ ...provider,
+ ...modelCatalogUpdate(group.catalog, provider.modelContextWindows),
+ id,
+ };
changed = true;
}
}
@@ -1025,6 +1056,14 @@ export function createProviderService(config = {}) {
return groups;
},
+ /**
+ * Probe an OpenAI-compatible `/models` endpoint.
+ *
+ * Returns the CATALOG shape (`{ models, contextWindows }`) rather than a
+ * bare id list — see internal/modelCatalog.js. The Ollama `/api/tags`
+ * short-circuit below still answers with a plain array; `toModelCatalog`
+ * normalizes both at the `fetchProviderModelCatalog` boundary.
+ */
async _refreshAPIProviderModels(provider) {
if (provider.endpoint?.includes('ollama') || provider.endpoint?.includes(':11434')) {
const ollamaUrl = `${provider.endpoint}/api/tags`;
@@ -1080,16 +1119,11 @@ export function createProviderService(config = {}) {
// a plausible-looking, entirely unusable catalog. Anything that still
// resolves to nothing means the shape isn't one we understand, so throw
// rather than save it, same posture as the unparseable-body case above.
- const toModelIds = (entries, key) => {
- const ids = entries.map(m => (typeof m === 'string' ? m : (m?.id || m?.name || m?.model)));
- if (ids.some(id => typeof id !== 'string' || !id)) {
- throw new Error(`Model list response had "${key}" entries with no usable model id`);
- }
- return ids;
- };
-
- if (Array.isArray(responseData.data)) return toModelIds(responseData.data, 'data');
- if (Array.isArray(responseData.models)) return toModelIds(responseData.models, 'models');
+ // `parseModelCatalog` also harvests each entry's declared context window
+ // (internal/modelCatalog.js) — the only source that knows a hosted
+ // gateway's model really has a 1M window rather than the assumed 128K.
+ if (Array.isArray(responseData.data)) return parseModelCatalog(responseData.data, 'data');
+ if (Array.isArray(responseData.models)) return parseModelCatalog(responseData.models, 'models');
throw new Error('Model list response had no recognizable "data" or "models" array');
},
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 16dbe94472..f16bce5c96 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -1435,6 +1435,73 @@ describe('Provider Service', () => {
expect((await providerService.getProviderById(bad.id)).models).toEqual(['model-a']);
});
+ it('records each model’s declared context window alongside the id list', async () => {
+ // Without this the whole catalog fell through to the blanket 128K
+ // assumption, so a 1M-context model was budgeted — and manuscripts were
+ // CHUNKED — as if it were an eighth the size.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ data: [
+ { id: 'stealth/ox-alpha', context_length: 1_000_000 },
+ { id: 'openrouter/auto' },
+ ],
+ }),
+ }));
+ const p = await providerService.createProvider({
+ name: 'Gateway API', type: 'api', endpoint: 'https://api.generic.com/v1', allowCustomEndpoint: true,
+ });
+
+ const updated = await providerService.refreshProviderModels(p.id);
+ expect(updated.models).toEqual(['stealth/ox-alpha', 'openrouter/auto']);
+ expect(updated.modelContextWindows).toEqual({ 'stealth/ox-alpha': 1_000_000 });
+ expect((await providerService.getProviderById(p.id)).modelContextWindows)
+ .toEqual({ 'stealth/ox-alpha': 1_000_000 });
+ });
+
+ it('merges a partial catalog per model instead of replacing the whole map', async () => {
+ // Catalogs are inconsistent about declaring `context_length`. A listing
+ // that declares it for one model says NOTHING about the others — wiping
+ // them would drop those back to the assumed 128K one refresh later, which
+ // is the bug this whole feature exists to fix.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: [{ id: 'a', context_length: 512_000 }, { id: 'b' }] }),
+ }));
+ const p = await providerService.createProvider({
+ name: 'Partial API',
+ type: 'api',
+ endpoint: 'https://api.generic.com/v1',
+ allowCustomEndpoint: true,
+ // `b' was learned earlier; `gone' is no longer in the catalog.
+ modelContextWindows: { a: 128_000, b: 1_000_000, gone: 64_000 },
+ });
+
+ const updated = await providerService.refreshProviderModels(p.id);
+ expect(updated.modelContextWindows).toEqual({ a: 512_000, b: 1_000_000 });
+ });
+
+ it('keeps previously-learned windows when a later catalog declares none', async () => {
+ // "The listing said nothing about context" is UNKNOWN, not "no model has
+ // a window" — erasing the map on an id-only listing would silently drop a
+ // 1M model back to the assumed 128K.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: [{ id: 'model-a' }] }),
+ }));
+ const p = await providerService.createProvider({
+ name: 'Forgetful API',
+ type: 'api',
+ endpoint: 'https://api.generic.com/v1',
+ allowCustomEndpoint: true,
+ modelContextWindows: { 'model-a': 400_000 },
+ });
+
+ const updated = await providerService.refreshProviderModels(p.id);
+ expect(updated.models).toEqual(['model-a']);
+ expect(updated.modelContextWindows).toEqual({ 'model-a': 400_000 });
+ });
+
it('throws and leaves the stored list untouched when a 200 body is not JSON', async () => {
// A captive portal / login page / proxy error served as HTTP 200. Degrading
// to `[]` here emptied the model dropdown while the UI toasted "Models
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index ae4b595538..f58eed6792 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -101,6 +101,14 @@ export const providerSchema = z.object({
// this provider — distinct from numCtx (what we *ask Ollama for*). For cloud
// providers numCtx stays null and this reflects the model's real ceiling.
contextWindow: z.number().int().min(512).max(2097152).nullable().optional(),
+ // Per-model context windows READ FROM the provider's own `/models` catalog
+ // (OpenRouter's `context_length`, vLLM's `max_model_len`, …), keyed by model
+ // id. Written by model refresh, not typed by a human — it beats the hardcoded
+ // model table and loses to the explicit `contextWindow` override above.
+ // The ceiling is deliberately wider than `contextWindow`'s: that one bounds
+ // what a person can type, this one has to accept whatever a vendor declares,
+ // and rejecting a 10M-window model would 400 the whole provider write.
+ modelContextWindows: z.record(z.number().int().min(512).max(33554432)).optional(),
timeout: z.number().int().min(MIN_TIMEOUT).max(MAX_TIMEOUT).optional(),
enabled: z.boolean().optional(),
// Marks a `claude` CLI/TUI provider whose ANTHROPIC_BASE_URL points at a
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index 54e06d64bc..21d080a82b 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -168,11 +168,13 @@ export function resolveEffortHint(stage, options = {}) {
return options.effortOverride || stage?.effort || options.effortDefault || null;
}
-// A conservative-large window assumed for frontier CLI / cloud-API providers
+// A conservative-large window ASSUMED for frontier CLI / cloud-API providers
// that haven't declared one. 128K is below every current frontier model's real
// ceiling (Claude/GPT/Gemini are ≥128K, often ~1M), so it means "a typical
-// whole manuscript fits in one call" without over-promising. Users with very
-// large manuscripts can set an explicit `contextWindow` to lift it further.
+// whole manuscript fits in one call" without over-promising. It is a floor to
+// escape, not a cap to honor: refreshing the provider's models records each
+// model's real window (`modelContextWindows`), and an explicit `contextWindow`
+// overrides both.
export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
export const CODEX_CONTEXT_WINDOW = 1_000_000;
export const GEMINI_CONTEXT_WINDOW = 1_048_576;
@@ -235,14 +237,33 @@ const isLikelyLargeContextProvider = (provider) => {
return false;
};
+/**
+ * The window this provider's own `/models` catalog reported for this model, or
+ * `null` when the catalog never mentioned it. Populated by model refresh (see
+ * aiToolkit/internal/modelCatalog.js), so it is the serving side's declaration
+ * rather than a guess — which is why it outranks the hand-maintained regex
+ * table below. Mirror of `catalogModelContextWindow` in
+ * client/src/utils/providers.js.
+ */
+export function catalogModelContextWindow(provider, model) {
+ const windows = provider?.modelContextWindows;
+ if (!windows || typeof windows !== 'object') return null;
+ if (typeof model !== 'string' || !model) return null;
+ const tokens = Number(windows[model]);
+ return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
+}
+
// Planning-time context window for a provider/model: an explicit
-// `contextWindow` wins, else a known model window for the resolved model, else
-// a known provider-level window for configured-default process providers, else
-// the Ollama per-request `numCtx`, else a large default for frontier providers,
+// `contextWindow` wins, else the window the provider's own catalog reported for
+// this model, else a known model window for the resolved model, else a known
+// provider-level window for configured-default process providers, else the
+// Ollama per-request `numCtx`, else a large default for frontier providers,
// else null (the budgeter applies a conservative floor for unknown local
// backends).
export function effectiveContextWindow(provider, model) {
if (Number(provider?.contextWindow) > 0) return Number(provider.contextWindow);
+ const catalogWindow = catalogModelContextWindow(provider, model);
+ if (catalogWindow) return catalogWindow;
const modelWindow = knownModelContextWindow(model);
if (modelWindow) return modelWindow;
const providerWindow = knownProviderContextWindow(provider);
diff --git a/server/lib/stageRunner.mirror.test.js b/server/lib/stageRunner.mirror.test.js
index 4d7a6f208f..a3ca58b309 100644
--- a/server/lib/stageRunner.mirror.test.js
+++ b/server/lib/stageRunner.mirror.test.js
@@ -40,6 +40,10 @@ const MIRRORED_NAMES = [
'GROK_CONTEXT_WINDOW',
'KIMI_CONTEXT_WINDOW',
'KNOWN_MODEL_CONTEXT_WINDOWS',
+ // The catalog rung sits ABOVE the table in both ladders, so a divergence here
+ // is the same silent ~8x disagreement the table's parity closes. Both copies
+ // are declared `function` precisely so this comparison can be made.
+ 'catalogModelContextWindow',
];
describe('stageRunner↔client providers context-window mirror parity', () => {
diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.js
index 43232eb6cf..806db96ec9 100644
--- a/server/lib/stageRunner.test.js
+++ b/server/lib/stageRunner.test.js
@@ -34,6 +34,7 @@ const {
GEMINI_CONTEXT_WINDOW,
GROK_CONTEXT_WINDOW,
KIMI_CONTEXT_WINDOW,
+ catalogModelContextWindow,
effectiveContextWindow,
knownModelContextWindow,
knownProviderContextWindow,
@@ -143,6 +144,40 @@ describe('stageRunner — context windows', () => {
)).toBe(64_000);
});
+ it('uses the catalog window a model refresh recorded, above the regex table and the assumed default', () => {
+ // The OpenCode/OpenRouter wrapper case: a TUI provider matching no vendor
+ // row used to fall straight to the blanket 128K, so a 1M model was chunked
+ // at an eighth of its real window.
+ const wrapper = {
+ id: 'opencode-openrouter-tui',
+ type: 'tui',
+ command: 'opencode',
+ modelContextWindows: { 'stealth/ox-alpha': 1_000_000 },
+ };
+ expect(effectiveContextWindow(wrapper, 'stealth/ox-alpha')).toBe(1_000_000);
+ // A model the catalog never mentioned still takes the old ladder.
+ expect(effectiveContextWindow(wrapper, 'openrouter/auto')).toBe(DEFAULT_LARGE_CONTEXT_WINDOW);
+ // The catalog beats the hand-maintained model table — it is the serving
+ // side's own declaration of what THIS provider will accept.
+ expect(effectiveContextWindow(
+ { type: 'api', endpoint: 'https://api.example.test/v1', modelContextWindows: { 'claude-sonnet-4-6': 200_000 } },
+ 'claude-sonnet-4-6'
+ )).toBe(200_000);
+ // …and loses to an explicit user override.
+ expect(effectiveContextWindow(
+ { type: 'tui', contextWindow: 64_000, modelContextWindows: { m: 1_000_000 } },
+ 'm'
+ )).toBe(64_000);
+ });
+
+ it('ignores a malformed or unrelated catalog entry instead of budgeting from it', () => {
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 0 } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 'lots' } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { other: 1_000 } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: null }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 1_000 } }, null)).toBeNull();
+ });
+
it('uses model and provider windows before provider numCtx', () => {
expect(effectiveContextWindow(
{ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 },