fix: 컨텍스트 윈도우가 이전 모델 값에 고정되던 문제

게이지가 8192로 표시됐으나 지서버 gemma4:26b의 실제 값은 262144, 32배 차이.
원인이 세 겹이었다.

1. resolveNumCtx()의 _cachedNumCtx가 아무 키 없이 프로세스 수명 내내 유지됐다.
   6곳에서 설정되는데 무효화하는 코드가 어디에도 없어, 모델/provider를 바꿔도
   이전 값을 계속 반환했다(클로서버로 바꿨는데 지서버의 262k가 계속 보이던 증상).
   → (provider, models.primary, provider별 model, llm.num_ctx) 키에 연동

2. 활성 provider가 아니라 localhost:11434를 하드코딩해 조회했다.
   provider가 ollama_local(지서버)일 때 클로서버 로컬 Ollama에 물어보니
   "model not found" → 최후 폴백 8192로 떨어졌다.
   → activeOllamaEndpoint() 추가, /api/model-context의 per-model 조회에도 적용

3. 프론트엔드 _fetchAppCtxMax()가 페이지 로드 시 한 번만 조회했다.
   → force 인자 추가, 설정 저장 직후 재조회

검증: 게이지 8192 → 262144(지서버 실제값 일치), 반복 호출 5회 안정.
캐시 키는 모델 전환 시 무효화되고 설정 동일 시 적중.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-08-09 01:04:12 +09:00
1 parent de738c3abd
commit 1146b59199
3 files changed
+60 -8

No files matched your search

+4 -3
View File
@@ -108,7 +108,7 @@ import { getPaths } from '../config/paths';
import { getVault, SecretValue } from '../security/vault';
import { getOllamaClient } from '../agents/ollama-client';
import { spawnAgent } from '../agents/spawner';
import { getSession, addMessage, getHistory, getHistoryForApiCall, getWorkspace, setWorkspace, clearHistory, setContextTokens, cleanupSessions, cleanupEmptySessions, migrateGlobalSessionsToUser, listAllSessions, resolveNumCtx } from './session';
import { getSession, addMessage, getHistory, getHistoryForApiCall, getWorkspace, setWorkspace, clearHistory, setContextTokens, cleanupSessions, cleanupEmptySessions, migrateGlobalSessionsToUser, listAllSessions, resolveNumCtx, activeOllamaEndpoint } from './session';
import { hookBus } from './hooks/hooks';
import { loadWorkspaceHooks } from './hooks/hook-loader';
import { validateLinksInText, filterImageMarkdown } from './guards/link-validator';
@@ -3545,9 +3545,10 @@ app.get('/api/model-context', async (req, res) => {
const manifestCtx = _readOllamaManifestNumCtx(model);
if (manifestCtx) { res.json({ contextWindow: manifestCtx }); return; }
// Fall back to /api/show model_info
// Fall back to /api/show model_info — on the active provider's endpoint, since
// the model being asked about may live on a remote box (지서버) rather than local.
try {
const ollamaEndpoint = (getConfig().getConfig() as any).ollama?.endpoint || 'http://localhost:11434';
const ollamaEndpoint = activeOllamaEndpoint();
const response = await fetch(`${ollamaEndpoint}/api/show`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
+44 -2
View File
@@ -98,9 +98,48 @@ function resolveDefaultWorkspace(username?: string): string {
}
let _cachedNumCtx: number | null = null;
let _cachedNumCtxKey: string | null = null;
/**
* Identity of the settings this resolution depends on. The cache used to be
* keyed on nothing, so switching provider or model kept serving the previous
* model's window for the rest of the process's life (e.g. the gauge stuck at
* 지서버's 262144 after switching back to a cloud model).
*/
function numCtxCacheKey(): string {
try {
const cfg: any = getConfig().getConfig();
const provider = String(cfg?.llm?.provider || 'ollama');
return [
provider,
String(cfg?.models?.primary || ''),
String(cfg?.llm?.providers?.[provider]?.model || ''),
String(cfg?.llm?.num_ctx || ''),
].join('|');
} catch {
return 'unknown';
}
}
/** Endpoint of the provider that is actually active, not a hardcoded default. */
export function activeOllamaEndpoint(): string {
try {
const cfg: any = getConfig().getConfig();
const provider = String(cfg?.llm?.provider || 'ollama');
const providerCfg = cfg?.llm?.providers?.[provider] || {};
const endpoint = providerCfg.endpoint || providerCfg.base_url || providerCfg.baseUrl;
if (endpoint) return String(endpoint).replace(/\/+$/, '');
if (cfg?.ollama?.endpoint) return String(cfg.ollama.endpoint).replace(/\/+$/, '');
} catch { /* fall through */ }
return 'http://localhost:11434';
}
export function resolveNumCtx(): number {
if (_cachedNumCtx !== null) return _cachedNumCtx;
const key = numCtxCacheKey();
if (_cachedNumCtx !== null && _cachedNumCtxKey === key) return _cachedNumCtx;
// Config changed since the cached value was computed — recompute below.
_cachedNumCtx = null;
_cachedNumCtxKey = key;
// 1. Env vars (highest priority)
for (const raw of [process.env.LOCALCLAW_SESSION_NUM_CTX, process.env.LOCALCLAW_CHAT_NUM_CTX]) {
@@ -159,8 +198,11 @@ export function resolveNumCtx(): number {
const cfg: any = getConfig().getConfig();
const model = String(cfg?.models?.primary || cfg?.llm?.providers?.ollama?.model || '');
if (model) {
// Must hit the *active* provider: with llm.provider=ollama_local the model
// lives on 지서버, and asking localhost returned "model not found" — which
// dropped through to the 8192 last-resort while the real window was 262144.
const result = spawnSync('curl', [
'-s', '-X', 'POST', 'http://localhost:11434/api/show',
'-s', '-X', 'POST', `${activeOllamaEndpoint()}/api/show`,
'-H', 'Content-Type: application/json',
'-d', JSON.stringify({ name: model }),
], { timeout: 3000, encoding: 'utf-8' });
+12 -3
View File
@@ -256,13 +256,19 @@ let chatSessions = [];
let activeChatSessionId = null;
let _appCtxMax = 0;
async function _fetchAppCtxMax() {
if (_appCtxMax > 0) return;
// force=true re-queries even when a value is cached — the window belongs to the
// active model, so a cache-once made the gauge keep showing the previous model's
// max after switching provider/model.
async function _fetchAppCtxMax(force) {
if (_appCtxMax > 0 && !force) return;
try {
const r = await fetch('/api/model-context', { headers: authHeaders() });
if (!r.ok) return;
const d = await r.json();
if (d.contextWindow) { _appCtxMax = d.contextWindow; renderSessionsList(); }
if (d.contextWindow && d.contextWindow !== _appCtxMax) {
_appCtxMax = d.contextWindow;
renderSessionsList();
}
} catch (_) {}
}
let sessionsEditMode = false;
@@ -767,6 +773,9 @@ async function saveSettings() {
await api('/api/settings/openweather', { method: 'POST', body: JSON.stringify({ api_key: owKey }) });
}
await loadSearchSettingsSummary();
// Model/provider may have just changed — the context gauge's max belongs to
// the active model, so re-resolve it instead of keeping the previous value.
_fetchAppCtxMax(true);
quickSearchRigor = payload.search_rigor || quickSearchRigor;
updateQuickModeUI();
addProcessEntry('final', '설정이 저장되었습니다.');