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
merge: the night shift's thirteen fixes join the 2.6.6 cost work
Davida43eee2fd045
diff --cc CHANGELOG.mdindex d7e956ad,733362a4..60ec62d0--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -4,53 -4,6 +4,105 @@@ All notable changes to Locally Uncensor## [Unreleased]+## [2.6.6] - 2026-08-21++The release that makes an agent or coding run cost less to do the same work,+and gives the Code view a mode menu, a plan panel and a real file explorer.++### Added++- **A mode menu in the Code composer.** Ask permissions, Bypass permissions or+ Plan mode, chosen per conversation with a global default in Settings. Bypass+ never lifts the cloud shell lock, and the menu says so. Plan mode explores+ read only and stops for your yes; Approve and run then carries the whole plan+ out in the same run and never lands in Bypass on its own, showing the mode it+ will run in and the real commands first.+- **A file explorer in the Code view.** A real tree you expand folder by folder+ and widen by dragging its edge, with the width kept across a restart. Click a+ file to preview it: code with highlighting, images inline, HTML in a sandboxed+ frame with scripts off until you ask. node_modules, .git, target and dist stay+ out of the way.+- **Prompt caching for your own Anthropic key.** Requests carry cache markers on+ the system block, the last tool and the last stable message, so a repeated+ request reads from the cache instead of paying for the whole prompt again.++### Changed++- **Agent and Code mode send far less context per step.** Older tool results are+ trimmed out of what goes upstream while the newest step is kept in full, the+ amount sent on a paid step is capped, and the stable half of the prompt stays+ put so the upstream cache keeps working across a long run. The coding tool+ catalog is leaner too. A setting turns the trimming off if a run ever+ misbehaves.+- **The plan moved into the right panel**, live above the file explorer, instead+ of sitting over the composer.+- **Plain chat, group chat and A/B compare cap the history they send to paid+ models**, so a long conversation stops getting more expensive without you+ noticing. A group round still bills once per model, and the composer says so.+- **The credits meter counts against the send cap**, not the whole model window,+ so its warning fires before a paid step gets expensive rather than after.++### Fixed++- **An agent run stopped firing a hidden memory step on every round.** The+ automatic memory step on LU Cloud now runs only if you turn it on, and then on+ the cheapest capable model rather than the one you are chatting with.+- **Old images stop riding along.** A follow up in the same conversation no+ longer re-attaches pictures from many messages back on every later step where+ nothing looks at them.++- **A wiped chat database is restored instead of overwritten.** A hard crash can++ leave the browser engine discarding the whole chat store while everything else++ comes back, and the restore only ever looked at the other half. The app now++ restores the chats from its own backup on the next start, and the backup++ merges with what it already held rather than writing an empty snapshot over++ the good copy seconds after every launch.++- **A hosted chat past the message limit shrinks its request instead of dying.**++ Plain chat sends the whole conversation every turn, so once a conversation++ crossed the server's message count limit every further turn was refused and++ the chat was a permanent dead end. The client now halves the history it sends++ and retries when the server refuses on count, without touching the stored++ conversation.++- **Browser voice recording reaches the transcriber.** The recorded audio was++ refused as the wrong body type before the handler ever saw it, and both voice++ requests went out without the header every other call sends. The content type++ rule now has one carve out for the audio endpoint and stays strict everywhere++ else.++- **An invented link is caught by the app.** A URL in an agent answer that++ appears nowhere in what the model was shown cannot have come from a tool. The++ bubble labels it as unverified, and after a real tool success the agent gets++ one steer to look it up properly or take it back.++- **The trim notice stops planting a system message mid conversation.** Strict++ chat templates refuse a system message that is not the first one and the run++ died with "System message must be at the beginning", which is why it only ever++ happened once a chat had grown long. The notice now rides inside user++ material, and repeated trims no longer stack notices.++- **The built in engine grows to the context the run budgets for.** An agent++ turn carries the tool catalogue and outgrew the engine's 8192 start default,++ which no per request option can raise. The engine is now restarted at the++ smaller of the model's trained context and the agent ceiling before the run++ budget is read.++- **The engine's KV save follows the tokens, not slot zero.** The save asks the++ engine which slot really holds the conversation instead of always writing the++ first one, so the saved state is the history and not a husk.++- **A render evicts with manners.** The Create, music and video lanes now save++ the engine state and bring Ollama, LM Studio and the built in engine back warm++ after the render, instead of killing them and leaving the next chat turn to a++ cold start.++- **The LoRA trainer plans for an AMD card.** The trainer decided its++ environment from nvidia-smi alone and read that probe's silence as no GPU, so++ an AMD box got CUDA wheels that import fine, see no device and die in step 1.++ The wheel channel is now planned per vendor: ROCm on Linux, and a refusal++ before the clone and the 2.5 GB on Windows and macOS, where no such wheel++ exists.++- **A bundle card reads its own downloads.** Video bundles share files, so one++ failed attempt on a shared file put a Retry button on every card and hid++ bundles that were complete on disk. The disk verdict is asked first now.++- **A finished download waits for ComfyUI in the Model Manager too.** A large++ file lands before ComfyUI's own scan has picked it up, so the model was simply++ absent from the Installed tab and every picker until a manual reload.++- **Source pin tests read the same bytes on a CRLF checkout**, so a Windows++ clone can report the suite honestly.+## [2.6.5] - 2026-08-16The release that makes updating possible again, plus the work you alreadydiff --cc src/api/__tests__/context-compaction.test.tsindex 5208bc43,d2d5de28..4adc53a0--- a/src/api/__tests__/context-compaction.test.ts+++ b/src/api/__tests__/context-compaction.test.ts@@@ -290,68 -295,3 +295,73 @@@ describe('compactMessages — oversizeexpect(notice!.content).toMatch(/never repeat a call/)})})++// ── Message-count ceiling (yaserrieh, 2026-08-21) ────────────────+// A chat of many SHORT turns sits under every token budget while the count+// grows past the LU Cloud proxy's 400-message gate; from then on every send+// 400s ("too many messages") and the chat is a permanent dead end. The cap+// must fire on COUNT alone.++import { MAX_SEND_MESSAGES, capMessageCount } from '../../lib/context-compaction'++describe('message-count ceiling', () => {+ const tiny = (n: number): OllamaChatMessage[] => [+ { role: 'system', content: 'sys' },+ ...Array.from({ length: n }, (_, i) => ({+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',+ content: `m${i}`,+ })),+ ]++ it('compactMessages shrinks a count-heavy history even under the token budget', () => {+ const messages = tiny(450)+ // Huge token budget: the OLD code returned this unchanged.+ const out = compactMessages(messages, 10_000_000)+ expect(out.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)+ expect(out[0].role).toBe('system')+ expect(out[out.length - 1].content).toBe('m449')+ })++ it('compactMessages leaves a history under both budgets alone', () => {+ const messages = tiny(100)+ expect(compactMessages(messages, 10_000_000)).toEqual(messages)+ })+- it('count trim announces itself like a token trim', () => {++ it('count trim announces itself like a token trim, riding user material', () => {+ const out = compactMessages(tiny(450), 10_000_000)++ // The notice rides inside a user message since the Jinja fix: a system++ // message mid conversation makes strict chat templates raise "System++ // message must be at the beginning" (Discord #bug-reports 2026-08-21).++ // A count-driven trim announces itself exactly like a token-driven one.+ const notice = out.find(- (m) => m.role === 'system' && typeof m.content === 'string' && m.content.includes('trimmed'),++ (m) => m.role === 'user' && typeof m.content === 'string' && m.content.includes('trimmed'),+ )+ expect(notice).toBeTruthy()++ expect(out.some((m, i) => m.role === 'system' && i > 0)).toBe(false)+ })++ it('capMessageCount keeps system prompt and the newest messages', () => {+ const out = capMessageCount(tiny(450))+ expect(out.length).toBe(MAX_SEND_MESSAGES)+ expect(out[0].content).toBe('sys')+ expect(out[out.length - 1].content).toBe('m449')+ })++ it('capMessageCount never starts the window on an orphan tool result', () => {+ const msgs: OllamaChatMessage[] = [+ { role: 'system', content: 'sys' },+ ...Array.from({ length: 500 }, (_, i) => ({+ role: (i % 2 === 0 ? 'assistant' : 'tool') as 'assistant' | 'tool',+ content: `m${i}`,+ })),+ ]+ const out = capMessageCount(msgs)+ expect(out[1].role).not.toBe('tool')+ expect(out.length).toBeLessThanOrEqual(MAX_SEND_MESSAGES)+ })++ it('capMessageCount is the identity under the ceiling', () => {+ const messages = tiny(50)+ expect(capMessageCount(messages)).toBe(messages)+ })+})diff --cc src/hooks/useAgentChat.tsindex 816c4ee0,39ef5c1e..02a552f0--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@@ -36,11 -36,9 +36,12 @@@ import { parseLooseToolCalls, stripMatcimport { mediaCallSucceeded } from '../lib/media-result'import { summarizeTurn } from '../lib/turn-summary'import { buildVisionFeedback } from '../api/vision-feedback'-import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'+import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'+import { buildRequestMessages, trimWorkingHistory } from '../lib/context-decay'+import { effectiveSendWindow } from '../lib/send-window'+import { useSendSizeStore } from '../stores/sendSizeStore'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'+ import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'import { useMemoryStore } from '../stores/memoryStore'import { useVoiceStore } from '../stores/voiceStore'import { autoSpeak } from '../lib/ttsBridge'@@@ -71,8 -69,9 +72,9 @@@ import { finalStripThinkingTags, splitOimport { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'+ import { findUnbackedLinks, unbackedLinksSteer } from '../lib/unbacked-links'import { useTodoStore } from '../stores/todoStore'-import { platformPromptLine } from '../lib/host-platform'+import { platformPromptLine, hostClockLine } from '../lib/host-platform'import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'diff --cc src/hooks/useChat.tsindex 18e7b1e1,a9c1f9be..6c84ef8f--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@@ -8,8 -8,8 +8,9 @@@ import { useMemoryStore } from "../storimport { useVoiceStore } from "../stores/voiceStore"import { autoSpeak } from "../lib/ttsBridge"import { retrieveContext } from "../api/rag"-import { getModelMaxTokens } from "../lib/context-compaction"+import { getModelMaxTokens, capMessageCount } from "../lib/context-compaction"+import { applyChatSendBudget, chatBudgetApplies } from "../lib/chat-send-budget"+ import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS } from "../lib/too-many-messages"import { getModelContextCached } from "../api/ollama"import { requestGenerationCancel } from "../api/vram-handoff"import { effectiveContextWindow } from "../lib/context-window"diff --cc src/hooks/useCodex.tsindex b97ee3c1,337ccbdc..b56ddcfd--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@@ -54,16 -52,13 +54,17 @@@ import { CREDITS_EXHAUSTED_MESSAGE } frimport { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'import { extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair'import { canonicalToolName } from '../lib/loose-tool-parse'-import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, CREATE_TOOLS } from '../lib/tool-selection'+import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, isGatedTool } from '../lib/tool-selection'import { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'-import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'-import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'+import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'+import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'+import { buildRequestMessages, trimWorkingHistory, decayRestoredToolResult, isToolResult } from '../lib/context-decay'+import { effectiveSendWindow } from '../lib/send-window'+import { useSendSizeStore } from '../stores/sendSizeStore'import { resolveAgentNumCtx } from '../lib/agent-num-ctx'+import { platformPromptLine, hostClockLine } from '../lib/host-platform'+ import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'import { AgentLoopGuard } from '../lib/agent-loop-guard'import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'import { applyAllStagedChanges } from '../lib/staged-apply'diff --cc src/lib/context-compaction.tsindex a470cf96,bf28e954..8eb6ac58--- a/src/lib/context-compaction.ts+++ b/src/lib/context-compaction.ts@@@ -153,72 -153,24 +167,78 @@@ function isToolResultMessage(msg: Ollam* Dropping is honest: the model re-reads with file_read when it needs the bytes* again, instead of trusting a lossy stub.*/+/**+ * Count-only cap for paths that never token-compact (the plain chat path).+ * Keeps the system prompt plus the newest messages and never starts the kept+ * window on an orphan tool result. Token budgets are compactMessages' job;+ * this only guarantees the proxy's message-count gate can't be tripped.+ */+export function capMessageCount<T extends { role: string; content?: unknown }>(+ messages: T[],+ max = MAX_SEND_MESSAGES,+): T[] {+ if (messages.length <= max) return messages+ const sys = messages[0]?.role === 'system' ? [messages[0]] : []+ const rest = sys.length ? messages.slice(1) : messages+ const kept = rest.slice(-(max - sys.length))+ while (kept.length > 0 && isToolResultMessage(kept[0] as unknown as OllamaChatMessage)) {+ kept.shift()+ }+ return [...sys, ...kept]+}++/**+ * Hysteresis (2.6.6, plan A3). Trimming to exactly the budget every step moves+ * the prompt prefix every step, and a moved prefix is a cold upstream cache:+ * the whole history is billed at full price again. So compaction waits until+ * the history is 15 percent OVER budget and then drops in one big block down+ * to 70 percent of it. In between, the array passes through byte-for-byte and+ * the cache keeps hitting.+ *+ * The decision is taken from the messages array alone, with no watermark kept+ * anywhere, so a run aborted mid-step strands no state (plan A3, Runde 2).+ */+export const COMPACT_TRIGGER_RATIO = 1.15+export const COMPACT_TARGET_RATIO = 0.7++/**+ * How many messages one drop step removes when the carried history has to+ * shrink (trimWorkingHistory in context-decay).+ *+ * The hysteresis pair above is what keeps the prefix still; this is the step+ * size of the search for how much to drop, and it is a block rather than a+ * single message because each probe re-measures the whole decayed history.+ * One at a time would make a long run quadratic for no gain.+ */+export const COMPACT_DROP_BLOCK = 16++export interface CompactOptions {+ /** Wait for budget × 1.15, then drop to budget × 0.7. */+ hysteresis?: boolean+}+export function compactMessages(messages: OllamaChatMessage[],- maxTokens: number+ maxTokens: number,+ opts: CompactOptions = {},): OllamaChatMessage[] {const currentTokens = estimateMessageTokens(messages)+ const triggerTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TRIGGER_RATIO) : maxTokens+ const targetTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TARGET_RATIO) : maxTokens- // Already within budget- if (currentTokens <= maxTokens) return messages+ // Already within budget — BOTH budgets. A history that fits the token+ // window but exceeds the message-count ceiling still has to shrink.+ if (currentTokens <= triggerTokens && messages.length <= MAX_SEND_MESSAGES) return messages- // Separate system prompt (always kept)+ // Separate system prompt (always kept). A stray system message deeper in+ // the history that is only an old trim notice is dropped outright here:+ // strict Jinja chat templates raise on any mid-conversation system message+ // ("System message must be at the beginning", Discord #bug-reports+ // 2026-08-21), so one may never survive a compaction round.const systemMsg = messages[0]?.role === 'system' ? messages[0] : null- const nonSystem = systemMsg ? messages.slice(1) : [...messages]+ const nonSystem = (systemMsg ? messages.slice(1) : [...messages]).filter(+ (m) => !(m.role === 'system' && typeof m.content === 'string' && trimNoticeRe().test(m.content)),+ )// If we have fewer messages than KEEP_RECENT, can't compact furtherif (nonSystem.length <= KEEP_RECENT) return messagesdiff --cc src/lib/release-notes.tsindex cdc4ed14,9a177922..41f40a98--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@@ -31,41 -31,6 +31,52 @@@ export interface ReleaseNote}export const RELEASE_NOTES: ReleaseNote[] = [+ {+ version: '2.6.6',+ headline: 'Agent and Code mode do the same work for fewer credits',+ lines: [+ 'Agent and Code mode send far less context on every step, so every step costs fewer credits. Old tool results shrink as the run goes on, the amount sent per step is capped, and the stable part of the prompt stays put so the upstream cache keeps paying off. The coding tool list alone is meaningfully leaner.',+ 'A run no longer quietly re-reads and re-sends the same big files forever, and an agent run stopped firing a hidden memory step on every single round. Same result, smaller bill, and the long runs are where you feel it.',+ 'Plain chat, group chat and A/B compare now cap how much history they send to paid models, so a long conversation stops getting more expensive without you noticing. A group round still costs one bill per model, and the composer says so.',+ 'Anthropic models sent with your own key now use prompt caching, so a follow up on the same conversation is cheaper than starting it cold.',+ 'The Code view grew a mode menu per conversation (Ask, Bypass, Plan mode), the plan moved into the right panel, and a real file explorer arrived that you can widen and preview files in without leaving the app.',++ 'Your chats survive a hard crash: a wiped chat database is restored from the app\'s own backup instead of the backup overwriting the good copy. A long hosted chat that hits the message limit shrinks its request and keeps going instead of refusing every further turn, browser voice recording reaches the transcriber again, and a link an agent made up is labelled as unverified.',+ ],+ details: [+ {+ title: 'Local',+ items: [+ 'Agent and Code runs trim older tool results out of what they send upstream. The newest step is always kept in full, so the model never edits against something it can no longer see, and a setting turns the whole thing off if a run ever misbehaves.',+ 'The context sent on a paid step is capped, and the meter now counts against that cap instead of the whole model window, so the warning fires before a step gets expensive rather than after.',+ 'The stable half of the prompt no longer changes every step. The minute clock and everything else that moves each turn sit at the end now, so the upstream cache survives a long run instead of going cold on a timestamp.',+ 'The coding tool catalog is leaner: the git and gh cookbook, paragraphs the system prompt already states, and the PR and delegate tools all left the every-step budget, and the image and video tools share one settings schema.',+ 'A mode menu in the Code composer picks Ask permissions, Bypass permissions or Plan mode per conversation, with a global default in Settings. Bypass never lifts the cloud shell lock, and the menu says so.',+ 'Plan mode explores read only, writes the plan, then stops for your yes. Approve and run carries the whole plan out in the same run and never lands in Bypass on its own: the button shows the mode it will run in, and it shows you the real commands first.',+ 'The plan moved out of the prompt box into the right panel, live above the files.',+ 'The file explorer is a real tree you expand folder by folder, widen by dragging its edge, with the width remembered across a restart. Click a file to preview it: code with highlighting, images inline, HTML in a sandboxed frame with scripts off until you ask. node_modules, .git, target and dist stay out of the way.',+ 'A follow up in the same conversation stops re-attaching images from many messages back, so old pictures no longer ride along on every later step where nothing looks at them.',++ 'A chat database wiped by a hard crash is restored from the app\'s own backup on the next start, and the backup now merges with what it already held instead of overwriting it. Three things had to go wrong at once for chats to be lost for good, and the app was finishing that job itself seconds after every launch.',++ 'Browser voice recording reaches the transcriber again. The recorded audio was refused as the wrong body type before the handler ever saw it, and the request went out without the header every other call sends.',++ 'A link in an agent answer that no tool ever returned is labelled as unverified in the bubble, and after a real tool success the agent is asked once to look it up properly or take it back.',++ 'A long run\'s trim notice no longer plants a system message in the middle of the conversation, which strict chat templates refuse outright. That is the crash that only ever showed up once a chat had grown long.',++ 'The built in engine is restarted at the context an agent or coding run actually budgets for, instead of staying at its 8192 default while the prompt quietly overflowed it.',++ 'The engine\'s saved conversation cache follows the slot that really holds the tokens instead of always writing slot zero, and a render in Create, music or video now saves that state and brings every backend back warm afterwards instead of leaving the next chat turn to a cold start.',++ 'The LoRA trainer plans for an AMD card instead of reading a silent nvidia-smi as no GPU at all. On Linux it installs the ROCm build; on Windows and macOS it refuses before the clone and the 2.5 GB, because there is no wheel to install there.',++ 'A bundle card in the Model Manager reads its own download state instead of its neighbours\'. Video bundles share files, so one failed attempt used to put a Retry button on every card and hide bundles that were complete on disk.',++ 'A finished download in the Model Manager waits for ComfyUI to list the file before announcing it, so a model stops being missing from the Installed tab and every picker until you reload by hand.',+ ],+ },+ {+ title: 'Cloud',+ items: [+ 'Anthropic models sent with your own key carry prompt caching markers on the system block, the last tool and the last stable message, so a repeated request reads from the cache instead of paying for the whole prompt again.',+ 'The automatic memory step on LU Cloud only runs if you turn it on, and then on the cheapest capable model rather than the one you are chatting with, and at most every third turn. It used to run on the model you were chatting with, on every single round, whether you wanted it or not.',+ 'Group chat and A/B compare cap the history they send per model, the same as a normal chat, instead of sending the full shared thread to every model on every round.',++ 'A hosted chat that has grown past the server\'s message limit shrinks the request it sends and retries, instead of refusing every further turn. Before this, one long conversation was a permanent dead end and every new message only made the payload the server had just refused longer.',+ ],+ },+ ],+ },{version: '2.6.5',headline: 'Updating works again, and the work you started survives it',diff --cc vite.config.tsindex bbada347,def781e9..bdd6fde8--- a/vite.config.ts+++ b/vite.config.ts@@@ -12,7 -12,7 +12,8 @@@ import { dirname } from 'pathimport os from 'os'import dns from 'node:dns'import net from 'node:net'+import { devResolveWithinJail, effectiveByteCap, JailEscapeError } from './src/lib/dev-fs-jail'+ import { postContentTypeAllowed, postContentTypeError } from './src/lib/local-api-guard'// ── Dev-server SSRF guard ───────────────────────────────────────// The dev proxies that fetch a *user-supplied* ?url= (proxy-image,