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
feat(cost): a chat turn sends at most the send window, and old pictures stop riding along
Davidb8999f4fc8ed
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 292826c8..4880c251 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -18,6 +18,7 @@ import { ModelSelector } from '../models/ModelSelector'import { GoalBar } from './GoalBar'import { PlanBar } from './PlanBar'import { LoopBar } from './LoopBar'+import { GroupCostHint } from './GroupCostHint'import { MemoryDebugToggle } from './MemoryDebugPanel'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'@@ -339,7 +340,7 @@ export function ChatView() {slashCommands={isAgentActive}onAttachDocs={appMode !== 'cloud' ? () => setRagPanelOpen(true) : undefined}composerModel={<ModelSelector openUpward />}- composerAbove={<><LoopBar onStop={stopGeneration} /><GoalBar /><PlanBar /></>}+ composerAbove={<><LoopBar onStop={stopGeneration} /><GoalBar /><GroupCostHint /><PlanBar /></>}composerActions={<>{/* Documents (RAG) — local-embeddings only, so hide indiff --git a/src/components/chat/GroupCostHint.tsx b/src/components/chat/GroupCostHint.tsxnew file mode 100644index 00000000..48209376--- /dev/null+++ b/src/components/chat/GroupCostHint.tsx@@ -0,0 +1,46 @@+// What a group round costs, said out loud above the composer (2.6.6, plan A4).+//+// The group is the only surface where one Enter buys more than one answer, and+// nothing on screen said so: the user picks three models in the Plugins+// dropdown, types a question, and the app quietly bills three completions on+// the shared history. A per-model send budget takes the runaway growth out of+// it, but the multiplier itself is the feature, not a bug, so the honest fix is+// to name it where the user is about to press send.+//+// Only rendered when a line-up is actually active, and never in a single-model+// chat, where it would be noise.++import { Users } from 'lucide-react'+import { useChatStore } from '../../stores/chatStore'+import { isGroupChat } from '../../lib/group-chat'++/** The line itself. Kept pure so the wording is testable without a renderer. */+export function groupCostHintText(models: number): string {+ return `1 round = ${models} answers = ${models}x the cost`+}++export function GroupCostHint() {+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const groupModels = useChatStore((s) =>+ activeConversationId+ ? s.conversations.find((c) => c.id === activeConversationId)?.groupModels+ : undefined,+ )++ if (!isGroupChat(groupModels)) return null++ return (+ <div className="w-full max-w-[70%] mx-auto px-3 pb-1 flex justify-center">+ <div className="w-full flex items-center gap-1.5 px-2 py-1 rounded-md border border-amber-500/20 bg-amber-500/[0.04]">+ <Users size={9} className="text-amber-400 shrink-0" />+ <span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">group</span>+ <span+ className="flex-1 min-w-0 truncate text-[0.6rem] text-gray-700 dark:text-gray-300"+ title={groupModels.join(', ')}+ >+ {groupCostHintText(groupModels.length)}+ </span>+ </div>+ </div>+ )+}diff --git a/src/components/chat/__tests__/group-cost-hint.test.ts b/src/components/chat/__tests__/group-cost-hint.test.tsnew file mode 100644index 00000000..14e5224e--- /dev/null+++ b/src/components/chat/__tests__/group-cost-hint.test.ts@@ -0,0 +1,41 @@+/**+ * The group multiplier is said out loud (2.6.6, plan A4).+ *+ * One Enter in a group chat buys N answers on the shared history, and nothing+ * on screen used to say so. The wording is the whole feature, so it is pinned+ * here rather than left to a refactor.+ */++import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { resolve } from 'path'+import { groupCostHintText } from '../GroupCostHint'+import { GROUP_CHAT_MIN, GROUP_CHAT_MAX } from '../../../lib/group-chat'++describe('groupCostHintText', () => {+ it('names the round, the answers and the cost', () => {+ expect(groupCostHintText(3)).toBe('1 round = 3 answers = 3x the cost')+ })++ it('covers the whole supported line-up', () => {+ for (let n = GROUP_CHAT_MIN; n <= GROUP_CHAT_MAX; n++) {+ expect(groupCostHintText(n)).toBe(`1 round = ${n} answers = ${n}x the cost`)+ }+ })+})++describe('the hint only exists while a line-up is active', () => {+ const source = readFileSync(resolve(__dirname, '..', 'GroupCostHint.tsx'), 'utf8')++ it('renders nothing for a single-model chat', () => {+ // isGroupChat is false below GROUP_CHAT_MIN, so a normal chat gets no bar.+ expect(source).toMatch(/if \(!isGroupChat\(groupModels\)\) return null/)+ })++ it('negative control: it does not read a global model list', () => {+ // The line-up lives on the conversation. Reading the model store instead+ // would show the hint in every chat.+ expect(source).not.toMatch(/useModelStore/)+ expect(source).toMatch(/s\.conversations\.find/)+ })+})diff --git a/src/hooks/__tests__/chat-budget-wiring.test.ts b/src/hooks/__tests__/chat-budget-wiring.test.tsnew file mode 100644index 00000000..37744a28--- /dev/null+++ b/src/hooks/__tests__/chat-budget-wiring.test.ts@@ -0,0 +1,92 @@+/**+ * A4 wiring: the three conversation surfaces actually go through the budget,+ * and the two agent loops inherit the image rule without being touched.+ *+ * There is no render harness for these hooks in this repo, so the contract is+ * guarded at the source the way decay-wiring.test.ts guards A1/A2. These are+ * exactly the lines a well-meaning refactor undoes for free: sending+ * `chatMessages` instead of the budgeted copy leaves compare uncapped while+ * every unit test still passes, and resolving the budget from anything other+ * than the provider id would quietly put a ceiling on local backends.+ */++import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { resolve } from 'path'++const read = (...p: string[]) => readFileSync(resolve(__dirname, '..', ...p), 'utf8')+const chat = read('useChat.ts')+const compare = read('useABCompare.ts')+const decay = read('..', 'lib', 'context-decay.ts')+const codex = read('useCodex.ts')+const agent = read('useAgentChat.ts')++describe('plain chat sends under the A2 budget', () => {+ it('routes the built array through the budget', () => {+ expect(chat).toMatch(/applyChatSendBudget\(/)+ expect(chat).toMatch(/sendWindowTokens: settings\.codexSendWindowTokens/)+ })++ it('keeps the message-count cap as the second barrier', () => {+ expect(chat).toMatch(/capMessageCount\(\[/)+ })++ it('resolves the cap from the provider, so local backends stay uncapped', () => {+ expect(chat).toMatch(/providerId,\n\s+modelWindow:/)+ })++ it('honours the contextDecay notaus', () => {+ expect(chat).toMatch(/contextDecay: settings\.contextDecay/)+ })+})++describe('a group round is budgeted per model', () => {+ it('resolves the window for the model whose turn it is', () => {+ const groupTurn = chat.slice(+ chat.indexOf('async function runGroupTurn'),+ chat.indexOf('export function useChat'),+ )+ expect(groupTurn).toMatch(/applyChatSendBudget\(/)+ expect(groupTurn).toMatch(/modelWindow: await getModelMaxTokens\(model\)/)+ expect(groupTurn).toMatch(/capMessageCount\(\[/)+ expect(groupTurn).toMatch(/contextDecay: settings\.contextDecay/)+ })++ it('names the multiplier above the composer', () => {+ const view = read('..', 'components', 'chat', 'ChatView.tsx')+ expect(view).toMatch(/<GroupCostHint \/>/)+ })+})++describe('compare caps the shared base before the fan-out', () => {+ it('takes the tightest budget of the two sides', () => {+ expect(compare).toMatch(/sharedChatSendBudget\(/)+ expect(compare).toMatch(/applySendBudget\(chatMessages, budget\)/)+ })++ it('streams the budgeted array to BOTH sides, not the raw history', () => {+ expect(compare.match(/chatStream\(modelId, sendMessages,/g)).toHaveLength(2)+ expect(compare).not.toMatch(/chatStream\(modelId, chatMessages,/)+ })++ it('honours the contextDecay notaus', () => {+ expect(compare).toMatch(/contextDecay: settings\.contextDecay/)+ })+})++describe('the agent and coding loops get the image rule for free', () => {+ it('the rule lives in the shared builder, not in the hooks', () => {+ expect(decay).toMatch(/ageOutImages\(/)+ expect(codex).not.toMatch(/ageOutImages\(/)+ expect(agent).not.toMatch(/ageOutImages\(/)+ })++ it('both loops still build their request through it', () => {+ expect(codex).toMatch(/buildRequestMessages\(/)+ expect(agent).toMatch(/buildRequestMessages\(/)+ })++ it('the rule is behind the same notaus as the decay', () => {+ expect(decay).toMatch(/opts\.enabled !== false && opts\.ageImages !== false/)+ })+})diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.tsindex e4052de0..084b440e 100644--- a/src/hooks/useABCompare.ts+++ b/src/hooks/useABCompare.ts@@ -5,7 +5,9 @@import { useCallback, useRef } from 'react'import { useCompareStore } from '../stores/compareStore'import { useSettingsStore } from '../stores/settingsStore'-import { getProviderForModel } from '../api/providers'+import { getProviderForModel, getProviderIdFromModel } from '../api/providers'+import { getModelMaxTokens } from '../lib/context-compaction'+import { applySendBudget, sharedChatSendBudget } from '../lib/chat-send-budget'import { v4 as uuid } from 'uuid'import type { ChatMessage } from '../api/providers/types'import type { Message } from '../types/chat'@@ -42,6 +44,25 @@ export function useABCompare() {chatMessages.push({ role: m.role as 'user' | 'assistant', content: m.content })}+ // Send budget on the SHARED base, before the fan-out (plan A4). Compare was+ // the only surface with no cap of any kind: it sent the full history to two+ // models on every round, so a long comparison billed history level twice+ // per question and grew without end. Capping the shared array rather than+ // each side keeps the comparison honest, since two models that were handed+ // different prompts are not being compared at all. A mixed pairing takes+ // the paid side's budget for both; two local models are untouched.+ const budget = sharedChatSendBudget(+ await Promise.all(+ [modelA, modelB].map(async (m) => ({+ providerId: getProviderIdFromModel(m),+ modelWindow: await getModelMaxTokens(m),+ sendWindowTokens: settings.codexSendWindowTokens,+ contextDecay: settings.contextDecay,+ })),+ ),+ )+ const sendMessages = applySendBudget(chatMessages, budget).messages+const opts = {temperature: settings.temperature,topP: settings.topP,@@ -59,7 +80,7 @@ export function useABCompare() {let tokenCount = 0try {const { provider, modelId } = getProviderForModel(modelA)- const stream = provider.chatStream(modelId, chatMessages, { ...opts, signal: abortA.current!.signal })+ const stream = provider.chatStream(modelId, sendMessages, { ...opts, signal: abortA.current!.signal })for await (const chunk of stream) {if (chunk.content) {fullContent += chunk.content@@ -84,7 +105,7 @@ export function useABCompare() {let tokenCount = 0try {const { provider, modelId } = getProviderForModel(modelB)- const stream = provider.chatStream(modelId, chatMessages, { ...opts, signal: abortB.current!.signal })+ const stream = provider.chatStream(modelId, sendMessages, { ...opts, signal: abortB.current!.signal })for await (const chunk of stream) {if (chunk.content) {fullContent += chunk.contentdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex b3a129ef..8c2226da 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -9,6 +9,7 @@ import { useVoiceStore } from "../stores/voiceStore"import { autoSpeak } from "../lib/ttsBridge"import { retrieveContext } from "../api/rag"import { getModelMaxTokens, capMessageCount } from "../lib/context-compaction"+import { applyChatSendBudget } from "../lib/chat-send-budget"import { getModelContextCached } from "../api/ollama"import { requestGenerationCancel } from "../api/vram-handoff"import { effectiveContextWindow } from "../lib/context-window"@@ -73,14 +74,29 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],useChatStore.getState().addMessage(convId, assistantMessage)const personaPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''+ const providerId = getProviderIdFromModel(model)// Same count cap as the plain path: a long group chat must not outgrow the// proxy's message gate either.- const messages = capMessageCount([- { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt) },- ...groupHistory(conv.messages, model),- ])+ //+ // And the same TOKEN budget, per model per round (plan A4, GELTUNG). This is+ // the most multiplied surface in the app: one round sends the whole shared+ // history to two to four models, so an uncapped group chat bills history+ // level times N every time the user says anything. The budget is resolved per+ // model because the line-up can mix a 262k cloud model with a local one, and+ // a local one is not billed and stays exactly as it was.+ const messages = applyChatSendBudget(+ capMessageCount([+ { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt) },+ ...groupHistory(conv.messages, model),+ ]),+ {+ providerId,+ modelWindow: await getModelMaxTokens(model),+ sendWindowTokens: settings.codexSendWindowTokens,+ contextDecay: settings.contextDecay,+ },+ ).messages- const providerId = getProviderIdFromModel(model)const canThink = isThinkingCompatible(model)const useThinking: boolean | undefined = canThink ? settings.thinkingEnabled === true : undefinedconst keepThinking = useThinking === true@@ -425,9 +441,16 @@ export function useChat() {}}+ // The model's context window, resolved once: the memory budget below reads+ // it, and so does the send budget further down (plan A4). Zero means the+ // lookup failed, and a zero window resolves to no cap at all, which is the+ // pre-2.6.6 payload.+ let modelWindowTokens = 0+// Memory context injection (context-aware, sanitized)try {const contextTokens = await getModelMaxTokens(activeModel)+ modelWindowTokens = contextTokens// Embedding-first retrieval; falls back to keyword scoring offline.// excludeToolResults: this is a PLAIN chat (agent already delegated// above) — remembered tool RESULTS read as worked tool-call examples@@ -487,18 +510,32 @@ export function useChat() {// token budget while the count climbs past the LU Cloud proxy's// 400-message gate — after which EVERY send 400s and the chat is a// permanent dead end (yaserrieh, 2026-08-21).- const messages = capMessageCount([- ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),- ...conv.messages- .filter((m) => m.content.trim() !== '')- .map((m) => ({- role: m.role as 'user' | 'assistant' | 'system' | 'tool',- content: m.role === 'user' && cavemanReminder- ? `${cavemanReminder}\n${m.content}`- : m.content,- ...(m.images?.length ? { images: m.images.map(img => ({ data: img.data, mimeType: img.mimeType })) } : {}),- })),- ])+ // Token budget (plan A4), on top of the count cap and only where a token+ // sent is a token billed. Plain chat rebuilt the ENTIRE history on every+ // send, so turn 60 of a long chat paid for turns 1 to 59 again just to ask+ // "and shorter please", and every attachment ever made rode along with it,+ // invisible to the token estimator the whole way. Local backends and the+ // contextDecay notaus get the untouched array, byte for byte.+ const messages = applyChatSendBudget(+ capMessageCount([+ ...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),+ ...conv.messages+ .filter((m) => m.content.trim() !== '')+ .map((m) => ({+ role: m.role as 'user' | 'assistant' | 'system' | 'tool',+ content: m.role === 'user' && cavemanReminder+ ? `${cavemanReminder}\n${m.content}`+ : m.content,+ ...(m.images?.length ? { images: m.images.map(img => ({ data: img.data, mimeType: img.mimeType })) } : {}),+ })),+ ]),+ {+ providerId,+ modelWindow: modelWindowTokens,+ sendWindowTokens: settings.codexSendWindowTokens,+ contextDecay: settings.contextDecay,+ },+ ).messagesconst abort = new AbortController()abortRef.current = abortdiff --git a/src/lib/__tests__/chat-send-budget.test.ts b/src/lib/__tests__/chat-send-budget.test.tsnew file mode 100644index 00000000..6ba6ceb6--- /dev/null+++ b/src/lib/__tests__/chat-send-budget.test.ts@@ -0,0 +1,213 @@+/**+ * A4, the budget half: the three conversation surfaces stop sending the whole+ * history to a paid provider.+ *+ * Plain chat, a group round (per model) and compare (both sides) all resolve+ * their payload through this module, so the numbers below are the numbers that+ * go over the wire. Every claim has its negative control: the cap is one+ * setting away from off, and a local backend has to come out byte-identical to+ * 2.6.5 or the whole thing is a regression for everyone who does not pay per+ * token.+ */++import { describe, it, expect } from 'vitest'+import {+ applyChatSendBudget,+ applySendBudget,+ chatSendBudget,+ sharedChatSendBudget,+} from '../chat-send-budget'+import { estimateMessageTokens, MAX_SEND_MESSAGES } from '../context-compaction'+import { DEFAULT_SEND_WINDOW_TOKENS } from '../send-window'++interface Wire {+ role: string+ content: string+ images?: { data: string; mimeType: string }[]+}++const size = (msgs: Wire[]) => estimateMessageTokens(msgs as never)++/** A history of roughly `tokens` tokens, in ordinary chat-sized turns. */+function historyOf(tokens: number): Wire[] {+ const perMessage = 500+ const chars = 'x '.repeat(perMessage) // ~1000 chars, ~250 tokens+ const out: Wire[] = [{ role: 'system', content: 'be helpful' }]+ while (size(out) < tokens) {+ out.push({ role: 'user', content: `q${out.length} ${chars}` })+ out.push({ role: 'assistant', content: `a${out.length} ${chars}` })+ }+ return out+}++const CLOUD_32K = { providerId: 'lu-cloud', modelWindow: 32768, contextDecay: true }+const CLOUD_262K = { providerId: 'lu-cloud', modelWindow: 262144, contextDecay: true }+const OLLAMA = { providerId: 'ollama', modelWindow: 262144, contextDecay: true }++describe('A4: a long chat costs budget level, not history level', () => {+ it('a 50k-token history plus a short question sends at most the budget', () => {+ const history = historyOf(50000)+ history.push({ role: 'user', content: 'and shorter please' })+ expect(size(history)).toBeGreaterThan(50000)++ const budget = chatSendBudget(CLOUD_32K)!+ expect(budget).toBe(Math.floor(32768 * 0.8))+ const sent = applyChatSendBudget(history, CLOUD_32K)+ expect(sent.promptTokens).toBeLessThanOrEqual(budget)+ expect(size(sent.messages)).toBeLessThanOrEqual(budget)+ })++ it('negative control: without the cap the same turn sends the whole 50k', () => {+ const history = historyOf(50000)+ history.push({ role: 'user', content: 'and shorter please' })+ const sent = applyChatSendBudget(history, { ...CLOUD_32K, contextDecay: false })+ expect(sent.budget).toBeNull()+ expect(sent.promptTokens).toBeGreaterThan(50000)+ expect(sent.messages).toBe(history)+ })++ it('a 262k model is capped at the 64k send window, not at 209k', () => {+ const history = historyOf(120000)+ expect(chatSendBudget(CLOUD_262K)).toBe(DEFAULT_SEND_WINDOW_TOKENS)+ const sent = applyChatSendBudget(history, CLOUD_262K)+ expect(sent.promptTokens).toBeLessThanOrEqual(DEFAULT_SEND_WINDOW_TOKENS)+ })++ it('negative control: the same history uncapped is over 100k', () => {+ const history = historyOf(120000)+ const sent = applyChatSendBudget(history, { ...CLOUD_262K, contextDecay: false })+ expect(sent.promptTokens).toBeGreaterThan(100000)+ })++ it('the power-user setting still raises it', () => {+ expect(chatSendBudget({ ...CLOUD_262K, sendWindowTokens: 128000 })).toBe(128000)+ })++ it('keeps the last messages, so the question being asked is always sent', () => {+ const history = historyOf(50000)+ history.push({ role: 'user', content: 'and shorter please' })+ const sent = applyChatSendBudget(history, CLOUD_32K)+ expect(sent.messages[sent.messages.length - 1].content).toBe('and shorter please')+ expect(sent.messages[0].role).toBe('system')+ })+})++describe('A4: a local backend is byte-identical to 2.6.5', () => {+ it('hands the very same array through, unchanged', () => {+ const history = historyOf(120000)+ history.push({+ role: 'user',+ content: 'look',+ images: [{ data: 'A'.repeat(40000), mimeType: 'image/png' }],+ })+ const before = JSON.stringify(history)+ const sent = applyChatSendBudget(history, OLLAMA)+ expect(sent.budget).toBeNull()+ expect(sent.messages).toBe(history)+ expect(JSON.stringify(sent.messages)).toBe(before)+ expect(sent.droppedImages).toBe(0)+ })++ it('negative control: the same history on lu-cloud does shrink', () => {+ const history = historyOf(120000)+ expect(applyChatSendBudget(history, CLOUD_262K).messages.length).toBeLessThan(history.length)+ })++ it('an unknown window resolves to no cap rather than to a tiny one', () => {+ expect(chatSendBudget({ providerId: 'lu-cloud', modelWindow: 0, contextDecay: true })).toBeNull()+ })+})++describe('A4: a group round is budgeted per model per round', () => {+ it('every model in the line-up gets the same ceiling on the shared history', () => {+ const shared = historyOf(120000)+ for (const model of [CLOUD_262K, CLOUD_262K, CLOUD_32K]) {+ const sent = applyChatSendBudget(shared, model)+ expect(sent.promptTokens).toBeLessThanOrEqual(chatSendBudget(model)!)+ }+ })++ it('a local member of the line-up keeps its 2.6.5 payload', () => {+ const shared = historyOf(120000)+ expect(applyChatSendBudget(shared, OLLAMA).messages).toBe(shared)+ })++ it('negative control: uncapped, one round bills the full history N times', () => {+ const shared = historyOf(120000)+ const perModel = [CLOUD_262K, CLOUD_262K, CLOUD_32K].map(+ (m) => applyChatSendBudget(shared, { ...m, contextDecay: false }).promptTokens,+ )+ expect(Math.min(...perModel)).toBeGreaterThan(100000)+ })+})++describe('A4: compare caps the shared base before the fan-out', () => {+ const bothSides = [CLOUD_262K, CLOUD_32K]++ it('takes the tightest of the two budgets', () => {+ expect(sharedChatSendBudget(bothSides)).toBe(Math.floor(32768 * 0.8))+ })++ it('sends both sides the same payload, under budget', () => {+ const history = historyOf(120000)+ const budget = sharedChatSendBudget(bothSides)!+ const sent = applySendBudget(history, budget)+ expect(sent.promptTokens).toBeLessThanOrEqual(budget)+ // One array, handed to A and to B: two models that were given different+ // prompts are not being compared.+ expect(applySendBudget(history, budget).messages.length).toBe(sent.messages.length)+ })++ it('two local models are not capped at all', () => {+ expect(sharedChatSendBudget([OLLAMA, OLLAMA])).toBeNull()+ const history = historyOf(50000)+ expect(applySendBudget(history, null).messages).toBe(history)+ })++ it('a mixed pairing takes the paid budget for both, so the prompts match', () => {+ expect(sharedChatSendBudget([OLLAMA, CLOUD_32K])).toBe(Math.floor(32768 * 0.8))+ })++ it('negative control: with the notaus off nothing is capped', () => {+ expect(sharedChatSendBudget(bothSides.map((s) => ({ ...s, contextDecay: false })))).toBeNull()+ })+})++describe('A4: the count cap stays the second barrier', () => {+ it('a chat of many short turns is cut by count even under the token budget', () => {+ const many: Wire[] = [{ role: 'system', content: 'be helpful' }]+ for (let i = 0; i < 600; i++) {+ many.push({ role: i % 2 === 0 ? 'user' : 'assistant', content: `t${i}` })+ }+ expect(size(many)).toBeLessThan(chatSendBudget(CLOUD_262K)!)+ const sent = applyChatSendBudget(many, CLOUD_262K)+ expect(sent.messages.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)+ })+})++describe('A4: old attachments are dropped on the chat path too', () => {+ it('reports the pictures it left behind', () => {+ const pixels = 'A'.repeat(40000)+ const history: Wire[] = [{ role: 'system', content: 'be helpful' }]+ for (let i = 1; i <= 6; i++) {+ history.push({ role: 'user', content: `q${i}`, images: [{ data: pixels, mimeType: 'image/png' }] })+ history.push({ role: 'assistant', content: `a${i}` })+ }+ const sent = applyChatSendBudget(history, CLOUD_262K)+ expect(sent.droppedImages).toBe(4)+ const rode = sent.messages.filter((m) => m.images?.length)+ expect(rode.map((m) => m.content)).toEqual(['q5', 'q6'])+ })++ it('negative control: with the notaus off all six ride along', () => {+ const pixels = 'A'.repeat(40000)+ const history: Wire[] = [{ role: 'system', content: 'be helpful' }]+ for (let i = 1; i <= 6; i++) {+ history.push({ role: 'user', content: `q${i}`, images: [{ data: pixels, mimeType: 'image/png' }] })+ history.push({ role: 'assistant', content: `a${i}` })+ }+ const sent = applyChatSendBudget(history, { ...CLOUD_262K, contextDecay: false })+ expect(sent.droppedImages).toBe(0)+ expect(sent.messages.filter((m) => m.images?.length)).toHaveLength(6)+ })+})diff --git a/src/lib/__tests__/context-images.test.ts b/src/lib/__tests__/context-images.test.tsnew file mode 100644index 00000000..98622176--- /dev/null+++ b/src/lib/__tests__/context-images.test.ts@@ -0,0 +1,162 @@+/**+ * A4, the image half: old attachments stop riding along.+ *+ * An image is the only thing in a message the token estimator cannot see, and+ * the plain chat plus both agent loops re-sent every one of them on every+ * request forever. Each claim below has its negative control right next to it,+ * because the whole feature is one boolean away from being off and a test that+ * cannot go red proves nothing.+ */++import { describe, it, expect } from 'vitest'+import {+ ageOutImages,+ imageDropNote,+ GENERATED_IMAGE_DROP_NOTE,+ IMAGE_KEEP_RECENT,+} from '../context-images'+import { buildRequestMessages } from '../context-decay'++const PIXELS = 'A'.repeat(40000)++interface Wire {+ role: string+ content: string+ images?: { data: string; mimeType: string }[]+ visionFeedback?: boolean+ tool_call_id?: string+}++/** A chat of `turns` user/assistant pairs, every user turn with a picture. */+function chatWithImages(turns: number): Wire[] {+ const out: Wire[] = [{ role: 'system', content: 'be helpful' }]+ for (let i = 1; i <= turns; i++) {+ out.push({+ role: 'user',+ content: `question ${i}`,+ images: [{ data: PIXELS, mimeType: 'image/png' }],+ })+ out.push({ role: 'assistant', content: `answer ${i}` })+ }+ return out+}++const imagesOn = (msgs: Wire[]) =>+ msgs.filter((m) => Array.isArray(m.images) && m.images.length > 0).map((m) => m.content)++describe('A4: the picture from message 1 is not in the payload at message 20', () => {+ const history = chatWithImages(20)++ it('keeps only the newest user turns, older attachments become a note', () => {+ const aged = ageOutImages(history)+ expect(imagesOn(aged.messages)).toEqual(['question 19', 'question 20'])+ expect(IMAGE_KEEP_RECENT).toBe(2)++ const first = aged.messages.find((m) => m.content.startsWith('question 1\n'))!+ expect(first.images).toBeUndefined()+ expect(first.content).toContain('question 1')+ expect(first.content).toContain(imageDropNote(1))+ expect(aged.strippedImages).toBe(18)+ expect(aged.savedChars).toBe(18 * PIXELS.length)+ })++ it('negative control: with the notaus off every one of the 20 rides along', () => {+ const aged = ageOutImages(history, { enabled: false })+ expect(imagesOn(aged.messages)).toHaveLength(20)+ expect(aged.strippedImages).toBe(0)+ expect(JSON.stringify(aged.messages)).toBe(JSON.stringify(history))+ })++ it('never touches the array it was handed', () => {+ ageOutImages(history)+ expect(imagesOn(history)).toHaveLength(20)+ })+})++describe('A4: the live turn always keeps its picture', () => {+ it('a single attachment on the newest question survives', () => {+ const msgs: Wire[] = [+ { role: 'system', content: 'be helpful' },+ { role: 'user', content: 'what is this', images: [{ data: PIXELS, mimeType: 'image/png' }] },+ ]+ expect(ageOutImages(msgs).strippedImages).toBe(0)+ })++ it('tool traffic on the user role does not push it out (hermes transport)', () => {+ // Every hermes tool result is a `user` message. Counting those as user+ // turns would drop the picture the question is about one step into the run.+ const msgs: Wire[] = [+ { role: 'user', content: 'describe it', images: [{ data: PIXELS, mimeType: 'image/png' }] },+ { role: 'assistant', content: '<tool_call>{"name":"file_read"}</tool_call>' },+ { role: 'user', content: '<tool_response>bytes</tool_response>' },+ { role: 'assistant', content: '<tool_call>{"name":"file_read"}</tool_call>' },+ { role: 'user', content: '<tool_response>more bytes</tool_response>' },+ ]+ expect(ageOutImages(msgs).strippedImages).toBe(0)+ })++ it('negative control: two more real user turns and it does go', () => {+ const msgs: Wire[] = [+ { role: 'user', content: 'describe it', images: [{ data: PIXELS, mimeType: 'image/png' }] },+ { role: 'assistant', content: 'sure' },+ { role: 'user', content: 'and now' },+ { role: 'assistant', content: 'ok' },+ { role: 'user', content: 'and now' },+ ]+ expect(ageOutImages(msgs).strippedImages).toBe(1)+ })+})++describe('A4: a picture the run generated itself says so', () => {+ it('vision feedback degrades to its own note, not the user one', () => {+ const msgs: Wire[] = [+ {+ role: 'user',+ content: 'Here is the image you generated.',+ images: [{ data: PIXELS, mimeType: 'image/png' }],+ visionFeedback: true,+ },+ { role: 'assistant', content: 'looks good' },+ { role: 'user', content: 'now the video' },+ { role: 'assistant', content: 'ok' },+ { role: 'user', content: 'go' },+ ]+ const aged = ageOutImages(msgs)+ expect(aged.messages[0].images).toBeUndefined()+ expect(aged.messages[0].content).toContain(GENERATED_IMAGE_DROP_NOTE)+ expect(aged.messages[0].content).not.toContain('ask the user to send')+ })+})++describe('A4: the agent and coding loops inherit the rule from the builder', () => {+ // Neither loop is touched: both already build their request through+ // buildRequestMessages, which is where the rule lives.+ const run: Wire[] = [+ { role: 'system', content: 'you are a coding agent' },+ { role: 'user', content: 'look at this screenshot', images: [{ data: PIXELS, mimeType: 'image/png' }] },+ { role: 'assistant', content: '', tool_call_id: undefined },+ { role: 'tool', content: 'file bytes' },+ { role: 'user', content: 'keep going' },+ { role: 'assistant', content: 'working' },+ { role: 'user', content: 'still going' },+ ]++ it('drops the aged attachment and reports what it saved', () => {+ const built = buildRequestMessages(run as never, { budgetTokens: 64000 })+ expect(built.droppedImages).toBe(1)+ expect(built.savedImageChars).toBe(PIXELS.length)+ expect(imagesOn(built.messages as unknown as Wire[])).toHaveLength(0)+ })++ it('negative control: the contextDecay notaus sends the pixels again', () => {+ const built = buildRequestMessages(run as never, { budgetTokens: 64000, enabled: false })+ expect(built.droppedImages).toBe(0)+ expect(imagesOn(built.messages as unknown as Wire[])).toEqual(['look at this screenshot'])+ })++ it('negative control: the image rule alone can be switched off', () => {+ const built = buildRequestMessages(run as never, { budgetTokens: 64000, ageImages: false })+ expect(built.droppedImages).toBe(0)+ expect(imagesOn(built.messages as unknown as Wire[])).toHaveLength(1)+ })+})diff --git a/src/lib/chat-send-budget.ts b/src/lib/chat-send-budget.tsnew file mode 100644index 00000000..7e8c89c6--- /dev/null+++ b/src/lib/chat-send-budget.ts@@ -0,0 +1,127 @@+/**+ * The send budget for the CONVERSATION surfaces (2.6.6, plan A4).+ *+ * A2 put a ceiling on what one agent step may send. The three chat surfaces had+ * none, and two of them multiply every byte:+ *+ * - plain chat rebuilds the full history on every send, so turn 60 of a long+ * chat pays for turns 1 to 59 again to ask "and shorter please";+ * - a group round sends that same full history to two to four models, so one+ * round costs history level times N;+ * - compare sends it to both sides of the panel, every round, uncapped.+ *+ * So all three get the A2 number: min(0.8 x model window,+ * codexSendWindowTokens) on a paid provider, and nothing at all anywhere else.+ * Local backends are byte-identical to 2.6.5 because there is no bill on the+ * other end, and the contextDecay notaus returns every surface to exactly the+ * payload it sent before, which is what makes this supportable in the field+ * without a rollback release.+ *+ * The message-COUNT cap (capMessageCount) stays where it is on every path. It+ * guards a different failure: a chat of many short turns fits every token+ * budget while the count climbs past the proxy's 400-message gate.+ */++import { compactMessages, estimateMessageTokens } from './context-compaction'+import { ageOutImages } from './context-images'+import { effectiveSendWindow, isPaidProvider } from './send-window'++export interface ChatSendBudgetInput {+ /** Provider id of the model this payload goes to. */+ providerId: string+ /** The model's context window, as getModelMaxTokens resolved it. */+ modelWindow: number+ /** settings.codexSendWindowTokens. */+ sendWindowTokens?: number+ /** settings.contextDecay. The notaus switches the whole cap off. */+ contextDecay?: boolean+}++/**+ * The budget one send may carry, or null when this surface is not capped at+ * all. Null is not "unlimited by accident": it is the explicit 2.6.5 path, and+ * callers hand the untouched array straight through on it.+ */+export function chatSendBudget(input: ChatSendBudgetInput): number | null {+ if (input.contextDecay === false) return null+ if (!isPaidProvider(input.providerId)) return null+ const window = effectiveSendWindow({+ providerId: input.providerId,+ modelWindow: input.modelWindow,+ sendWindowTokens: input.sendWindowTokens,+ capEnabled: true,+ })+ return window > 0 ? window : null+}++/**+ * The budget for a payload that goes to SEVERAL models at once (compare, and+ * conceptually a group round): the tightest of the applicable ones.+ *+ * Both sides of a compare have to receive the same prompt or the comparison is+ * not a comparison, so a mixed pairing takes the paid side's budget for both.+ */+export function sharedChatSendBudget(inputs: ChatSendBudgetInput[]): number | null {+ const budgets = inputs.map(chatSendBudget).filter((b): b is number => b !== null)+ return budgets.length ? Math.min(...budgets) : null+}++export interface ChatSendResult<T> {+ messages: T[]+ /** The budget that was applied, or null when the payload passed through. */+ budget: number | null+ /** Estimated size of the payload as it goes out. */+ promptTokens: number+ /** Attachments left behind by the image rule. */+ droppedImages: number+}++export interface ApplyBudgetOptions {+ /** How many of the newest user turns keep their attachments. */+ keepImages?: number+}++/**+ * Apply a resolved budget to a message array.+ *+ * Order is the same as the agent builder's: attachments first (they are the+ * bytes the token estimator cannot see), then the token budget. Compaction runs+ * with the A3 hysteresis, so a chat sitting at the ceiling keeps the same+ * prompt prefix for several turns running instead of shifting the window on+ * every single send and paying full price for the whole history again.+ */+export function applySendBudget<T extends { role: string; content?: unknown }>(+ messages: T[],+ budget: number | null,+ opts: ApplyBudgetOptions = {},+): ChatSendResult<T> {+ type Estimated = Parameters<typeof estimateMessageTokens>[0]+ if (budget === null) {+ // The untouched array, by reference: this is the 2.6.5 payload, and+ // nothing about it may change on a local backend or with the notaus off.+ return {+ messages,+ budget: null,+ promptTokens: estimateMessageTokens(messages as unknown as Estimated),+ droppedImages: 0,+ }+ }+ const aged = ageOutImages(messages, { keepRecent: opts.keepImages })+ const compacted = compactMessages(aged.messages as unknown as Estimated, budget, {+ hysteresis: true,+ }) as unknown as T[]+ return {+ messages: compacted,+ budget,+ promptTokens: estimateMessageTokens(compacted as unknown as Estimated),+ droppedImages: aged.strippedImages,+ }+}++/** Resolve the budget for one model and apply it in one call. */+export function applyChatSendBudget<T extends { role: string; content?: unknown }>(+ messages: T[],+ input: ChatSendBudgetInput & ApplyBudgetOptions,+): ChatSendResult<T> {+ return applySendBudget(messages, chatSendBudget(input), { keepImages: input.keepImages })+}diff --git a/src/lib/context-decay.ts b/src/lib/context-decay.tsindex 35a070da..7bfd2b86 100644--- a/src/lib/context-decay.ts+++ b/src/lib/context-decay.ts@@ -32,6 +32,7 @@*/import { truncateToolResult } from './truncate-tool-result'+import { ageOutImages } from './context-images'import {compactMessages,estimateMessageTokens,@@ -416,11 +417,19 @@ export interface BuildRequestOptions<T> extends DecayOptions<T> {hysteresis?: boolean/** Prune superseded todo_write pairs (plan A5). Off with decay off. */prunePlans?: boolean+ /** Age out attachments of older user turns (plan A4). Off with decay off. */+ ageImages?: boolean+ /** How many of the newest user turns keep their attachments (plan A4). */+ keepImages?: number}export interface BuiltRequest<T> extends DecayReport<T> {/** Superseded plan messages dropped or blanked. */prunedPlans: number+ /** Attachments left behind by the image rule (plan A4). */+ droppedImages: number+ /** Base64 characters the image rule kept off the wire. */+ savedImageChars: number/** Estimated size of the request as it goes out. */promptTokens: number}@@ -431,12 +440,25 @@ export interface BuiltRequest<T> extends DecayReport<T> {* The order is binding (plan A1): decay first, then the budget, then* compaction. The other way round the budget counts full results, decides to* drop whole messages, and the decay it would have needed never happens.+ *+ * Attachments age out ahead of all of it (plan A4). They are the one thing the+ * token estimator cannot see, so leaving them for later would mean every budget+ * decision on the way is taken on a size that is not the size being billed. It+ * is the same builder both agent loops already call, which is why the picture a+ * user attached three turns ago stops riding on every step without either loop+ * having to know about the rule.*/export function buildRequestMessages<T extends DecayMessage>(messages: T[],opts: BuildRequestOptions<T>,): BuiltRequest<T> {- const decayed = applyToolResultDecay(messages, opts)+ const aged =+ opts.enabled !== false && opts.ageImages !== false+ ? ageOutImages(messages as unknown as Array<{ role: string; content?: unknown }>, {+ keepRecent: opts.keepImages,+ })+ : { messages: messages.slice(), strippedImages: 0, savedChars: 0 }+ const decayed = applyToolResultDecay(aged.messages as unknown as T[], opts)let working = decayed.messageslet prunedPlans = 0if (opts.enabled !== false && opts.prunePlans !== false) {@@ -455,6 +477,8 @@ export function buildRequestMessages<T extends DecayMessage>(savedChars: decayed.savedChars,trimmedKeys: decayed.trimmedKeys,prunedPlans,+ droppedImages: aged.strippedImages,+ savedImageChars: aged.savedChars,promptTokens: estimateMessageTokens(compacted as unknown as Parameters<typeof estimateMessageTokens>[0],),diff --git a/src/lib/context-images.ts b/src/lib/context-images.tsnew file mode 100644index 00000000..e35b9f0e--- /dev/null+++ b/src/lib/context-images.ts@@ -0,0 +1,143 @@+/**+ * Old attachments stop riding along (2.6.6, plan A4).+ *+ * An image is the most expensive thing a message can carry and the only thing+ * the token estimator cannot see: `estimateMessageTokens` reads `content`, so a+ * 900 KB base64 screenshot counts as zero tokens in every budget decision we+ * make, and then gets billed as a few thousand real ones. Worse, it is carried+ * FOREVER. The plain chat rebuilds the whole history on every send, and the two+ * agent loops rebuild it on every STEP of every following turn, so one picture+ * attached on Monday is paid for again by every request for the rest of that+ * conversation.+ *+ * The rule is the same one age decay uses for tool results, applied to pixels:+ * only the newest user turns carry their attachments. Everything older keeps+ * its text and loses the bytes, with a one-line note in their place so the+ * model knows a picture existed rather than silently seeing a question about+ * nothing.+ *+ * Three properties, same as the decay module:+ *+ * 1. BUILDER ONLY. The stripping happens on the copy a request is built from.+ * The store, the persisted conversation and the visible bubble keep the+ * image, so the user still sees what they attached and the whole feature is+ * one settings flip away from being off.+ * 2. POSITIONAL AND DETERMINISTIC. The keep set is "the newest N user turns",+ * nothing derived from sizes or budgets, so the same history always yields+ * the same bytes and the prompt prefix stays still.+ * 3. NEVER THE LIVE TURN. The message being answered is by definition among+ * the newest user turns, so the picture the question is about is always+ * there (plan meta-rule 4).+ */++/** How many of the newest user turns keep their attachments. */+export const IMAGE_KEEP_RECENT = 2++/** Minimal shape this module needs. Fits ChatMessage and the group wire type. */+export interface ImageMessage {+ role: string+ content?: unknown+ images?: unknown[]+ /** Set by buildVisionFeedback: the loop attached this picture itself. */+ visionFeedback?: boolean+ tool_call_id?: string+}++/**+ * What replaces a user attachment. It has to say the picture still EXISTS,+ * otherwise a model asked "what is in this image" answers that it never got+ * one, which reads as a bug to the user who can see it on screen.+ */+export function imageDropNote(count: number): string {+ const n = count === 1 ? 'An image' : `${count} images`+ const it = count === 1 ? 'it' : 'them'+ return `[${n} attached earlier in this conversation ${count === 1 ? 'is' : 'are'} not re-sent with every message. The attachment is still in the chat; ask the user to send ${it} again if you need to look at ${it}.]`+}++/** What replaces a picture the run generated and fed back to itself. */+export const GENERATED_IMAGE_DROP_NOTE =+ '[The image generated earlier in this run is not re-attached to every request. It is already shown to the user in the chat.]'++/**+ * True for a message that carries a tool RESULT rather than a user turn: the+ * native `tool` role, or a Hermes `<tool_response>` riding on a user message.+ *+ * It matters for the keep set. On the Hermes transport every tool result is a+ * user message, so counting those as user turns would push the picture the user+ * just attached out of the window after a single step of tool traffic.+ */+function carriesToolResult(msg: ImageMessage): boolean {+ if (msg.role === 'tool') return true+ if (typeof msg.tool_call_id === 'string' && msg.tool_call_id) return true+ if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.includes('<tool_response>')) {+ return true+ }+ return false+}++export interface AgeImagesOptions {+ /** The contextDecay notaus. False sends the history exactly as before. */+ enabled?: boolean+ /** How many of the newest user turns keep their attachments. */+ keepRecent?: number+}++export interface AgedImages<T> {+ /** A fresh array. The input is never touched. */+ messages: T[]+ /** Messages whose attachments were replaced by a note. */+ strippedMessages: number+ /** Attachments left behind. */+ strippedImages: number+ /** Base64 characters kept off the wire. */+ savedChars: number+}++/**+ * Drop the attachments of every user turn older than the newest `keepRecent`.+ *+ * With the notaus off the messages come back unchanged (a copy, so the caller+ * can keep treating the result as the send array).+ */+export function ageOutImages<T extends { role: string; content?: unknown }>(+ messages: T[],+ opts: AgeImagesOptions = {},+): AgedImages<T> {+ const out = messages.slice()+ if (opts.enabled === false) {+ return { messages: out, strippedMessages: 0, strippedImages: 0, savedChars: 0 }+ }+ const keepRecent = Math.max(0, opts.keepRecent ?? IMAGE_KEEP_RECENT)++ const userTurns: number[] = []+ for (let i = 0; i < messages.length; i++) {+ const m = messages[i] as ImageMessage+ if (m.role !== 'user' || carriesToolResult(m)) continue+ userTurns.push(i)+ }+ const keep = new Set(userTurns.slice(-keepRecent))++ let strippedMessages = 0+ let strippedImages = 0+ let savedChars = 0+ for (let i = 0; i < messages.length; i++) {+ const m = messages[i] as ImageMessage+ if (m.role !== 'user' || !Array.isArray(m.images) || m.images.length === 0) continue+ if (keep.has(i)) continue++ const count = m.images.length+ for (const img of m.images) {+ const data = (img as { data?: unknown }).data+ if (typeof data === 'string') savedChars += data.length+ }+ const note = m.visionFeedback ? GENERATED_IMAGE_DROP_NOTE : imageDropNote(count)+ const text = typeof m.content === 'string' ? m.content : ''+ const next = { ...m } as ImageMessage+ delete next.images+ next.content = text.trim() ? `${text}\n\n${note}` : note+ out[i] = next as unknown as T+ strippedMessages+++ strippedImages += count+ }+ return { messages: out, strippedMessages, strippedImages, savedChars }+}