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.

fix(agent): the cost brake counts what LU Cloud really billed, at full price until it knows (CA)

purpledd7531f6c4fb
diff --git a/src/api/agents/__tests__/the-architect-step-counts-toward-the-hour.test.ts b/src/api/agents/__tests__/the-architect-step-counts-toward-the-hour.test.ts
new file mode 100644
index 00000000..5dd117b2
--- /dev/null
+++ b/src/api/agents/__tests__/the-architect-step-counts-toward-the-hour.test.ts
@@ -0,0 +1,37 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// CA audit (14.11.2026): the Architect pass in Code is one paid model call
+// per plan, and it was the last agent step on LU Cloud outside the hour.
+const chatWithTools = vi.fn()
+vi.mock('../../providers', () => ({
+ getProviderForModel: (name: string) => ({ provider: { chatWithTools }, modelId: name }),
+}))
+vi.mock('../../../lib/agent-core/credit-rates', () => ({
+ creditRatesOf: (m: string) => (m === 'lu-cloud::paid' ? { inputPerMillion: 1_000, outputPerMillion: 4_000 } : null),
+ billingOf: () => undefined,
+}))
+
+import { planWithArchitect } from '../architect'
+import { _resetCreditLedger, hourCredits } from '../../../lib/agent-core/credit-ledger'
+
+beforeEach(() => {
+ chatWithTools.mockReset()
+ _resetCreditLedger()
+})
+
+describe('the Architect plan step', () => {
+ it('counts its credits toward the hour on a priced model', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: '## Plan', toolCalls: [], promptEvalCount: 20_000, evalCount: 1_000 })
+ await planWithArchitect({ model: 'lu-cloud::paid', userInstruction: 'x', workingDirectory: '/w' })
+ expect(hourCredits()).toBeCloseTo(24, 5) // 20k × 1000/M + 1k × 4000/M
+ })
+
+ it('counts nothing on a model without a price', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: '## Plan', toolCalls: [], promptEvalCount: 20_000, evalCount: 1_000 })
+ await planWithArchitect({ model: 'ollama::local', userInstruction: 'x', workingDirectory: '/w' })
+ expect(hourCredits()).toBe(0)
+ })
+})
diff --git a/src/api/agents/architect.ts b/src/api/agents/architect.ts
index 491c9a16..212772a9 100644
--- a/src/api/agents/architect.ts
+++ b/src/api/agents/architect.ts
@@ -74,10 +74,23 @@ export async function planWithArchitect(
...(input.recentMessages ?? []),
{ role: 'user', content: input.userInstruction },
]
- const { content } = await provider.chatWithTools(modelId, messages, [], {
+ const raw = await provider.chatWithTools(modelId, messages, [], {
temperature: input.temperature ?? 0.3,
signal: input.signal,
})
+ const { content } = raw
+ // The plan step is paid like any other step on LU Cloud and counts toward
+ // the hourly credit limit (CA, 14.11.2026). Accounting never breaks the plan.
+ try {
+ const { stepCredits, wireCloudSpent } = await import('../../lib/agent-cost-brake')
+ const { creditRatesOf, billingOf } = await import('../../lib/agent-core/credit-rates')
+ const { addHourCredits } = await import('../../lib/agent-core/credit-ledger')
+ const spent = stepCredits(creditRatesOf(input.model), raw.promptEvalCount, raw.evalCount, billingOf(raw))
+ if (spent > 0) {
+ if (import.meta.env?.MODE !== 'test') wireCloudSpent()
+ addHourCredits(spent)
+ }
+ } catch { /* counted nothing */ }
return {
// The plan is pasted into the EDITOR's system prompt verbatim, so a
// thinking model's reasoning would ride into every coding turn after it
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 3b6b84be..98a5d1fc 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -633,11 +633,12 @@ export async function defaultSubAgentRunner(
// (a test double, a phone without the catalogue) counts nothing.
let paused: string | null = null
try {
- const { stepCredits, HOUR_CREDIT_LIMIT } = await import('../../lib/agent-cost-brake')
+ const { stepCredits, HOUR_CREDIT_LIMIT, wireCloudSpent } = await import('../../lib/agent-cost-brake')
const { creditRatesOf, billingOf } = await import('../../lib/agent-core/credit-rates')
const { addHourCredits } = await import('../../lib/agent-core/credit-ledger')
const spent = stepCredits(creditRatesOf(laufmodell), raw.promptEvalCount, raw.evalCount, billingOf(raw))
if (spent > 0) {
+ if (import.meta.env?.MODE !== 'test') wireCloudSpent()
const hour = addHourCredits(spent)
const { useSettingsStore } = await import('../../stores/settingsStore')
const limit = useSettingsStore.getState().settings.agentHourCreditLimit ?? HOUR_CREDIT_LIMIT
diff --git a/src/lib/__tests__/the-cost-brake-counts-what-the-server-bills.test.ts b/src/lib/__tests__/the-cost-brake-counts-what-the-server-bills.test.ts
new file mode 100644
index 00000000..02f96780
--- /dev/null
+++ b/src/lib/__tests__/the-cost-brake-counts-what-the-server-bills.test.ts
@@ -0,0 +1,126 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ _resetCreditLedger, addHourCredits, creditFactor, hourCredits, reconcileNow, setSpentReader, FACTOR_FLOOR, RECONCILE_EVERY,
+} from '../agent-core/credit-ledger'
+import { AgentCostBrake } from '../agent-cost-brake'
+
+// CA bench, Kimi K2.6 on LU Cloud, 14.11.2026: the hour counted 1.6–2.7× what
+// the server billed (cached input is cheaper, and the server hides the cache
+// fields), so the brake paused at about half its limit.
+
+const T0 = 1_800_000_000_000
+let spent: number | null
+const reader = async () => spent
+
+beforeEach(() => {
+ _resetCreditLedger()
+ spent = 50_000
+})
+
+describe('the hour reconciles with the server', () => {
+ it('counts what the server billed once it has been asked', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0) // baseline 50,000
+ addHourCredits(3_000, T0 + 1_000)
+ addHourCredits(3_000, T0 + 2_000) // 6,000 estimated, at full price
+ spent = 53_000 // the server billed half
+ await reconcileNow(T0 + 3_000)
+ expect(hourCredits(T0 + 4_000)).toBeCloseTo(3_000, 0)
+ expect(creditFactor()).toBeCloseTo(0.5, 5)
+ // The next steps are priced at the measured factor.
+ addHourCredits(2_000, T0 + 5_000)
+ expect(hourCredits(T0 + 6_000)).toBeCloseTo(4_000, 0)
+ })
+
+ it('stays at full price without an answer', async () => {
+ setSpentReader(async () => null)
+ await reconcileNow(T0)
+ addHourCredits(12_000, T0 + 1_000)
+ await reconcileNow(T0 + 2_000)
+ expect(creditFactor()).toBe(1)
+ expect(hourCredits(T0 + 3_000)).toBe(12_000)
+ })
+
+ it('stays at full price when the request fails', async () => {
+ setSpentReader(async () => { throw new Error('offline') })
+ addHourCredits(12_000, T0)
+ await reconcileNow(T0 + 1_000)
+ expect(creditFactor()).toBe(1)
+ expect(hourCredits(T0 + 2_000)).toBe(12_000)
+ })
+
+ it('takes no measurement when the counter goes backwards (top-up, new month)', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0)
+ addHourCredits(12_000, T0 + 1_000)
+ spent = 10_000
+ await reconcileNow(T0 + 2_000)
+ expect(creditFactor()).toBe(1)
+ expect(hourCredits(T0 + 3_000)).toBe(12_000)
+ })
+
+ it('brakes earlier, never later, when the server billed more', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0)
+ addHourCredits(5_000, T0 + 1_000)
+ spent = 57_500 // a chat in between: 7,500 for 5,000 estimated
+ await reconcileNow(T0 + 2_000)
+ expect(hourCredits(T0 + 3_000)).toBeCloseTo(7_500, 0)
+ expect(creditFactor()).toBeCloseTo(1.5, 5)
+ })
+
+ it('never prices a step below the floor', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0)
+ addHourCredits(5_000, T0 + 1_000)
+ spent = 50_100 // implausibly cheap: a lagging counter
+ await reconcileNow(T0 + 2_000)
+ expect(creditFactor()).toBe(FACTOR_FLOOR)
+ expect(hourCredits(T0 + 3_000)).toBeCloseTo(5_000 * FACTOR_FLOOR, 0)
+ })
+
+ it('a lowering leaves the hour with the steps it lowered', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0)
+ addHourCredits(6_000, T0 + 1_000)
+ spent = 53_000
+ await reconcileNow(T0 + 30 * 60_000)
+ // An hour after the step, step and correction are both gone; a new step
+ // counts in full, not lowered by a correction that outlived its step.
+ addHourCredits(1_000, T0 + 61 * 60_000)
+ expect(hourCredits(T0 + 61 * 60_000)).toBeCloseTo(1_000 * creditFactor(), 0)
+ })
+
+ it('asks the server on its own every RECONCILE_EVERY estimated credits', async () => {
+ let asked = 0
+ setSpentReader(async () => { asked++; return spent })
+ addHourCredits(1, T0) // first step: asks for the baseline
+ await Promise.resolve(); await Promise.resolve()
+ addHourCredits(RECONCILE_EVERY - 10, T0 + 1)
+ expect(asked).toBe(1)
+ addHourCredits(20, T0 + 2)
+ await Promise.resolve(); await Promise.resolve()
+ expect(asked).toBe(2)
+ })
+})
+
+describe('the per-task limit uses the measured price', () => {
+ it('pauses at the limit, not at half of it', async () => {
+ setSpentReader(reader)
+ await reconcileNow(T0)
+ addHourCredits(5_000)
+ spent = 52_500
+ await reconcileNow()
+ expect(creditFactor()).toBeCloseTo(0.5, 5)
+ // 1M input tokens at 10 credits per million = 10 credits full price, 5 measured.
+ const brake = new AgentCostBrake({ paid: true, rates: { inputPerMillion: 10_000, outputPerMillion: 0 }, runCreditLimit: 15_000, hourCreditLimit: 0, runHaltTokens: 1e12 })
+ brake.record(1_000_000) // 10,000 full price → 5,000
+ brake.record(1_000_000) // → 10,000
+ expect(brake.take().action).not.toBe('halt')
+ brake.record(1_000_000) // → 15,000
+ expect(brake.take().action).toBe('halt')
+ })
+})
diff --git a/src/lib/agent-core/cloud-spent.ts b/src/lib/agent-core/cloud-spent.ts
new file mode 100644
index 00000000..70bc2110
--- /dev/null
+++ b/src/lib/agent-core/cloud-spent.ts
@@ -0,0 +1,38 @@
+/**
+ * What the LU Cloud account has spent, read from the server's own counter
+ * (CA, 14.11.2026). The credit ledger calibrates its full-price estimate
+ * against it (credit-ledger.ts, "Reconciling with the server").
+ *
+ * Spent = monthly credits used minus the top-up wallet: a step paid from the
+ * wallet lowers the wallet instead of raising `credits_used`. Buying credits
+ * or a new month moves this backwards, which the ledger reads as "no
+ * measurement" and keeps full price.
+ */
+import { getQuota } from '../../api/cloud/jobs'
+import { setSpentReader, type SpentReader } from './credit-ledger'
+
+const ASK_TIMEOUT_MS = 8_000
+
+export const luCloudSpent: SpentReader = async () => {
+ try {
+ const q = await Promise.race([
+ getQuota(),
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), ASK_TIMEOUT_MS)),
+ ])
+ const used = q?.used?.credits_used
+ if (typeof used !== 'number' || !Number.isFinite(used)) return null
+ const wallet = typeof q?.topup?.credits === 'number' && Number.isFinite(q.topup.credits) ? q.topup.credits : 0
+ return used - wallet
+ } catch {
+ return null
+ }
+}
+
+let wired = false
+
+/** Wires the reader once per app run; a second call keeps the baseline. */
+export function ensureCloudSpentReader(): void {
+ if (wired) return
+ wired = true
+ setSpentReader(luCloudSpent)
+}
diff --git a/src/lib/agent-core/credit-ledger.ts b/src/lib/agent-core/credit-ledger.ts
index 55d55269..5f9d9c07 100644
--- a/src/lib/agent-core/credit-ledger.ts
+++ b/src/lib/agent-core/credit-ledger.ts
@@ -20,7 +20,7 @@ function load(): State {
if (!raw) return { entries: [], pausedAt: null }
const s = JSON.parse(raw) as Partial<State>
return {
- entries: Array.isArray(s.entries) ? s.entries.filter((e) => typeof e?.at === 'number' && typeof e?.credits === 'number') : [],
+ entries: Array.isArray(s.entries) ? s.entries.filter((e) => typeof e?.at === 'number' && typeof e?.credits === 'number' && Number.isFinite(e.credits)) : [],
pausedAt: typeof s.pausedAt === 'number' ? s.pausedAt : null,
}
} catch {
@@ -39,14 +39,117 @@ function prune(s: State, now: number): State {
/** Add one step's credits; returns the sum over the last hour. */
export function addHourCredits(credits: number, now: number = Date.now()): number {
const s = prune(load(), now)
- if (credits > 0) s.entries.push({ at: now, credits })
+ if (credits > 0) {
+ // Priced at the learned factor (full price until the server has been
+ // asked once), and the full-price estimate goes to the reconciler.
+ s.entries.push({ at: now, credits: credits * recon.factor })
+ noteEstimate(credits, now)
+ }
save(s)
- return s.entries.reduce((a, e) => a + e.credits, 0)
+ return Math.max(0, s.entries.reduce((a, e) => a + e.credits, 0))
+}
+
+// ── Reconciling with the server (CA, 14.11.2026) ─────────────────────────
+//
+// The step price above is an upper bound: LU Cloud bills cached input for
+// less and strips the cache fields from its answer (cache-oracle.ts, a side
+// channel guard), so the app cannot see the discount. Measured on Kimi K2.6:
+// the ledger counted 1.6–2.7× what the server billed, so the brake paused at
+// about half its limit. The server's own counter is the truth; every
+// RECONCILE_EVERY estimated credits the ledger asks it, and corrects the
+// hour and the factor for the next steps by the real spend.
+//
+// Safe by construction: without an answer (offline, signed out, a failing
+// request, a month change or a top-up in between) nothing changes and every
+// step stays at full price. The factor never drops below FACTOR_FLOOR, and a
+// real spend ABOVE the estimate (a chat or a render in between) raises it,
+// which brakes earlier, never later.
+
+export const RECONCILE_EVERY = 10_000
+export const FACTOR_FLOOR = 0.4
+const FACTOR_CEIL = 2
+
+/** What the server says this account has spent, in credits; null when unknown. */
+export type SpentReader = () => Promise<number | null>
+
+interface Recon {
+ factor: number
+ reader: SpentReader | null
+ baseline: number | null
+ estimatedSince: number
+ pricedSince: number
+ /** When the first step since the baseline was counted. */
+ sinceAt: number | null
+ inFlight: boolean
+}
+const recon: Recon = { factor: 1, reader: null, baseline: null, estimatedSince: 0, pricedSince: 0, sinceAt: null, inFlight: false }
+
+/** The account spend counter, e.g. from LU Cloud's quota answer. */
+export function setSpentReader(reader: SpentReader | null): void {
+ recon.reader = reader
+ recon.baseline = null
+ recon.estimatedSince = 0
+ recon.pricedSince = 0
+ recon.sinceAt = null
+}
+
+/** Real price per estimated credit, as last measured; 1 until measured. */
+export function creditFactor(): number {
+ return recon.factor
+}
+
+function noteEstimate(credits: number, now: number): void {
+ if (!recon.reader) return
+ if (recon.sinceAt === null) recon.sinceAt = now
+ recon.estimatedSince += credits
+ recon.pricedSince += credits * recon.factor
+ if (recon.baseline === null || recon.estimatedSince >= RECONCILE_EVERY) void reconcileNow()
+}
+
+/** Ask the server now; resolves when the answer is applied (or dropped). */
+export async function reconcileNow(now: number = Date.now()): Promise<void> {
+ if (!recon.reader || recon.inFlight) return
+ recon.inFlight = true
+ try {
+ const spent = await recon.reader().catch(() => null)
+ if (typeof spent !== 'number' || !Number.isFinite(spent)) return
+ if (recon.baseline === null) {
+ // First answer: the starting point. Steps before it stay at full price.
+ recon.baseline = spent
+ recon.estimatedSince = 0
+ recon.pricedSince = 0
+ recon.sinceAt = null
+ return
+ }
+ const real = spent - recon.baseline
+ const estimated = recon.estimatedSince
+ const priced = recon.pricedSince
+ const since = recon.sinceAt ?? now
+ recon.baseline = spent
+ recon.estimatedSince = 0
+ recon.pricedSince = 0
+ recon.sinceAt = null
+ // A month change or a top-up moves the counter backwards: no measurement.
+ if (real < 0 || estimated <= 0) return
+ recon.factor = Math.min(FACTOR_CEIL, Math.max(FACTOR_FLOOR, real / estimated))
+ // The hour gets the difference between what it counted and what was
+ // billed, bounded so the correction never takes it below the real spend.
+ // Stamped with the EARLIEST step it corrects: it leaves the hour no later
+ // than those steps do, so a lowering never outlives what it lowered.
+ const correction = Math.max(real, estimated * FACTOR_FLOOR) - priced
+ if (Math.abs(correction) >= 1) {
+ const s = prune(load(), now)
+ s.entries.push({ at: since, credits: correction })
+ save(s)
+ }
+ } finally {
+ recon.inFlight = false
+ }
}
/** Sum over the last hour, without adding. */
export function hourCredits(now: number = Date.now()): number {
- return prune(load(), now).entries.reduce((a, e) => a + e.credits, 0)
+ return Math.max(0, prune(load(), now).entries.reduce((a, e) => a + e.credits, 0))
}
/**
@@ -66,4 +169,7 @@ export function markHourPause(now: number = Date.now()): void {
/** Tests only. */
export function _resetCreditLedger(): void {
try { globalThis.localStorage?.removeItem(KEY) } catch { /* nothing to reset */ }
+ setSpentReader(null)
+ recon.factor = 1
+ recon.inFlight = false
}
diff --git a/src/lib/agent-cost-brake.ts b/src/lib/agent-cost-brake.ts
index 2becbfdf..85efe0be 100644
--- a/src/lib/agent-cost-brake.ts
+++ b/src/lib/agent-cost-brake.ts
@@ -1,6 +1,6 @@
import type { CreditRates } from '../api/providers/types'
import { HOSTED_CREDITS_PER_EUR } from './cloud-pitch'
-import { addHourCredits, hourPauseDue, markHourPause } from './agent-core/credit-ledger'
+import { addHourCredits, creditFactor, hourPauseDue, markHourPause } from './agent-core/credit-ledger'
/**
* Cost brake for one agent run (C83).
*
@@ -42,6 +42,11 @@ export const RUN_HALT_TOKENS = 2_000_000
export const RUN_CREDIT_LIMIT = 100_000
export const HOUR_CREDIT_LIMIT = 250_000
+/** Loaded lazily: the quota client pulls in the cloud API. */
+export function wireCloudSpent(): void {
+ void import('./agent-core/cloud-spent').then((m) => m.ensureCloudSpentReader()).catch(() => {})
+}
+
export type CostBrakeVerdict =
| { action: 'ok' }
| { action: 'warn'; message: string }
@@ -90,6 +95,9 @@ export class AgentCostBrake {
this.rates = opts.rates && opts.rates.inputPerMillion >= 0 && opts.rates.outputPerMillion >= 0 ? opts.rates : null
this.runCreditLimit = opts.runCreditLimit ?? RUN_CREDIT_LIMIT
this.hourCreditLimit = opts.hourCreditLimit ?? HOUR_CREDIT_LIMIT
+ // A declared credit price means LU Cloud: let the ledger ask the server
+ // what the steps really cost. Unit tests wire their own reader.
+ if (this.paid && this.rates && import.meta.env?.MODE !== 'test') wireCloudSpent()
}
/** Credits this run used so far, upper bound; 0 without a declared price. */
@@ -117,7 +125,10 @@ export class AgentCostBrake {
if (this.rates && extra.billing !== 'flash') {
const out = typeof extra.output === 'number' && extra.output > 0 ? extra.output : 0
const step = (n * this.rates.inputPerMillion + out * this.rates.outputPerMillion) / 1_000_000
- this.credits += step
+ // At the price the server really charged lately (creditFactor, 1 until
+ // it has been asked, see credit-ledger.ts), so the pause comes at the
+ // limit and not at half of it.
+ this.credits += step * creditFactor()
const hour = addHourCredits(step)
if (this.mayHalt && this.runCreditLimit > 0 && this.credits >= this.runCreditLimit) {
this.pending = {