The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(budget): ein eigener Server im LAN wird nicht mehr als bezahlt gekappt
purpled6e6be37a9b7
diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.tsindex 5bd64e3f..56f418c6 100644--- a/src/hooks/useABCompare.ts+++ b/src/hooks/useABCompare.ts@@ -8,6 +8,7 @@ import { useSettingsStore } from '../stores/settingsStore'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { getModelMaxTokens } from '../lib/context-compaction'import { applySendBudget, chatBudgetApplies, sharedChatSendBudget } from '../lib/chat-send-budget'+import { sendsToALanBackend } from '../lib/lan-openai-slot'import { v4 as uuid } from 'uuid'import type { ChatMessage } from '../api/providers/types'import type { Message } from '../types/chat'@@ -70,6 +71,7 @@ export function useABCompare() {: 0,sendWindowTokens: settings.codexSendWindowTokens,contextDecay: settings.contextDecay,+ localBackend: sendsToALanBackend(providerId),}}),),diff --git a/src/hooks/useActiveContextWindow.ts b/src/hooks/useActiveContextWindow.tsindex 7f7ddd91..19cd8972 100644--- a/src/hooks/useActiveContextWindow.ts+++ b/src/hooks/useActiveContextWindow.ts@@ -11,11 +11,10 @@ import { isManagedBuiltinSlot } from '../api/builtin-ensure'import { ENGINE_DEFAULT_CTX } from '../lib/builtin-ctx'import { bundledEngineStatus, bundledCtxTrain } from '../api/engine'import { getProviderForModel } from '../api/providers'-import { isPrivateOrLanHost, hostnameOf } from '../api/backend'-import { useProviderStore } from '../stores/providerStore'import type { ContextSource } from '../lib/context-source'import type { ProviderClient } from '../api/providers/types'import { resolveActiveWindow } from '../lib/context-source'+import { isLanOpenAiBackend, sendsToALanBackend } from '../lib/lan-openai-slot'/** `custom` ist jeder andere OpenAI-kompatible Server auf diesem Rechner oder* im LAN: llama.cpp, vLLM, KoboldCpp, text-generation-webui (GH #129). */@@ -60,23 +59,6 @@ const NO_CONTEXT: ActiveContext = {adjustable: false, source: 'guess', windowKey: '',}-/**- * Laeuft der eingestellte OpenAI-Slot auf diesem Rechner oder im LAN?- *- * Dieselbe Frage, die `isLanBackend` im Provider stellt, und bewusst dieselbe- * Antwortquelle: die Voreinstellung des Slots ODER der Hostname. Ein fremder- * Host im Internet bekommt weder Metadaten-Abfragen noch einen Fensterwaehler.- */-function isLanOpenAiBackend(): boolean {- try {- const cfg = useProviderStore.getState().providers.openai- if (!cfg) return false- return cfg.isLocal === true || isPrivateOrLanHost(hostnameOf(cfg.baseUrl))- } catch {- return false- }-}-/** Der Client zu einem Modellnamen, ohne zu werfen, wenn der Slot fehlt. */function safeProviderFor(modelName: string): { provider: ProviderClient | null; modelId: string } {try {@@ -277,6 +259,10 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {modelWindow: max,sendWindowTokens,capEnabled,+ // Der Zweig oben kehrt nur um, wenn der eigene Server ein Fenster+ // GENANNT hat. Sagt er keins, faellt er bis hierher durch, und ohne+ // diese Zeile bekaeme er dann doch den bezahlten Deckel.+ localBackend: sendsToALanBackend(providerId),}),isTrue: false,// Aus der Ferne ist das Fenster keine Sache des Nutzers: es gehoertdiff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex a63d0731..0d32d46d 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -43,6 +43,7 @@ import { buildVisionFeedback } from '../api/vision-feedback'import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'import { buildRequestMessages, trimWorkingHistory } from '../lib/context-decay'import { effectiveSendWindow } from '../lib/send-window'+import { sendsToALanBackend } from '../lib/lan-openai-slot'import { useSendSizeStore } from '../stores/sendSizeStore'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'@@ -988,6 +989,7 @@ export function useAgentChat() {sendWindowTokens: settings.codexSendWindowTokens,capEnabled: decayOn,smallModelMode: settings.smallModelMode,+ localBackend: sendsToALanBackend(providerId),})let sendMessages: ChatMessage[] = agentMessages.slice()let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYSdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 3c670232..303bea7a 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -14,6 +14,7 @@ import { retrieveContext } from "../api/rag"import { buildRagSuffix, RETRIEVAL_FAILED_MESSAGE } from "../lib/rag-prompt"import { getModelMaxTokens, capMessageCount } from "../lib/context-compaction"import { applyChatSendBudget, chatBudgetApplies } from "../lib/chat-send-budget"+import { sendsToALanBackend } from "../lib/lan-openai-slot"import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS } from "../lib/too-many-messages"import { getModelContextCached } from "../api/ollama"import { requestGenerationCancel } from "../api/vram-handoff"@@ -121,6 +122,7 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],: 0,sendWindowTokens: settings.codexSendWindowTokens,contextDecay: settings.contextDecay,+ localBackend: sendsToALanBackend(providerId),},).messagesdiff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 746092ef..235b66f0 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -76,6 +76,7 @@ import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS }import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'import { buildRequestMessages, trimWorkingHistory, decayRestoredToolResult, isToolResult } from '../lib/context-decay'import { effectiveSendWindow } from '../lib/send-window'+import { sendsToALanBackend } from '../lib/lan-openai-slot'import { useSendSizeStore } from '../stores/sendSizeStore'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'import { platformPromptLine, hostClockLine } from '../lib/host-platform'@@ -1121,6 +1122,7 @@ export function useCodex() {sendWindowTokens: settings.codexSendWindowTokens,capEnabled: decayOn,smallModelMode: settings.smallModelMode,+ localBackend: sendsToALanBackend(providerId),})let sendMessages: ChatMessage[] = messages.slice()let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYSdiff --git a/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts b/src/lib/__tests__/a-lan-server-is-not-a-bill.test.tsnew file mode 100644index 00000000..84b3f66b--- /dev/null+++ b/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts@@ -0,0 +1,176 @@+/**+ * 3.0.0 leftover, found 2026-09-11: the compaction budget still called a+ * self-hosted LAN server a paid provider.+ *+ * GH #129 taught `useActiveContextWindow` that the `openai` slot can hold a+ * llama.cpp on this machine as easily as api.openai.com, and gave that case+ * `sendWindow = contextWindow`. The budget path next to it never learned it:+ * `PAID_PROVIDER_IDS` has `openai` in it, so `effectiveSendWindow` clamped the+ * reporter's 262144-token local model to 64000 and compacted a history that+ * nobody was ever going to be billed for.+ *+ * The two now ask ONE question (lib/lan-openai-slot), the same one the context+ * fix asks: the slot's own isLocal flag, or a private/loopback host.+ *+ * Run: npx vitest run src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { readFileSync } from 'fs'+import { resolve } from 'path'++vi.mock('../../api/backend', () => ({+ // The real rule, reimplemented nowhere: the classifier calls this and the+ // test needs it to answer for the hosts below.+ isPrivateOrLanHost: (host: string) =>+ /^(127\.|localhost$|\[?::1\]?$|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host),+ hostnameOf: (url: string) => { try { return new URL(url).hostname } catch { return '' } },+ isTauri: () => false,+}))++const { useProviderStore } = await import('../../stores/providerStore')+const { effectiveSendWindow, isPaidProvider, DEFAULT_SEND_WINDOW_TOKENS, WINDOW_SHARE } =+ await import('../send-window')+const { isLanOpenAiBackend, sendsToALanBackend } = await import('../lan-openai-slot')+const { chatSendBudget } = await import('../chat-send-budget')++const LOCAL_MODEL_WINDOW = 262144++/** Point the shared `openai` slot at one base URL, with an explicit isLocal. */+function slotPointsAt(baseUrl: string, isLocal: boolean) {+ const providers = useProviderStore.getState().providers+ useProviderStore.setState({+ providers: {+ ...providers,+ openai: { ...providers.openai, baseUrl, isLocal, enabled: true, managed: false },+ },+ })+}++beforeEach(() => { slotPointsAt('https://api.openai.com/v1', false) })++describe('the one classification', () => {+ it('calls a loopback server local even when the flag says nothing', () => {+ slotPointsAt('http://127.0.0.1:8080/v1', false)+ expect(isLanOpenAiBackend()).toBe(true)+ })++ it('calls a LAN address local', () => {+ slotPointsAt('http://192.168.0.54:8000/v1', false)+ expect(isLanOpenAiBackend()).toBe(true)+ })++ it('believes the slot flag for a host it cannot judge', () => {+ slotPointsAt('http://my-workstation.lan:8080/v1', true)+ expect(isLanOpenAiBackend()).toBe(true)+ })++ it('does not call api.openai.com local', () => {+ expect(isLanOpenAiBackend()).toBe(false)+ })++ // The answer must never be given without the provider id: a llama.cpp in the+ // openai slot does not make a send to LU Cloud free.+ it('never lets a LAN openai slot speak for another provider', () => {+ slotPointsAt('http://127.0.0.1:8080/v1', true)+ expect(sendsToALanBackend('openai')).toBe(true)+ expect(sendsToALanBackend('lu-cloud')).toBe(false)+ expect(sendsToALanBackend('anthropic')).toBe(false)+ })+})++describe('the budget follows it', () => {+ it('gives a LAN custom backend its whole local budget', () => {+ slotPointsAt('http://127.0.0.1:8080/v1', false)+ const budget = effectiveSendWindow({+ providerId: 'openai',+ modelWindow: LOCAL_MODEL_WINDOW,+ localBackend: sendsToALanBackend('openai'),+ })+ expect(budget).toBe(Math.floor(LOCAL_MODEL_WINDOW * WINDOW_SHARE))+ expect(budget).toBeGreaterThan(DEFAULT_SEND_WINDOW_TOKENS)+ })++ it('counter-check: the same slot pointed at a paid remote keeps the clamp', () => {+ const budget = effectiveSendWindow({+ providerId: 'openai',+ modelWindow: LOCAL_MODEL_WINDOW,+ localBackend: sendsToALanBackend('openai'),+ })+ expect(budget).toBe(DEFAULT_SEND_WINDOW_TOKENS)+ })++ it('leaves a real paid provider clamped even while a LAN slot is configured', () => {+ slotPointsAt('http://127.0.0.1:8080/v1', true)+ expect(+ effectiveSendWindow({+ providerId: 'lu-cloud',+ modelWindow: LOCAL_MODEL_WINDOW,+ localBackend: sendsToALanBackend('lu-cloud'),+ }),+ ).toBe(DEFAULT_SEND_WINDOW_TOKENS)+ })++ it('says so in the cost question itself', () => {+ expect(isPaidProvider('openai')).toBe(true)+ expect(isPaidProvider('openai', true)).toBe(false)+ expect(isPaidProvider('lu-cloud', true)).toBe(false)+ // Nothing passed is the pre-3.0.0 answer, so no caller that was never+ // touched can change behaviour by accident.+ expect(isPaidProvider('openai', undefined)).toBe(true)+ expect(isPaidProvider('ollama')).toBe(false)+ })++ it('carries through the chat surfaces too', () => {+ slotPointsAt('http://192.168.0.54:8000/v1', false)+ const local = chatSendBudget({+ providerId: 'openai',+ modelWindow: LOCAL_MODEL_WINDOW,+ localBackend: sendsToALanBackend('openai'),+ })+ expect(local).toBe(Math.floor(LOCAL_MODEL_WINDOW * WINDOW_SHARE))++ slotPointsAt('https://api.openai.com/v1', false)+ expect(+ chatSendBudget({+ providerId: 'openai',+ modelWindow: LOCAL_MODEL_WINDOW,+ localBackend: sendsToALanBackend('openai'),+ }),+ ).toBe(DEFAULT_SEND_WINDOW_TOKENS)+ })+})++/**+ * The flag is only as good as the call sites, and a budget that forgets it is+ * silently back to the bug. Reading the sources is the only way to catch the+ * next `effectiveSendWindow({ ... })` that goes in without it.+ */+describe('no budget is computed without asking the question', () => {+ const SITES = [+ 'src/hooks/useAgentChat.ts',+ 'src/hooks/useCodex.ts',+ 'src/hooks/useActiveContextWindow.ts',+ 'src/lib/run-compact-command.ts',+ 'src/lib/chat-send-budget.ts',+ ]++ it('every production call passes localBackend', () => {+ for (const site of SITES) {+ const src = readFileSync(resolve(process.cwd(), site), 'utf8')+ const calls = src.split('effectiveSendWindow({').slice(1)+ expect(calls.length, `${site} no longer computes a send window`).toBeGreaterThan(0)+ for (const call of calls) {+ const body = call.slice(0, call.indexOf('})'))+ expect(body, `${site} computes a send window without localBackend`).toContain('localBackend')+ }+ }+ })++ it('and both chat surfaces fill the field they were given', () => {+ for (const site of ['src/hooks/useChat.ts', 'src/hooks/useABCompare.ts']) {+ const src = readFileSync(resolve(process.cwd(), site), 'utf8')+ expect(src, `${site} builds a budget input without localBackend`)+ .toContain('localBackend: sendsToALanBackend(providerId)')+ }+ })+})diff --git a/src/lib/chat-send-budget.ts b/src/lib/chat-send-budget.tsindex 7f13537e..b8de0dec 100644--- a/src/lib/chat-send-budget.ts+++ b/src/lib/chat-send-budget.ts@@ -36,6 +36,9 @@ export interface ChatSendBudgetInput {sendWindowTokens?: number/** settings.contextDecay. The notaus switches the whole cap off. */contextDecay?: boolean+ /** Whether this payload goes to a machine on this network. See+ * lib/lan-openai-slot; a LAN server in the `openai` slot is not a bill. */+ localBackend?: boolean}/**@@ -111,6 +114,7 @@ export function chatSendBudget(input: ChatSendBudgetInput): number | null {modelWindow: input.modelWindow,sendWindowTokens: input.sendWindowTokens,capEnabled: true,+ localBackend: input.localBackend,})return window > 0 ? window : null}diff --git a/src/lib/lan-openai-slot.ts b/src/lib/lan-openai-slot.tsnew file mode 100644index 00000000..52ac0091--- /dev/null+++ b/src/lib/lan-openai-slot.ts@@ -0,0 +1,50 @@+/**+ * Wo der `openai`-Steckplatz wirklich hinzeigt.+ *+ * `ProviderId` ist eine feste Menge von vier Steckplaetzen, und JEDES+ * OpenAI-kompatible Backend teilt sich denselben: api.openai.com, ein+ * llama.cpp auf 127.0.0.1:8080, ein vLLM im LAN, LM Studio, der eingebaute+ * Motor dieses Hauses. Der Name `openai` sagt also nur, welches Protokoll+ * gesprochen wird, und nichts darueber, wer die Rechnung schickt.+ *+ * Zwei Stellen mussten das schon wissen, und bis zum 11.09.2026 wusste es nur+ * eine: `useActiveContextWindow` (GH #129) hat die Frage gestellt, damit ein+ * eigener Server einen Fensterwaehler bekommt und nicht den bezahlten+ * Sendedeckel. Der Kompaktierungsweg daneben hat sie nicht gestellt und den+ * Steckplatz weiter an einer Liste gemessen, in der `openai` als bezahlt+ * steht. Beide fragen jetzt hier.+ */++import { isPrivateOrLanHost, hostnameOf } from '../api/backend'+import { useProviderStore } from '../stores/providerStore'++/**+ * Laeuft der eingestellte OpenAI-Slot auf diesem Rechner oder im LAN?+ *+ * Dieselbe Frage, die `isLanBackend` im Provider stellt, und bewusst dieselbe+ * Antwortquelle: die Voreinstellung des Slots ODER der Hostname. Ein fremder+ * Host im Internet bekommt weder Metadaten-Abfragen noch einen Fensterwaehler.+ */+export function isLanOpenAiBackend(): boolean {+ try {+ const cfg = useProviderStore.getState().providers.openai+ if (!cfg) return false+ return cfg.isLocal === true || isPrivateOrLanHost(hostnameOf(cfg.baseUrl))+ } catch {+ return false+ }+}++/**+ * Geht eine Sendung an diesem Modell an eine Maschine, fuer die niemand+ * bezahlt?+ *+ * Nur fuer den `openai`-Steckplatz eine echte Frage. `ollama` und `lmstudio`+ * sind ohnehin lokal und stehen gar nicht erst auf der Bezahlliste, `lu-cloud`+ * und `anthropic` sind immer fern. Die Antwort darf NICHT ohne den+ * Anbieternamen gegeben werden: ein eigener Server im `openai`-Steckplatz+ * macht eine Sendung an LU Cloud nicht kostenlos.+ */+export function sendsToALanBackend(providerId: string): boolean {+ return providerId === 'openai' && isLanOpenAiBackend()+}diff --git a/src/lib/run-compact-command.ts b/src/lib/run-compact-command.tsindex cdb4bd4a..44fb6509 100644--- a/src/lib/run-compact-command.ts+++ b/src/lib/run-compact-command.ts@@ -39,6 +39,7 @@ import { estimateTokens } from './context-compaction'import { computeContextFill, type FillMessage } from './token-usage'import { shouldAutoCompact, MIN_MESSAGES_SINCE_COMPACT } from './compact-trigger'import { effectiveSendWindow } from './send-window'+import { sendsToALanBackend } from './lan-openai-slot'import { useSendSizeStore } from '../stores/sendSizeStore'import type { CompactionRecord, Message } from '../types/chat'import { formatCount } from './formatters'@@ -311,12 +312,14 @@ export async function maybeAutoCompact(opts: {// mit `modelWindowTokens`), hat seinen Nenner schon gewaehlt, und die// Nutzlast des einfachen Chats kennt diese Kappe nicht.const st = useSettingsStore.getState().settings+ const anbieter = getProviderIdFromModel(opts.activeModel)const gekappt = effectiveSendWindow({- providerId: getProviderIdFromModel(opts.activeModel),+ providerId: anbieter,modelWindow: window,sendWindowTokens: st.codexSendWindowTokens,capEnabled: st.contextDecay !== false,smallModelMode: st.smallModelMode,+ localBackend: sendsToALanBackend(anbieter),})if (gekappt > 0) window = gekappt}diff --git a/src/lib/send-window.ts b/src/lib/send-window.tsindex 510816e2..96b8c451 100644--- a/src/lib/send-window.ts+++ b/src/lib/send-window.ts@@ -23,7 +23,19 @@* loop).*/-/** Providers where a token sent is a token billed. */+/**+ * Providers where a token sent is a token billed.+ *+ * `openai` is on this list because that is the slot api.openai.com sits in. It+ * is also the slot a llama.cpp on 127.0.0.1:8080, a vLLM in the LAN, LM Studio+ * and this app's own engine sit in, because `ProviderId` is a fixed set of+ * four and every OpenAI-protocol backend shares one of them. So the id alone+ * cannot answer the cost question for this entry, and `localBackend` is what+ * finishes it: where the send goes to a machine on this network, nobody is+ * billed and there is nothing to cap. The classification itself is NOT+ * repeated here as a second list; it lives in lib/lan-openai-slot.ts, which is+ * the same answer the context window uses (GH #129).+ */export const PAID_PROVIDER_IDS: ReadonlySet<string> = new Set(['lu-cloud', 'openai', 'anthropic'])/** Default ceiling for one sent step, in tokens. Power users may raise it. */@@ -47,9 +59,18 @@ export interface SendWindowInput {capEnabled?: boolean/** settings.smallModelMode. */smallModelMode?: boolean+ /**+ * The send goes to a server on this machine or in the LAN+ * (`sendsToALanBackend` in lib/lan-openai-slot). Only the `openai` slot can+ * be either; left out, the provider id decides alone, which is what every+ * caller did before 3.0.0.+ */+ localBackend?: boolean}-export function isPaidProvider(providerId: string): boolean {+export function isPaidProvider(providerId: string, localBackend?: boolean): boolean {+ // A server in the next room bills nobody, whichever protocol it speaks.+ if (localBackend === true) return falsereturn PAID_PROVIDER_IDS.has(providerId)}@@ -63,7 +84,7 @@ export function effectiveSendWindow(input: SendWindowInput): number {? Math.floor(Math.min(window * SMALL_MODEL_SHARE, SMALL_MODEL_CEILING)): Math.floor(window * WINDOW_SHARE)if (input.capEnabled === false) return base- if (!isPaidProvider(input.providerId)) return base+ if (!isPaidProvider(input.providerId, input.localBackend)) return baseconst cap =typeof input.sendWindowTokens === 'number' && input.sendWindowTokens > 0? Math.floor(input.sendWindowTokens)