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.

Show Flash allowance and credit fallback in chat

David84575f08d53c
diff --git a/e2e/flash-chat-billing.spec.ts b/e2e/flash-chat-billing.spec.ts
new file mode 100644
index 00000000..8150ab6e
--- /dev/null
+++ b/e2e/flash-chat-billing.spec.ts
@@ -0,0 +1,53 @@
+import { test, expect } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'
+
+test('flash metadata and paid fallback reach the actual desktop composer', async ({ page }) => {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME })
+ await seedOnboardingDone(page)
+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })
+ const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'authorization, content-type',
+ 'access-control-expose-headers': 'x-lu-chat-billing, x-lu-flash-remaining' }
+ await page.route('**/api/inference/v1/models', (route) => route.fulfill({ status: 200, headers: cors,
+ contentType: 'application/json', body: JSON.stringify({ object: 'list', data: [{
+ id: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo', name: 'Llama 3.1 8B Turbo',
+ context_length: 131072, supports_tools: true, think: 'never', usage_class: 'flash',
+ flash: { daily_tokens: 50000, default_max_output: 8192, request_seconds: 240, sessions_only: true, concurrent_requests: 1 },
+ }] }),
+ }))
+ let requests = 0
+ await page.route('**/api/inference/v1/chat/completions', (route) => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers: cors })
+ requests++
+ const content = `Flash browser proof ${requests}.`
+ return route.fulfill({ status: 200, headers: { ...cors,
+ 'x-lu-chat-billing': requests === 1 ? 'flash' : 'credits', 'x-lu-flash-remaining': requests === 1 ? '41000' : '0',
+ }, contentType: 'text/event-stream', body:
+ `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content } }] })}\n\ndata: [DONE]\n\n`,
+ })
+ })
+ await page.goto('/')
+ await expect(cloudSwitch(page)).toBeVisible()
+ await signInViaGate(page)
+ await expect(cloudSwitch(page)).toBeChecked()
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await page.getByRole('button', { name: 'Select chat model', exact: true }).click()
+ const row = page.getByRole('button', { name: /Llama 3.1 8B Turbo/ })
+ await expect(row.getByText('Flash', { exact: true })).toBeVisible()
+ await row.click()
+ await expect(page.getByTestId('flash-chat-notice')).toContainText('50,000 input and output tokens')
+ const composer = page.locator('textarea').first()
+ await composer.fill('Say hello')
+ await composer.press('Enter')
+ await expect(page.getByTestId('flash-chat-notice').getByRole('status')).toContainText('41,000')
+ await expect(page.getByText('Flash browser proof 1.', { exact: true })).toBeVisible()
+ await expect(async () => {
+ if (requests < 2) {
+ await composer.fill('Say hello again')
+ await composer.press('Enter')
+ }
+ expect(requests).toBe(2)
+ }).toPass({ timeout: 10000 })
+ await expect(page.getByTestId('flash-chat-notice').getByRole('alert')).toContainText('uses credits')
+ await expect(page.getByText('Flash browser proof 2.', { exact: true })).toBeVisible()
+})
diff --git a/src/api/providers/__tests__/flash-metadata.test.ts b/src/api/providers/__tests__/flash-metadata.test.ts
new file mode 100644
index 00000000..acd37349
--- /dev/null
+++ b/src/api/providers/__tests__/flash-metadata.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { OpenAIProvider } from '../openai-provider'
+import { useFlashBillingStore } from '../../../lib/flash-ui'
+
+vi.mock('../../backend', () => ({
+ localFetch: vi.fn(async () => new Response('{}', { status: 404 })),
+ localFetchStream: vi.fn(), isPrivateOrLanHost: () => false,
+ isDirectFetchAllowed: () => true, hostnameOf: (url: string) => new URL(url).hostname,
+ ensureProxyAllowsHost: vi.fn(), backendCall: vi.fn(), isTauri: () => false,
+}))
+const base = 'https://lu-labs.ai/api/inference/v1'
+const model = 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'
+const provider = (apiKey = '') => new OpenAIProvider({
+ id: 'openai', name: 'LU Cloud', enabled: true, isLocal: false, apiKey, baseUrl: base,
+})
+const entry = {
+ id: model, name: 'Llama 3.1 8B Turbo', context_length: 131072, usage_class: 'flash',
+ flash: { daily_tokens: 50000, default_max_output: 8192, request_seconds: 240, sessions_only: true, concurrent_requests: 1 },
+}
+beforeEach(() => useFlashBillingStore.setState({ entries: {} }))
+afterEach(() => vi.unstubAllGlobals())
+
+describe('flash metadata through the real provider adapter', () => {
+ it('carries validated policy from the models response', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [entry] }))))
+ const models = await provider().listModels()
+ expect(models[0].flash).toEqual({ dailyTokens: 50000, defaultMaxOutput: 8192, requestSeconds: 240, billingKey: base + '|' + model })
+ })
+ it('never labels a personal API-key connection as free', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [entry] }))))
+ expect((await provider('lu_test_fixture').listModels())[0].flash).toBeUndefined()
+ })
+ it('leaves older catalog responses unmarked', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [{ id: model }] }))))
+ expect((await provider().listModels())[0].flash).toBeUndefined()
+ })
+ it('records the paid fallback before reporting a failed wallet check', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'credits exhausted' }), {
+ status: 429, headers: { 'x-lu-chat-billing': 'credits', 'x-lu-flash-remaining': '0' },
+ })))
+ await expect(provider().chatWithTools(model, [{ role: 'user', content: 'Hello' }], [])).rejects.toThrow()
+ expect(useFlashBillingStore.getState().entries[base + '|' + model]).toEqual({ billing: 'credits', remaining: 0, ok: false })
+ })
+})
+
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index b04605bc..fb8b31a8 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -1,3 +1,5 @@
+import { parseFlashPolicy, recordFlashResponse } from '../../lib/flash-ui'
+
/**
* OpenAI-Compatible Provider
*
@@ -108,6 +110,8 @@ type ChatFetcher = (
) => Promise<Response>
interface OpenAIModelEntry {
+ flash?: unknown
+ usage_class?: unknown
id: string
object: string
created?: number
@@ -154,6 +158,8 @@ function toModelEntry(m: Record<string, unknown>): OpenAIModelEntry {
created: asNumber(m.created),
owned_by: asString(m.owned_by),
name: asString(m.name),
+ flash: m.flash,
+ usage_class: m.usage_class,
context_length: asNumber(m.context_length),
input_modalities: Array.isArray(m.input_modalities)
? m.input_modalities.filter((x): x is string => typeof x === 'string')
@@ -590,6 +596,7 @@ export class OpenAIProvider implements ProviderClient {
else if (survived !== asked) this.rememberEffort(memoryKey, lane, 'minimal')
}
+ recordFlashResponse(this.catalogKey(model), res)
return res
}
@@ -1005,6 +1012,7 @@ export class OpenAIProvider implements ProviderClient {
: (serverTools ?? m.supports_tools ?? true),
supportsVision: m.input_modalities?.includes('image') || undefined,
thinkMode: m.think,
+ flash: this.config.apiKey?.startsWith('lu_') ? undefined : parseFlashPolicy(m.flash, m.usage_class, this.catalogKey(m.id)),
effortLevels: m.reasoning_effort_levels,
effortDefault: m.reasoning_effort_default,
}
@@ -1031,6 +1039,7 @@ export class OpenAIProvider implements ProviderClient {
supportsTools: m.supports_tools ?? true,
supportsVision: m.input_modalities?.includes('image') || undefined,
thinkMode: m.think,
+ flash: this.config.apiKey?.startsWith('lu_') ? undefined : parseFlashPolicy(m.flash, m.usage_class, this.catalogKey(m.id)),
// Straight through, no invention: a server that does not declare the
// ladder leaves both undefined, and undefined is what switches the
// whole effort feature off for this model.
diff --git a/src/api/providers/types.ts b/src/api/providers/types.ts
index b9ef680a..ce6f0d05 100644
--- a/src/api/providers/types.ts
+++ b/src/api/providers/types.ts
@@ -104,6 +104,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
// ── Model ──────────────────────────────────────────────────────
export interface ProviderModel {
+ flash?: import('../../lib/flash-ui').FlashPolicy
id: string // Model ID as provider knows it (e.g. "gpt-4o", "claude-sonnet-4-20250514")
name: string // Display name
provider: ProviderId
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 95f54007..17b62ba4 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -2,6 +2,7 @@ import { useState, useRef, useEffect, useCallback, type ReactNode } from 'react'
import { Send, Square, Paperclip, X, Brain, Gauge, Terminal } from 'lucide-react'
import { matchAgentCommands, type AgentCommand, type CommandScope } from '../../lib/agent-commands'
import { VoiceButton } from './VoiceButton'
+import { FlashChatNotice } from './FlashChatNotice'
import { ApprovalDialog } from './ApprovalDialog'
import { useVoiceStore } from '../../stores/voiceStore'
import { useSettingsStore } from '../../stores/settingsStore'
@@ -362,6 +363,7 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp
return (
<div className={`px-3 pb-2 pt-1 w-full ${COMPOSER_MAX_W} mx-auto`}>
+ <FlashChatNotice />
{/* Approval used to live here as a popup over the chat input.
Per user feedback ("eventuell in den chat einarbeiten") it now
renders INSIDE the pending tool-call block in MessageList, so
diff --git a/src/components/chat/FlashChatNotice.tsx b/src/components/chat/FlashChatNotice.tsx
new file mode 100644
index 00000000..840b8626
--- /dev/null
+++ b/src/components/chat/FlashChatNotice.tsx
@@ -0,0 +1,35 @@
+import { useModelStore } from '../../stores/modelStore'
+import { useFlashBillingStore } from '../../lib/flash-ui'
+
+export function FlashChatNotice() {
+ const active = useModelStore((s) => s.models.find((m) => m.name === s.activeModel))
+ const policy = active && 'flash' in active ? active.flash : undefined
+ const notice = useFlashBillingStore((s) => policy ? s.entries[policy.billingKey] : undefined)
+ if (!policy) return null
+ return (
+ <div className="mb-2 text-xs text-gray-500" data-testid="flash-chat-notice">
+ <details>
+ <summary className="cursor-pointer">Flash: {policy.dailyTokens.toLocaleString('en-US')} input and output tokens per UTC day without credits</summary>
+ <p className="mt-1">
+ One free request at a time per account. Resets at 00:00 UTC. API keys always use credits.
+ A request that exceeds the remaining allowance uses credits instead.
+ Without an explicit output limit, free requests allow up to {policy.defaultMaxOutput.toLocaleString('en-US')} output tokens.
+ Each free request lasts at most {policy.requestSeconds} seconds.
+ The request budget is reserved before generation. Failed or interrupted requests without final usage keep that reservation.
+ </p>
+ </details>
+ {notice?.billing === 'credits' && (
+ <p role="alert" className="mt-1 text-gray-700 dark:text-gray-200">
+ {notice.ok ? 'This request uses credits instead of the free Flash allowance.' : 'This request requires credits. No generation started.'}
+ {' '}Its token budget exceeds the available allowance.
+ </p>
+ )}
+ {notice?.billing === 'flash' && (
+ <p role="status" className="mt-1">
+ Free Flash request. Remaining after reservation: {notice.remaining.toLocaleString('en-US')} tokens.
+ </p>
+ )}
+ </div>
+ )
+}
+
diff --git a/src/components/chat/__tests__/flash-chat-notice.test.ts b/src/components/chat/__tests__/flash-chat-notice.test.ts
new file mode 100644
index 00000000..58a2f20d
--- /dev/null
+++ b/src/components/chat/__tests__/flash-chat-notice.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import { createElement } from 'react'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { FlashChatNotice } from '../FlashChatNotice'
+import { useModelStore } from '../../../stores/modelStore'
+import { parseFlashPolicy, recordFlashResponse, useFlashBillingStore } from '../../../lib/flash-ui'
+
+const wire = { daily_tokens: 50000, default_max_output: 8192, request_seconds: 240, sessions_only: true, concurrent_requests: 1 }
+const policy = parseFlashPolicy(wire, 'flash', 'test-endpoint|model')!
+beforeEach(() => {
+ useFlashBillingStore.setState({ entries: {} })
+ useModelStore.setState({ activeModel: 'test-model', models: [{
+ name: 'test-model', model: 'test-model', size: 0, type: 'text', provider: 'openai', providerName: 'Test', flash: policy,
+ }] })
+})
+afterEach(cleanup)
+
+describe('visible flash policy and billing', () => {
+ it('publishes the server-provided limits before a request', () => {
+ render(createElement(FlashChatNotice))
+ fireEvent.click(screen.getByText(/50,000 input and output tokens/))
+ expect(screen.getByText(/API keys always use credits/).textContent).toContain('8,192')
+ expect(screen.getByText(/API keys always use credits/).textContent).toContain('240 seconds')
+ expect(screen.getByText(/API keys always use credits/).textContent).toContain('00:00 UTC')
+ })
+ it('renders a persistent paid-fallback alert from response headers', () => {
+ render(createElement(FlashChatNotice))
+ act(() => recordFlashResponse(policy.billingKey, new Response('', { headers: {
+ 'x-lu-chat-billing': 'credits', 'x-lu-flash-remaining': '0',
+ } })))
+ expect(screen.getByRole('alert').textContent).toContain('This request uses credits')
+ })
+ it('does not claim a failed credit check started generation', () => {
+ render(createElement(FlashChatNotice))
+ act(() => recordFlashResponse(policy.billingKey, new Response('', { status: 429, headers: {
+ 'x-lu-chat-billing': 'credits', 'x-lu-flash-remaining': '0',
+ } })))
+ expect(screen.getByRole('alert').textContent).toContain('No generation started')
+ })
+ it('labels remaining tokens as a reservation, not final usage', () => {
+ render(createElement(FlashChatNotice))
+ act(() => recordFlashResponse(policy.billingKey, new Response('', { headers: {
+ 'x-lu-chat-billing': 'flash', 'x-lu-flash-remaining': '12345',
+ } })))
+ expect(screen.getByRole('status').textContent).toContain('Remaining after reservation: 12,345')
+ })
+ it('does not show a notice for another endpoint or model', () => {
+ recordFlashResponse('other|model', new Response('', { headers: { 'x-lu-chat-billing': 'credits', 'x-lu-flash-remaining': '0' } }))
+ render(createElement(FlashChatNotice))
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+ it('offers no free usage claim when an old backend omits metadata', () => {
+ const row = useModelStore.getState().models[0]
+ if (!('flash' in row)) throw new Error('Expected the flash model fixture')
+ useModelStore.setState({ models: [{ ...row, flash: undefined }] })
+ render(createElement(FlashChatNotice))
+ expect(screen.queryByTestId('flash-chat-notice')).toBeNull()
+ expect(parseFlashPolicy(undefined, undefined, 'key')).toBeUndefined()
+ })
+ it('rejects malformed policy and billing metadata', () => {
+ expect(parseFlashPolicy({ ...wire, daily_tokens: -1 }, 'flash', 'key')).toBeUndefined()
+ expect(parseFlashPolicy({ ...wire, sessions_only: false }, 'flash', 'key')).toBeUndefined()
+ expect(parseFlashPolicy(wire, 'anything', 'key')).toBeUndefined()
+ recordFlashResponse(policy.billingKey, new Response('', { headers: { 'x-lu-chat-billing': 'credits' } }))
+ expect(useFlashBillingStore.getState().entries).toEqual({})
+ })
+})
diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsx
index 5d3df429..b6aff651 100644
--- a/src/components/models/ModelSelector.tsx
+++ b/src/components/models/ModelSelector.tsx
@@ -1407,6 +1407,7 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy
{nameEnde && <span className="shrink-0">{nameEnde}</span>}
</span>
+ {'flash' in model && model.flash && <span className="t-micro text-emerald-600 dark:text-emerald-400" title="Session-only free allowance. See the chat composer for daily limits.">Flash</span>}
{/* Subtle meta */}
{model.type !== 'text' && (
<span className={`text-[0.5rem] uppercase font-medium tracking-wide ${TYPE_COLOR[model.type] || 'text-gray-500'} opacity-60`}>
diff --git a/src/lib/cloud-model-row.ts b/src/lib/cloud-model-row.ts
index 9161cfd7..a5b9f2a4 100644
--- a/src/lib/cloud-model-row.ts
+++ b/src/lib/cloud-model-row.ts
@@ -17,6 +17,7 @@ export function cloudModelRow(pm: ProviderModel): CloudModel {
return {
name: prefixModelName(pm.provider, pm.id),
model: pm.id,
+ flash: pm.flash,
size: 0,
type: 'text',
provider: pm.provider,
diff --git a/src/lib/flash-ui.ts b/src/lib/flash-ui.ts
new file mode 100644
index 00000000..013af576
--- /dev/null
+++ b/src/lib/flash-ui.ts
@@ -0,0 +1,40 @@
+import { create } from 'zustand'
+
+export interface FlashPolicy {
+ dailyTokens: number
+ defaultMaxOutput: number
+ requestSeconds: number
+ billingKey: string
+}
+
+export function parseFlashPolicy(value: unknown, usageClass: unknown, billingKey: string): FlashPolicy | undefined {
+ if (usageClass !== 'flash' || !value || typeof value !== 'object') return undefined
+ const v = value as Record<string, unknown>
+ const positive = (n: unknown): n is number => typeof n === 'number' && Number.isSafeInteger(n) && n > 0 && n <= 10_000_000
+ if (v.sessions_only !== true || v.concurrent_requests !== 1 || !positive(v.daily_tokens)
+ || !positive(v.default_max_output) || !positive(v.request_seconds)) return undefined
+ return { dailyTokens: v.daily_tokens, defaultMaxOutput: v.default_max_output, requestSeconds: v.request_seconds, billingKey }
+}
+
+interface BillingNotice {
+ billing: 'flash' | 'credits'
+ remaining: number
+ ok: boolean
+}
+export const useFlashBillingStore = create<{ entries: Record<string, BillingNotice> }>(() => ({ entries: {} }))
+
+export function recordFlashResponse(billingKey: string, response: Response): void {
+ const billing = response.headers.get('x-lu-chat-billing')
+ const raw = response.headers.get('x-lu-flash-remaining')
+ const remaining = raw === null ? NaN : Number(raw)
+ if ((billing !== 'flash' && billing !== 'credits') || !Number.isSafeInteger(remaining) || remaining < 0) return
+ useFlashBillingStore.setState((s) => {
+ const entries = { ...s.entries }
+ delete entries[billingKey]
+ const keys = Object.keys(entries)
+ if (keys.length >= 32) delete entries[keys[0]]
+ entries[billingKey] = { billing, remaining, ok: response.ok }
+ return { entries }
+ })
+}
+
diff --git a/src/types/models.ts b/src/types/models.ts
index 027f5da9..f049ebb9 100644
--- a/src/types/models.ts
+++ b/src/types/models.ts
@@ -24,6 +24,7 @@ export interface OllamaModel {
// Cloud text model (OpenAI-compat or Anthropic) — lighter than OllamaModel
export interface CloudModel {
+ flash?: import('../lib/flash-ui').FlashPolicy
name: string
model: string
size: number