Skip to content

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.

feat(cost): a paid step sends at most the send window, and the meter says so

Davidc489fcc77cab
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
index 26c9b6e8..4b54aa99 100644
--- a/src/components/chat/TokenCounter.tsx
+++ b/src/components/chat/TokenCounter.tsx
@@ -1,10 +1,14 @@
import { useChatStore } from '../../stores/chatStore'
import { computeContextFill } from '../../lib/token-usage'
import { useActiveContextWindow } from '../../hooks/useActiveContextWindow'
+import { useSendSizeStore } from '../../stores/sendSizeStore'
export function TokenCounter() {
const activeConversationId = useChatStore((s) => s.activeConversationId)
const conversations = useChatStore((s) => s.conversations)
+ // What the agent loops last actually built and sent for this conversation
+ // (2.6.6, plan A2). Undefined on a plain chat, where the estimate stands.
+ const sent = useSendSizeStore((s) => (activeConversationId ? s.byConv[activeConversationId] : undefined))
// The denominator is the REAL context window the active model runs with —
// provider-aware and shared with the Context dropdown so the two never drift
@@ -23,14 +27,23 @@ export function TokenCounter() {
// forever after one looping cloud reasoner burned its whole 16,384-token
// completion budget, while the next real prompt cost 65 tokens (David,
// 2026-07-12). An honest dip after compaction beats a sticky wrong maximum.
- const fill = computeContextFill(messages)
+ const fill = computeContextFill(
+ messages,
+ sent ? { tokens: sent.tokens, atMessageCount: sent.atMessageCount } : undefined,
+ )
const rawUsed = fill.used
if (!activeConversationId || messages.length === 0) return null
// Resolved real context window; fall back to the VRAM-safe default only while
- // the provider probe is still in flight (ctx not resolved yet).
- const maxTokens = ctx.contextWindow > 0 ? ctx.contextWindow : 16384
+ // the provider probe is still in flight (ctx not resolved yet). On a paid
+ // provider the denominator is the SEND window, not the model window: a
+ // 262k-context model whose steps are capped at 64k would otherwise sit green
+ // at 25 percent forever, the red warning would never fire, and every support
+ // case would arrive with a healthy meter next to a drained wallet (plan A2,
+ // meter honesty).
+ const window = ctx.sendWindow > 0 ? ctx.sendWindow : ctx.contextWindow
+ const maxTokens = window > 0 ? window : 16384
// Cap the numerator at the active window: a long chat carried onto a
// smaller-context model shows "8.0k/8.0k" (full), not "20k/8k".
const usedTokens = Math.min(rawUsed, maxTokens)
@@ -50,9 +63,15 @@ export function TokenCounter() {
: ctx.provider === 'builtin'
? 'built-in engine loaded context'
: 'model context'
- const title = isReal
- ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), anchored on the model's last reported usage (includes system prompt + tools + RAG); reasoning tokens are not context and aren't counted`
- : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), estimate until the model reports real usage`
+ const capped = ctx.sendWindow > 0 && ctx.contextWindow > ctx.sendWindow
+ const capNote = capped
+ ? `. Capped: a step sends at most ${maxTokens.toLocaleString()} of this model's ${ctx.contextWindow.toLocaleString()} tokens (Settings, send window), and tool results older than the newest step go out shortened`
+ : ''
+ const title = fill.source === 'built'
+ ? `Last request: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens, the size of the payload actually built for the last step, decay and compaction included${capNote}`
+ : isReal
+ ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), anchored on the model's last reported usage (includes system prompt + tools + RAG); reasoning tokens are not context and aren't counted${capNote}`
+ : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), estimate until the model reports real usage${capNote}`
return (
<div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={title}>
diff --git a/src/hooks/useActiveContextWindow.ts b/src/hooks/useActiveContextWindow.ts
index 0fe42e0f..da1abe7b 100644
--- a/src/hooks/useActiveContextWindow.ts
+++ b/src/hooks/useActiveContextWindow.ts
@@ -6,6 +6,7 @@ import { getModelContextCached } from '../api/ollama'
import { getLmStudioModelContext } from '../api/lmstudio'
import { getModelMaxTokens } from '../lib/context-compaction'
import { effectiveContextWindow } from '../lib/context-window'
+import { effectiveSendWindow } from '../lib/send-window'
import { isManagedBuiltinSlot } from '../api/builtin-ensure'
import { bundledEngineStatus, bundledCtxTrain } from '../api/engine'
@@ -19,6 +20,13 @@ export interface ActiveContext {
contextWindow: number
/** The model's ceiling, used to cap the dropdown presets (0 = unknown). */
modelMax: number
+ /**
+ * The window one request may actually SEND (2.6.6, plan A2). Equal to
+ * contextWindow on local backends; on a paid provider it is the send cap,
+ * which is the only honest denominator for the token counter. A 262k model
+ * whose steps are capped at 64k is not "25 percent full", it is full.
+ */
+ sendWindow: number
/** True when the value is the model's real, confirmed live context (Ollama
* num_ctx, or LM Studio's loaded_context_length) rather than a fallback. */
isTrue: boolean
@@ -40,8 +48,10 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
const activeModel = useModelStore((s) => s.activeModel)
const override = useSettingsStore((s) => s.settings.contextWindowOverride)
const builtinCtx = useSettingsStore((s) => s.settings.builtinEngine.ctx)
+ const sendWindowTokens = useSettingsStore((s) => s.settings.codexSendWindowTokens)
+ const capEnabled = useSettingsStore((s) => s.settings.contextDecay)
const [state, setState] = useState<ActiveContext>({
- provider: 'unknown', contextWindow: 0, modelMax: 0, isTrue: false, adjustable: false,
+ provider: 'unknown', contextWindow: 0, modelMax: 0, sendWindow: 0, isTrue: false, adjustable: false,
})
// Re-read whenever a model reload finishes anywhere (the Context dropdown
@@ -56,7 +66,7 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
useEffect(() => {
if (!activeModel) {
- setState({ provider: 'unknown', contextWindow: 0, modelMax: 0, isTrue: false, adjustable: false })
+ setState({ provider: 'unknown', contextWindow: 0, modelMax: 0, sendWindow: 0, isTrue: false, adjustable: false })
return
}
let cancelled = false
@@ -67,10 +77,13 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
if (providerId === 'ollama') {
const max = await getModelContextCached(activeModel).catch(() => 0)
if (cancelled) return
+ const ollamaCtx = effectiveContextWindow(max, override)
setState({
provider: 'ollama',
- contextWindow: effectiveContextWindow(max, override),
+ contextWindow: ollamaCtx,
modelMax: max,
+ // Local backend: nothing is billed, so the send window IS the window.
+ sendWindow: ollamaCtx,
isTrue: true,
adjustable: true,
})
@@ -94,16 +107,19 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
provider: 'builtin',
contextWindow: status.ctx,
modelMax,
+ sendWindow: status.ctx,
isTrue: true,
adjustable: true,
})
} else {
// Managed but not up (offloaded / before first send): the next
// start uses the tuning value, so that IS the honest prediction.
+ const nextCtx = builtinCtx > 0 ? builtinCtx : 8192
setState({
provider: 'builtin',
- contextWindow: builtinCtx > 0 ? builtinCtx : 8192,
+ contextWindow: nextCtx,
modelMax,
+ sendWindow: nextCtx,
isTrue: false,
adjustable: true,
})
@@ -120,12 +136,14 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
if (info.loaded || info.max) {
const loaded = info.loaded ?? 0
const max = info.max ?? loaded
+ const lmCtx = loaded > 0
+ ? loaded // TRUE: what LM Studio actually loaded
+ : (override > 0 ? override : Math.min(max || 8192, 16384))
setState({
provider: 'lmstudio',
- contextWindow: loaded > 0
- ? loaded // TRUE: what LM Studio actually loaded
- : (override > 0 ? override : Math.min(max || 8192, 16384)),
+ contextWindow: lmCtx,
modelMax: max,
+ sendWindow: lmCtx,
isTrue: loaded > 0,
adjustable: true,
})
@@ -143,13 +161,21 @@ export function useActiveContextWindow(reloadTick = 0): ActiveContext {
provider: 'cloud',
contextWindow: max,
modelMax: max,
+ // Meter honesty (plan A2): a paid step never sends more than the cap,
+ // so the cap is what the counter divides by.
+ sendWindow: effectiveSendWindow({
+ providerId,
+ modelWindow: max,
+ sendWindowTokens,
+ capEnabled,
+ }),
isTrue: false,
adjustable: false,
})
})()
return () => { cancelled = true }
- }, [activeModel, override, builtinCtx, reloadTick, reloadBump])
+ }, [activeModel, override, builtinCtx, sendWindowTokens, capEnabled, reloadTick, reloadBump])
return state
}
diff --git a/src/lib/__tests__/send-window.test.ts b/src/lib/__tests__/send-window.test.ts
new file mode 100644
index 00000000..eb0f8e80
--- /dev/null
+++ b/src/lib/__tests__/send-window.test.ts
@@ -0,0 +1,139 @@
+/**
+ * A2: the cost ceiling for one sent step, and the meter that has to be honest
+ * about it (2.6.6 plan).
+ *
+ * Before this, a 262k-context cloud model let a coding step grow to 209k tokens
+ * and every step of a long run was billed at that size, while the token counter
+ * divided by 262k and sat green at 25 percent. Both halves are tested here: the
+ * budget itself, and the denominator the user sees.
+ */
+
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+import {
+ effectiveSendWindow,
+ isPaidProvider,
+ DEFAULT_SEND_WINDOW_TOKENS,
+} from '../send-window'
+import { computeContextFill } from '../token-usage'
+import { DEFAULT_SETTINGS } from '../constants'
+
+describe('A2: the paid-provider send cap', () => {
+ it('gives a 262k cloud model a 64k budget, not 209k', () => {
+ const budget = effectiveSendWindow({ providerId: 'lu-cloud', modelWindow: 262144 })
+ expect(budget).toBe(DEFAULT_SEND_WINDOW_TOKENS)
+ })
+
+ it('negative control: without the cap the same model gets 0.8 of its window', () => {
+ const budget = effectiveSendWindow({
+ providerId: 'lu-cloud',
+ modelWindow: 262144,
+ capEnabled: false,
+ })
+ expect(budget).toBe(Math.floor(262144 * 0.8))
+ expect(budget).toBeGreaterThan(200000)
+ })
+
+ it('never RAISES a small model to the cap', () => {
+ // 32k model: 0.8 x 32768 = 26214, well under 64k, so the cap does nothing.
+ expect(effectiveSendWindow({ providerId: 'lu-cloud', modelWindow: 32768 }))
+ .toBe(Math.floor(32768 * 0.8))
+ })
+
+ it('leaves a local Ollama model exactly where it was', () => {
+ for (const window of [8192, 32768, 262144]) {
+ expect(effectiveSendWindow({ providerId: 'ollama', modelWindow: window }))
+ .toBe(Math.floor(window * 0.8))
+ }
+ })
+
+ it('applies to every provider that bills, and to no other', () => {
+ expect(isPaidProvider('lu-cloud')).toBe(true)
+ expect(isPaidProvider('openai')).toBe(true)
+ expect(isPaidProvider('anthropic')).toBe(true)
+ expect(isPaidProvider('ollama')).toBe(false)
+ })
+
+ it('lets a power user raise the ceiling', () => {
+ expect(effectiveSendWindow({
+ providerId: 'lu-cloud',
+ modelWindow: 262144,
+ sendWindowTokens: 120000,
+ })).toBe(120000)
+ })
+
+ it('keeps Small-Model Mode tighter than the cap', () => {
+ expect(effectiveSendWindow({
+ providerId: 'lu-cloud',
+ modelWindow: 262144,
+ smallModelMode: true,
+ })).toBe(6000)
+ })
+
+ it('survives a model whose window is unknown', () => {
+ expect(effectiveSendWindow({ providerId: 'lu-cloud', modelWindow: 0 })).toBe(0)
+ })
+})
+
+describe('A2: the shipped defaults', () => {
+ it('ships the cap at 64k and the decay switch on', () => {
+ expect(DEFAULT_SETTINGS.codexSendWindowTokens).toBe(64000)
+ expect(DEFAULT_SETTINGS.contextDecay).toBe(true)
+ })
+})
+
+describe('A2 meter honesty: the numerator is what was actually built', () => {
+ const msgs = [
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: 'hi', usage: { promptTokens: 20, completionTokens: 2, totalTokens: 22 } },
+ ]
+
+ it('uses the built-request size over the usage anchor', () => {
+ const fill = computeContextFill(msgs, { tokens: 58000, atMessageCount: 2 })
+ expect(fill.source).toBe('built')
+ expect(fill.used).toBe(58000)
+ })
+
+ it('adds messages that arrived after the request was built', () => {
+ const later = [...msgs, { role: 'user', content: 'a'.repeat(400) }]
+ const fill = computeContextFill(later, { tokens: 58000, atMessageCount: 2 })
+ expect(fill.used).toBeGreaterThan(58000)
+ expect(fill.used).toBeLessThan(58200)
+ })
+
+ it('falls back to the usage anchor when nothing was built yet', () => {
+ expect(computeContextFill(msgs).source).toBe('usage')
+ })
+
+ it('ignores a stale report that names more messages than exist', () => {
+ const fill = computeContextFill(msgs, { tokens: 58000, atMessageCount: 99 })
+ expect(fill.source).toBe('usage')
+ })
+})
+
+describe('A2: the counter divides by the send window', () => {
+ const src = readFileSync(
+ resolve(__dirname, '..', '..', 'components', 'chat', 'TokenCounter.tsx'),
+ 'utf8',
+ )
+
+ // There is no render harness in this repo, so the wiring is guarded at the
+ // source, the way host-platform.test.ts guards the prompt.
+ it('takes its denominator from ctx.sendWindow, not ctx.contextWindow', () => {
+ expect(src).toMatch(
+ /const window = ctx\.sendWindow > 0 \? ctx\.sendWindow : ctx\.contextWindow/,
+ )
+ expect(src).toMatch(/const maxTokens = window > 0 \? window : 16384/)
+ })
+
+ it('feeds the built-request size in as the numerator', () => {
+ expect(src).toMatch(/useSendSizeStore/)
+ expect(src).toMatch(/atMessageCount: sent\.atMessageCount/)
+ })
+
+ it('explains the cap and the decay in the tooltip', () => {
+ expect(src).toMatch(/a step sends at most/)
+ expect(src).toMatch(/older than the newest step go out shortened/)
+ })
+})
diff --git a/src/lib/__tests__/token-usage.test.ts b/src/lib/__tests__/token-usage.test.ts
index c18ef389..f4a6d438 100644
--- a/src/lib/__tests__/token-usage.test.ts
+++ b/src/lib/__tests__/token-usage.test.ts
@@ -19,7 +19,7 @@ describe('computeContextFill', () => {
it('estimates from visible content only when no usage exists', () => {
const msgs = [user('hello there'), assistant('hi!')]
const expected = estimateTokens('hello there') + 4 + estimateTokens('hi!') + 4
- expect(computeContextFill(msgs)).toEqual({ used: expected, real: false })
+ expect(computeContextFill(msgs)).toEqual({ used: expected, real: false, source: 'estimate' })
})
it('never counts thinking — with or without a usage anchor', () => {
@@ -52,7 +52,7 @@ describe('computeContextFill', () => {
const tail =
estimateTokens('a2') + 4 +
estimateTokens('third — not answered yet') + 4
- expect(computeContextFill(msgs)).toEqual({ used: 900 + tail, real: true })
+ expect(computeContextFill(msgs)).toEqual({ used: 900 + tail, real: true , source: 'usage' })
})
it('a provisional (estimated) anchor is used but not reported as real', () => {
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index f1c45448..5bf5833b 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -48,6 +48,10 @@ export const DEFAULT_SETTINGS: Settings = {
// Bug AA v2.5.0 — Ollama num_ctx override. 0 = use Ollama default (2048
// on most builds). Users with RAG / long chats can bump this up.
contextWindowOverride: 0,
+ // 2.6.6 plan A1/A2: age decay and the paid-provider send cap. ON by
+ // default; the switch is the support way back without a rollback release.
+ contextDecay: true,
+ codexSendWindowTokens: 64000,
builtinEngine: {
ctx: 8192,
flashAttn: 'auto',
diff --git a/src/lib/send-window.ts b/src/lib/send-window.ts
new file mode 100644
index 00000000..d34eeb11
--- /dev/null
+++ b/src/lib/send-window.ts
@@ -0,0 +1,64 @@
+/**
+ * The window an agent step is allowed to SEND (2.6.6, plan A2).
+ *
+ * A 262k-context cloud model let the coding loop grow its prompt to whatever
+ * the history happened to be: the compaction budget was 0.8 × the model
+ * window, so nothing trimmed until 209k tokens, and every step of a long run
+ * was billed at that size. The model window is what the model can read; it was
+ * never a statement about what a step is worth paying for.
+ *
+ * So paid providers get a second, tighter ceiling: min(0.8 × model window,
+ * codexSendWindowTokens), default 64k. Local backends keep exactly the
+ * behaviour they had, because there is no bill on the other end and their
+ * windows are small to begin with. num_ctx is untouched either way, so no
+ * model is ever asked to run in a smaller allocation than before (that would
+ * only trade money for a trim loop).
+ */
+
+/** Providers where a token sent is a token billed. */
+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. */
+export const DEFAULT_SEND_WINDOW_TOKENS = 64000
+
+/** The share of the model window a step was already limited to before 2.6.6. */
+export const WINDOW_SHARE = 0.8
+
+/** Small-Model Mode keeps its own, much tighter profile (Knob 4). */
+export const SMALL_MODEL_SHARE = 0.5
+export const SMALL_MODEL_CEILING = 6000
+
+export interface SendWindowInput {
+ /** Provider id of the active model ('lu-cloud', 'ollama', …). */
+ providerId: string
+ /** The context window the loop resolved for this model (num_ctx). */
+ modelWindow: number
+ /** settings.codexSendWindowTokens. */
+ sendWindowTokens?: number
+ /** settings.contextDecay. The notaus switches the cap off with the decay. */
+ capEnabled?: boolean
+ /** settings.smallModelMode. */
+ smallModelMode?: boolean
+}
+
+export function isPaidProvider(providerId: string): boolean {
+ return PAID_PROVIDER_IDS.has(providerId)
+}
+
+/**
+ * The compaction budget for one step. Identical to the pre-2.6.6 number
+ * everywhere the cap does not apply, so a local run cannot change behaviour.
+ */
+export function effectiveSendWindow(input: SendWindowInput): number {
+ const window = Number.isFinite(input.modelWindow) && input.modelWindow > 0 ? input.modelWindow : 0
+ const base = input.smallModelMode
+ ? 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
+ const cap =
+ typeof input.sendWindowTokens === 'number' && input.sendWindowTokens > 0
+ ? Math.floor(input.sendWindowTokens)
+ : DEFAULT_SEND_WINDOW_TOKENS
+ return Math.min(base, cap)
+}
diff --git a/src/lib/token-usage.ts b/src/lib/token-usage.ts
index 1ea2921d..753b1cec 100644
--- a/src/lib/token-usage.ts
+++ b/src/lib/token-usage.ts
@@ -40,6 +40,20 @@ export interface ContextFill {
used: number
/** True when `used` is anchored on a non-estimated, model-reported usage. */
real: boolean
+ /** Where the number came from, so the tooltip can say so. */
+ source: 'built' | 'usage' | 'estimate'
+}
+
+/**
+ * The size of the request the builder last built for this conversation
+ * (2.6.6, plan A2). It beats every other anchor because it is not a guess
+ * about what will be sent: it IS what was sent, decay, plan pruning,
+ * compaction and all. Messages added since are counted on top.
+ */
+export interface BuiltRequestAnchor {
+ tokens: number
+ /** Messages in the conversation at build time. */
+ atMessageCount: number
}
/** Visible size of one message in a future prompt (content only, no thinking). */
@@ -49,7 +63,21 @@ function visibleTokens(m: FillMessage): number {
return t + 4 // role overhead
}
-export function computeContextFill(messages: FillMessage[]): ContextFill {
+export function computeContextFill(
+ messages: FillMessage[],
+ built?: BuiltRequestAnchor,
+): ContextFill {
+ // A real built request wins: it already contains the system prompt, the tool
+ // catalogue, the decayed results and whatever compaction dropped, none of
+ // which the visible conversation can show.
+ if (built && built.tokens > 0 && built.atMessageCount <= messages.length) {
+ let used = built.tokens
+ for (let i = built.atMessageCount; i < messages.length; i++) {
+ used += visibleTokens(messages[i])
+ }
+ return { used, real: false, source: 'built' }
+ }
+
// Newest message carrying usage (assistant turns store it when the model
// reports real counts; the agent path stores a provisional estimated one).
let anchorIdx = -1
@@ -60,7 +88,11 @@ export function computeContextFill(messages: FillMessage[]): ContextFill {
if (anchorIdx === -1) {
// No usage anywhere yet — plain estimate over the visible conversation.
- return { used: messages.reduce((sum, m) => sum + visibleTokens(m), 0), real: false }
+ return {
+ used: messages.reduce((sum, m) => sum + visibleTokens(m), 0),
+ real: false,
+ source: 'estimate',
+ }
}
const anchor = messages[anchorIdx].usage!
@@ -70,5 +102,5 @@ export function computeContextFill(messages: FillMessage[]): ContextFill {
for (let i = anchorIdx; i < messages.length; i++) {
used += visibleTokens(messages[i])
}
- return { used, real: !anchor.estimated }
+ return { used, real: !anchor.estimated, source: 'usage' }
}
diff --git a/src/stores/sendSizeStore.ts b/src/stores/sendSizeStore.ts
new file mode 100644
index 00000000..85653611
--- /dev/null
+++ b/src/stores/sendSizeStore.ts
@@ -0,0 +1,49 @@
+import { create } from 'zustand'
+
+/**
+ * What the last request of a conversation actually WEIGHED (2.6.6, plan A2,
+ * meter honesty).
+ *
+ * The token counter used to divide an estimate of the visible conversation by
+ * the model's full context window. On a 262k-context cloud model that reads
+ * green at 25 percent forever: the red warning never fires, and a support case
+ * arrives with a screenshot of a healthy meter next to a drained wallet. With
+ * the send cap in place the honest denominator is the window a step may send,
+ * and the honest numerator is the size of the request the builder just built.
+ *
+ * Ephemeral on purpose. It describes the run in front of the user, not a fact
+ * worth carrying across a restart.
+ */
+export interface SendSizeReport {
+ /** Estimated tokens of the request as it went out. */
+ tokens: number
+ /** The effective send window it was built against. */
+ window: number
+ /** Messages in the conversation when the request was built. */
+ atMessageCount: number
+ /** Results the age decay sent capped on this step. */
+ trimmedResults: number
+ /** Characters the capping saved on this step. */
+ savedChars: number
+}
+
+interface SendSizeState {
+ byConv: Record<string, SendSizeReport>
+ report: (convId: string, size: SendSizeReport) => void
+ get: (convId: string) => SendSizeReport | undefined
+ clear: (convId: string) => void
+}
+
+export const useSendSizeStore = create<SendSizeState>((set, get) => ({
+ byConv: {},
+ report: (convId, size) =>
+ set((state) => ({ byConv: { ...state.byConv, [convId]: size } })),
+ get: (convId) => get().byConv[convId],
+ clear: (convId) =>
+ set((state) => {
+ if (!(convId in state.byConv)) return state
+ const next = { ...state.byConv }
+ delete next[convId]
+ return { byConv: next }
+ }),
+}))
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index d591b72e..b893e601 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -59,7 +59,17 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'
// 'cloud' with no real choice, so reset them to the local default ONCE so they
// land in the now-built local mode; the visible switch flips back anytime.
// Windows/Linux appMode reflects a real user choice and is never touched.
-const STORE_VERSION = 19
+// v20 (2.6.6): added settings.contextDecay (default true) and
+// settings.codexSendWindowTokens (default 64000) for the tool-result age decay
+// and the paid-provider send cap. STRICTLY ADDITIVE and IDEMPOTENT: the merge
+// below fills both defaults in and preserves every existing value, and this
+// version adds NO one-shot reset the way v10 and v19 did.
+// That is a hard requirement, not a preference (plan R1, DOWNGRADE-KONTRAKT):
+// the 2.6.5/2.6.6 A/B share one WebView profile, zustand stamps the OLD
+// version back when the old build writes the store, so this migration runs
+// AGAIN on the next 2.6.6 start. A one-shot reset here would fire on every
+// build switch and quietly wipe a user preference each time.
+const STORE_VERSION = 20
interface SettingsState {
settings: Settings
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 76930815..2b0f46fb 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -110,6 +110,24 @@ export interface Settings {
// providers ignore this field — they manage context themselves.
/** User-side context-window override (forwarded as Ollama's num_ctx). 0 = auto. */
contextWindowOverride: number
+ /**
+ * Age decay for tool results plus the paid-provider send cap (2.6.6, plan
+ * A1/A2). ON is the shipped behaviour: results older than the newest
+ * iteration go out head+tail-capped and a step never sends more than
+ * codexSendWindowTokens on a paid provider.
+ *
+ * This is the support way back without a rollback release. If a run halts
+ * with "repeated with identical arguments", turning this off restores the
+ * 2.6.5 prompt exactly, at 2.6.5 prices.
+ */
+ contextDecay: boolean
+ /**
+ * Ceiling for one agent step on a paid provider, in tokens. The effective
+ * budget is min(0.8 × model window, this). The model's own context window
+ * and num_ctx are untouched, so raising it never breaks a model, it only
+ * costs more. Local backends ignore it.
+ */
+ codexSendWindowTokens: number
// Built-in engine expert tuning (2.6.0 Engine-Sweep). Forwarded to the Rust
// EngineTuning (whitelisted there) on every engine start/swap — Onboarding,
// Discover, model picker and the post-offload self-heal all inherit it via