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(cloud): full LU Cloud tier — cloud GPU rendering + cloud chat, no bridge
purple50d6b0870744
diff --git a/package-lock.json b/package-lock.jsonindex 0b0295ed..7fbfcad9 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,16 +1,17 @@{"name": "locally-uncensored",- "version": "2.5.4",+ "version": "2.5.5","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "locally-uncensored",- "version": "2.5.4",+ "version": "2.5.5","license": "AGPL-3.0","dependencies": {"@react-three/drei": "^10.7.7","@react-three/fiber": "^9.5.0",+ "@supabase/supabase-js": "^2.110.0","@tailwindcss/vite": "^4.2.2","@tauri-apps/plugin-shell": "^2.3.5","@tauri-apps/plugin-updater": "^2.10.1",@@ -1235,6 +1236,90 @@"dev": true,"license": "MIT"},+ "node_modules/@supabase/auth-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.0.tgz",+ "integrity": "sha512-Mi288WCTp6wxMFCOu/UgzgHEXODjdl2uVTLqK11eanzGZaldU3RyP8Am+ZbNuVzFP+5+iOvppxzv7N5Ym84xTg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@supabase/functions-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.110.0.tgz",+ "integrity": "sha512-Fde5wlY8ZZy+9yqrWlQHo8MacSyUBArBEtN2boB4thJQigPnQD/cc61qZN0n3I1L0gwhWtHYwIMnOBKxSvF6Hw==",+ "license": "MIT",+ "dependencies": {+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@supabase/phoenix": {+ "version": "0.4.4",+ "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.4.tgz",+ "integrity": "sha512-Gt0pqoXuIqX/8dvG0OKp/wMCobXNH3klNbUPBNyOfN0YA1IswrM3HyWFMOPk1Jy+BRaIyDPcFx4jLBwHNmlyfQ==",+ "license": "MIT"+ },+ "node_modules/@supabase/postgrest-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.110.0.tgz",+ "integrity": "sha512-ZbC1QZL3jcvBUfVKjJbgRM27G4Mg3Zzqdm44m5pJafe1e52Cli793EOnwQucomBAGEUDd03Nzaf7XV3ji/XexQ==",+ "license": "MIT",+ "dependencies": {+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@supabase/realtime-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.110.0.tgz",+ "integrity": "sha512-Wn2AWpneZuDFTkp/65tqctvoh+3JvyTjMam8sTMqVWy5BgkU8zAvFwilPYPPPhkINeKF8NAJKP7FclJ2iGCUMw==",+ "license": "MIT",+ "dependencies": {+ "@supabase/phoenix": "0.4.4",+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@supabase/storage-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.110.0.tgz",+ "integrity": "sha512-71+gU3HrhiylAhftY6FmO5PPdcsScnVcS766CVD+vTYK9qTDLbrx8FhgBYbqGm3iV/wkTfzrNJfjGsMeFRkJRQ==",+ "license": "MIT",+ "dependencies": {+ "iceberg-js": "^0.8.1",+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@supabase/supabase-js": {+ "version": "2.110.0",+ "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.110.0.tgz",+ "integrity": "sha512-8yI84VJiEVW4zxZpLUmxXmjzQ7O2St9X/ymzlBETDHTURPWG3LmvbSiibq+7dqAJmyoUfxZnSfXeM4HCM8s4XQ==",+ "license": "MIT",+ "dependencies": {+ "@supabase/auth-js": "2.110.0",+ "@supabase/functions-js": "2.110.0",+ "@supabase/postgrest-js": "2.110.0",+ "@supabase/realtime-js": "2.110.0",+ "@supabase/storage-js": "2.110.0"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },"node_modules/@tailwindcss/node": {"version": "4.2.2","resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.2.tgz",@@ -3657,6 +3742,15 @@"url": "https://opencollective.com/unified"}},+ "node_modules/iceberg-js": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/ieee754": {"version": "1.2.1","resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",diff --git a/package.json b/package.jsonindex d9d3647c..1b976057 100644--- a/package.json+++ b/package.json@@ -36,6 +36,7 @@"dependencies": {"@react-three/drei": "^10.7.7","@react-three/fiber": "^9.5.0",+ "@supabase/supabase-js": "^2.110.0","@tailwindcss/vite": "^4.2.2","@tauri-apps/plugin-shell": "^2.3.5","@tauri-apps/plugin-updater": "^2.10.1",diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 20f04769..3568705a 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -24,7 +24,7 @@}],"security": {- "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com ws://localhost:8188 ws://127.0.0.1:8188; img-src 'self' data: blob: http://localhost:8188 http://127.0.0.1:8188 https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:8188 http://127.0.0.1:8188; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'"+ "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://*.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com ws://localhost:8188 ws://127.0.0.1:8188; img-src 'self' data: blob: http://localhost:8188 http://127.0.0.1:8188 https://*.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:8188 http://127.0.0.1:8188 https://*.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'"}},"plugins": {diff --git a/src/api/cloud/__tests__/cloud-client.test.ts b/src/api/cloud/__tests__/cloud-client.test.tsnew file mode 100644index 00000000..e0b7d1d5--- /dev/null+++ b/src/api/cloud/__tests__/cloud-client.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Cloud client: bearer injection, base-URL prefixing, error mapping, and the+// jobs wrappers on top. getAccessToken is mocked (no live Supabase); fetch is+// stubbed per test.++const { getAccessToken } = vi.hoisted(() => ({ getAccessToken: vi.fn() }))+vi.mock('../supabase', () => ({ getAccessToken }))++import { cloudFetch, jsonOrError, CloudJobError } from '../client'+import { submitCloudJob, uploadInput, getJob, getQuota } from '../jobs'+import { CLOUD_BASE } from '../config'++const fetchMock = vi.fn()++beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('fetch', fetchMock)+ getAccessToken.mockResolvedValue('tok-123')+})++function jsonRes(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ })+}++describe('cloudFetch', () => {+ it('prefixes CLOUD_BASE and injects the bearer token', async () => {+ fetchMock.mockResolvedValue(jsonRes({ ok: true }))+ await cloudFetch('/api/me')+ expect(fetchMock).toHaveBeenCalledOnce()+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toBe(`${CLOUD_BASE}/api/me`)+ expect(new Headers(init.headers).get('authorization')).toBe('Bearer tok-123')+ })++ it('throws a 401 CloudJobError when signed out (no network call)', async () => {+ getAccessToken.mockResolvedValue(null)+ await expect(cloudFetch('/api/me')).rejects.toMatchObject({+ name: 'CloudJobError',+ status: 401,+ })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('preserves method, body and extra headers', async () => {+ fetchMock.mockResolvedValue(jsonRes({}))+ await cloudFetch('/api/jobs', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: '{"x":1}',+ })+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(init.method).toBe('POST')+ expect(init.body).toBe('{"x":1}')+ expect(new Headers(init.headers).get('content-type')).toBe('application/json')+ })+})++describe('jsonOrError', () => {+ it('returns the parsed body on 2xx', async () => {+ await expect(jsonOrError(jsonRes({ id: 'j1' }, 202))).resolves.toEqual({ id: 'j1' })+ })++ it('maps { error } bodies to CloudJobError with the status', async () => {+ const err = await jsonOrError(jsonRes({ error: 'monthly credit budget exhausted' }, 429)).catch(+ (e: unknown) => e,+ )+ expect(err).toBeInstanceOf(CloudJobError)+ expect((err as CloudJobError).status).toBe(429)+ expect((err as CloudJobError).message).toBe('monthly credit budget exhausted')+ })++ it('falls back to a generic message on non-JSON error bodies', async () => {+ const res = new Response('gateway timeout', { status: 504 })+ const err = await jsonOrError(res).catch((e: unknown) => e)+ expect((err as CloudJobError).message).toBe('request failed (504)')+ })+})++describe('jobs wrappers', () => {+ it('submitCloudJob posts the submit payload and returns id + quota', async () => {+ fetchMock.mockResolvedValue(jsonRes({ id: 'j1', quota: { cost: 5, used: 10, limit: 800 } }, 202))+ const out = await submitCloudJob({+ kind: 'image',+ model: 'sdxl-base-1.0',+ prompt: 'a lighthouse',+ params: { op: 'generate' },+ })+ expect(out.id).toBe('j1')+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toBe(`${CLOUD_BASE}/api/jobs`)+ expect(JSON.parse(String(init.body)).model).toBe('sdxl-base-1.0')+ })++ it('uploadInput sends multipart form-data with the role and returns the path', async () => {+ fetchMock.mockResolvedValue(jsonRes({ path: 'uid/abc.png', role: 'source' }, 201))+ const path = await uploadInput(new Blob(['x']), 'source')+ expect(path).toBe('uid/abc.png')+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toBe(`${CLOUD_BASE}/api/jobs/upload`)+ expect(init.body).toBeInstanceOf(FormData)+ expect((init.body as FormData).get('role')).toBe('source')+ })++ it('getJob unwraps { job } and encodes the id', async () => {+ fetchMock.mockResolvedValue(jsonRes({ job: { id: 'j 1', status: 'queued' } }))+ const job = await getJob('j 1')+ expect(job.id).toBe('j 1')+ expect(fetchMock.mock.calls[0][0]).toBe(`${CLOUD_BASE}/api/jobs/j%201`)+ })++ it('getQuota surfaces 402 (no license) as CloudJobError', async () => {+ fetchMock.mockResolvedValue(jsonRes({ error: 'no active license' }, 402))+ await expect(getQuota()).rejects.toMatchObject({ status: 402 })+ })+})diff --git a/src/api/cloud/client.ts b/src/api/cloud/client.tsnew file mode 100644index 00000000..036cc3cf--- /dev/null+++ b/src/api/cloud/client.ts@@ -0,0 +1,36 @@+// Fetch wrapper for the lu-labs.ai cloud APIs: prefixes CLOUD_BASE and+// injects the Supabase bearer token. Direct HTTPS from the WebView (no Tauri+// proxy — the CSP allowlists the cloud hosts, and the server side speaks+// CORS for Tauri origins).++import { CLOUD_BASE } from './config'+import { getAccessToken } from './supabase'++export class CloudJobError extends Error {+ readonly status: number+ constructor(message: string, status: number) {+ super(message)+ this.name = 'CloudJobError'+ this.status = status+ }+}++export async function jsonOrError<T>(res: Response): Promise<T> {+ const body = await res.json().catch(() => ({}))+ if (!res.ok) {+ const msg =+ typeof (body as { error?: unknown }).error === 'string'+ ? (body as { error: string }).error+ : `request failed (${res.status})`+ throw new CloudJobError(msg, res.status)+ }+ return body as T+}++export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {+ const token = await getAccessToken()+ if (!token) throw new CloudJobError('not signed in', 401)+ const headers = new Headers(init.headers)+ headers.set('authorization', `Bearer ${token}`)+ return fetch(`${CLOUD_BASE}${path}`, { ...init, headers })+}diff --git a/src/api/cloud/config.ts b/src/api/cloud/config.tsnew file mode 100644index 00000000..84455508--- /dev/null+++ b/src/api/cloud/config.ts@@ -0,0 +1,15 @@+// LU Cloud endpoints. The anon key is public by design (it only unlocks+// RLS-guarded, user-scoped access); real authorization is the user's session+// token. VITE_* overrides exist for developing against a local uselu server+// (`VITE_LU_CLOUD_URL=http://localhost:3000 npm run dev`).++export const CLOUD_BASE: string =+ (import.meta.env.VITE_LU_CLOUD_URL as string | undefined) ?? 'https://lu-labs.ai'++export const SUPABASE_URL: string =+ (import.meta.env.VITE_LU_SUPABASE_URL as string | undefined) ??+ 'https://lrrhheztdytyfpizvuup.supabase.co'++export const SUPABASE_ANON_KEY: string =+ (import.meta.env.VITE_LU_SUPABASE_ANON_KEY as string | undefined) ??+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxycmhoZXp0ZHl0eWZwaXp2dXVwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODMxNDkwNzUsImV4cCI6MjA5ODcyNTA3NX0.1AuX4tmup82d3NHLAgQx1KdXhwlCkPcX7liB6eNSkAU'diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.tsnew file mode 100644index 00000000..d0cd66fa--- /dev/null+++ b/src/api/cloud/jobs.ts@@ -0,0 +1,142 @@+// Desktop client for the hosted render queue — port of uselu's+// lib/render/cloud-jobs.ts fetch wrappers onto cloudFetch (bearer + base URL).+// Pure HTTP, no store access; useCloudCreate owns the store choreography.++import type { RenderKind, CloudQuota } from '../../lib/render/cloud-jobs'+import { cloudFetch, jsonOrError, CloudJobError } from './client'+import type { RenderOp } from '../../lib/render/cloud-jobs'++export interface CloudJobParams {+ op: RenderOp+ negative_prompt?: string+ width?: number+ height?: number+ steps?: number+ cfg?: number+ seed?: number+ frames?: number+ fps?: number+ denoise?: number+ grow_mask_by?: number+ source_path?: string+ mask_path?: string+}++export interface CloudJobSubmit {+ kind: RenderKind+ model: string+ prompt: string+ params: CloudJobParams+}++export interface CloudJob {+ id: string+ kind: RenderKind+ model: string+ provider: string | null+ status: 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled'+ result_url: string | null+ attestation: { quote: string; verify_url: string } | null+ cost_units: number+ created_at: string+ started_at?: string | null+ completed_at: string | null+ error: string | null+}++export interface CloudMe {+ user: { id: string; email?: string } | null+ license: { status: string }+}++/** Stage a source image or mask; returns the render-inputs storage path. */+export async function uploadInput(file: Blob, role: 'source' | 'mask'): Promise<string> {+ const form = new FormData()+ form.append('file', file, role === 'mask' ? 'mask.png' : 'source.png')+ form.append('role', role)+ const res = await cloudFetch('/api/jobs/upload', { method: 'POST', body: form })+ const { path } = await jsonOrError<{ path: string }>(res)+ return path+}++export async function submitCloudJob(+ submit: CloudJobSubmit,+): Promise<{ id: string; quota: { cost: number; used: number; limit: number } }> {+ const res = await cloudFetch('/api/jobs', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(submit),+ })+ return jsonOrError(res)+}++export async function getJob(id: string): Promise<CloudJob> {+ const res = await cloudFetch(`/api/jobs/${encodeURIComponent(id)}`)+ const { job } = await jsonOrError<{ job: CloudJob }>(res)+ return job+}++export async function cancelJob(id: string): Promise<{ status: string; refunded?: boolean }> {+ const res = await cloudFetch(`/api/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' })+ return jsonOrError(res)+}++export async function getQuota(): Promise<CloudQuota> {+ const res = await cloudFetch('/api/jobs/quota')+ return jsonOrError(res)+}++/** Account probe — logged-out is a valid state, not an error. */+export async function getMe(): Promise<CloudMe> {+ const res = await cloudFetch('/api/me')+ return jsonOrError(res)+}++/** Re-fetch the job for a fresh signed result URL (they expire ~1 h after the+ * last read; /api/jobs/[id] re-signs on every GET). Video gallery items keep+ * remoteUrl + jobId and refresh lazily through this. */+export async function refreshResultUrl(jobId: string): Promise<string | null> {+ try {+ const job = await getJob(jobId)+ return job.result_url+ } catch {+ return null+ }+}++const TERMINAL = new Set(['succeeded', 'failed', 'canceled'])++/** Poll until the job reaches a terminal state, the timeout hits, or the+ * AbortSignal fires. onTick fires on every poll with the fresh job. */+export async function pollJob(+ id: string,+ opts: {+ signal?: AbortSignal+ intervalMs?: number+ timeoutMs?: number+ onTick?: (job: CloudJob) => void+ } = {},+): Promise<CloudJob> {+ const intervalMs = opts.intervalMs ?? 2_500+ const deadline = Date.now() + (opts.timeoutMs ?? 15 * 60_000)+ for (;;) {+ if (opts.signal?.aborted) throw new CloudJobError('polling aborted', 0)+ const job = await getJob(id)+ opts.onTick?.(job)+ if (TERMINAL.has(job.status)) return job+ if (Date.now() >= deadline) throw new CloudJobError('render timed out', 0)+ await new Promise<void>((resolve) => {+ const t = setTimeout(resolve, intervalMs)+ opts.signal?.addEventListener(+ 'abort',+ () => {+ clearTimeout(t)+ resolve()+ },+ { once: true },+ )+ })+ }+}++export { CloudJobError }diff --git a/src/api/cloud/supabase.ts b/src/api/cloud/supabase.tsnew file mode 100644index 00000000..0b3a9db5--- /dev/null+++ b/src/api/cloud/supabase.ts@@ -0,0 +1,85 @@+// Supabase auth client for the LU Cloud tier. Desktop authenticates directly+// against Supabase (email+password) with the public anon key; the resulting+// access token is sent as `Authorization: Bearer` to the lu-labs.ai APIs.+//+// Session storage: OS keychain via the existing Rust `secret_*` commands+// (Windows Credential Manager / macOS Keychain) — survives the NSIS-update+// WebView2 wipe and keeps refresh tokens out of localStorage. Linux and the+// browser dev build fall back to localStorage (same tiering as providerStore).++import { createClient, type SupabaseClient } from '@supabase/supabase-js'+import { secretGet, secretSet, secretDelete } from '../backend'+import { SUPABASE_URL, SUPABASE_ANON_KEY } from './config'++const SESSION_ACCOUNT = 'lu-cloud-session'+const LOCAL_KEY = 'lu-cloud-session'++// Keychain-first async storage adapter. A single failed keychain call flips+// the adapter to localStorage for the rest of the session (Linux, web dev).+let keychainBroken = false++// There is exactly one session per app: the keychain path stores under a+// fixed account; the localStorage fallback keys by the (equally fixed)+// storageKey supabase passes in.+const keychainStorage = {+ async getItem(key: string): Promise<string | null> {+ if (!keychainBroken) {+ try {+ return await secretGet(SESSION_ACCOUNT)+ } catch {+ keychainBroken = true+ }+ }+ return localStorage.getItem(key)+ },+ async setItem(key: string, value: string): Promise<void> {+ if (!keychainBroken) {+ try {+ await secretSet(SESSION_ACCOUNT, value)+ return+ } catch {+ keychainBroken = true+ }+ }+ localStorage.setItem(key, value)+ },+ async removeItem(key: string): Promise<void> {+ if (!keychainBroken) {+ try {+ await secretDelete(SESSION_ACCOUNT)+ return+ } catch {+ keychainBroken = true+ }+ }+ localStorage.removeItem(key)+ },+}++let client: SupabaseClient | null = null++export function supabaseCloud(): SupabaseClient {+ if (!client) {+ client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {+ auth: {+ storage: keychainStorage,+ storageKey: LOCAL_KEY,+ persistSession: true,+ // Timers are throttled while the app is minimized/asleep, so we do+ // NOT rely on background refresh — getAccessToken() refreshes lazily+ // via getSession() on every use instead.+ autoRefreshToken: true,+ detectSessionInUrl: false,+ },+ })+ }+ return client+}++/** Current access token, refreshing an expired session if needed. Null when+ * logged out. Called per request — getSession() is cached in-memory and only+ * hits the network when the token actually expired. */+export async function getAccessToken(): Promise<string | null> {+ const { data } = await supabaseCloud().auth.getSession()+ return data.session?.access_token ?? null+}diff --git a/src/api/providers/lu-cloud-provider.ts b/src/api/providers/lu-cloud-provider.tsnew file mode 100644index 00000000..f2d4cf08--- /dev/null+++ b/src/api/providers/lu-cloud-provider.ts@@ -0,0 +1,75 @@+/**+ * LU Cloud Provider — OpenAI-compatible chat through the lu-labs.ai+ * confidential-inference proxy (`/api/inference/v1`).+ *+ * Thin composition over OpenAIProvider: the only difference is auth — the+ * bearer is the user's short-lived Supabase access token, refreshed per call+ * via getAccessToken(), never a static apiKey from the provider store.+ */++import type {+ ProviderClient, ProviderModel, ProviderConfig, ChatMessage, ChatOptions,+ ChatStreamChunk, ToolCall, ToolDefinition,+} from './types'+import { ProviderError } from './types'+import { OpenAIProvider } from './openai-provider'+import { getAccessToken } from '../cloud/supabase'++export class LuCloudProvider implements ProviderClient {+ readonly id = 'lu-cloud' as const+ private config: ProviderConfig++ constructor(config: ProviderConfig) {+ this.config = config+ }++ // Fresh delegate per call: the token rotates (~1 h), and OpenAIProvider+ // reads apiKey from its config. isLocal:false keeps it off the Rust proxy.+ private async delegate(): Promise<OpenAIProvider> {+ const token = await getAccessToken()+ if (!token) {+ throw new ProviderError('Sign in to your LU Cloud account to chat in the cloud.', 'lu-cloud', 'auth', 401)+ }+ return new OpenAIProvider({ ...this.config, apiKey: token, isLocal: false })+ }++ async *chatStream(+ model: string,+ messages: ChatMessage[],+ options?: ChatOptions,+ ): AsyncGenerator<ChatStreamChunk> {+ const inner = await this.delegate()+ yield* inner.chatStream(model, messages, options)+ }++ async chatWithTools(+ model: string,+ messages: ChatMessage[],+ tools: ToolDefinition[],+ options?: ChatOptions,+ ): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number }> {+ const inner = await this.delegate()+ return inner.chatWithTools(model, messages, tools, options)+ }++ async listModels(): Promise<ProviderModel[]> {+ const inner = await this.delegate()+ const models = await inner.listModels()+ // Rebrand: the delegate reports provider 'openai' — these are LU Cloud.+ return models.map((m) => ({ ...m, provider: this.id, providerName: 'LU Cloud' }))+ }++ async checkConnection(): Promise<boolean> {+ try {+ const inner = await this.delegate()+ return await inner.checkConnection()+ } catch {+ return false+ }+ }++ async getContextLength(model: string): Promise<number> {+ const inner = await this.delegate()+ return inner.getContextLength(model)+ }+}diff --git a/src/api/providers/registry.ts b/src/api/providers/registry.tsindex 1cc5177b..56e20292 100644--- a/src/api/providers/registry.ts+++ b/src/api/providers/registry.ts@@ -9,6 +9,7 @@ import type { ProviderId, ProviderClient, ProviderConfig } from './types'import { OllamaProvider } from './ollama-provider'import { OpenAIProvider } from './openai-provider'import { AnthropicProvider } from './anthropic-provider'+import { LuCloudProvider } from './lu-cloud-provider'import { useProviderStore } from '../../stores/providerStore'// ── Provider client cache ──────────────────────────────────────@@ -34,6 +35,8 @@ function createClient(config: ProviderConfig): ProviderClient {return new OpenAIProvider(config)case 'anthropic':return new AnthropicProvider(config)+ case 'lu-cloud':+ return new LuCloudProvider(config)default:throw new Error(`Unknown provider: ${config.id}`)}diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex c8e87257..870c101e 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -7,7 +7,7 @@// ── Provider Identity ──────────────────────────────────────────-export type ProviderId = 'ollama' | 'openai' | 'anthropic'+export type ProviderId = 'ollama' | 'openai' | 'anthropic' | 'lu-cloud'export interface ProviderConfig {id: ProviderIddiff --git a/src/components/auth/AccountPanel.tsx b/src/components/auth/AccountPanel.tsxnew file mode 100644index 00000000..f5965f37--- /dev/null+++ b/src/components/auth/AccountPanel.tsx@@ -0,0 +1,157 @@+// LU Cloud account panel (Settings → General). Signed out: inline+// email+password sign-in/sign-up. Signed in: email, tier, credits/token+// meters, manage-subscription (system browser), sign out. Enabling the cloud+// axis everywhere else (Create backend toggle, lu-cloud chat provider) hangs+// off the cloudAuthStore this panel drives via useCloudAuth.++import { useState } from 'react'+import { Loader2, LogOut, ExternalLink, Cloud } from 'lucide-react'+import { useCloudAuth } from '../../hooks/useCloudAuth'+import { useCloudAuthStore } from '../../stores/cloudAuthStore'+import { CLOUD_BASE } from '../../api/cloud/config'+import { openExternal } from '../../api/backend'++function Meter({ label, used, limit }: { label: string; used: number; limit: number }) {+ const pct = limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0+ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[0.65rem]">+ <span className="text-gray-600 dark:text-gray-400">{label}</span>+ <span className="text-gray-500 dark:text-gray-500 tabular-nums">+ {used.toLocaleString()} / {limit.toLocaleString()}+ </span>+ </div>+ <div className="h-1 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden">+ <div className="h-full rounded-full bg-gray-700 dark:bg-white/60" style={{ width: `${pct}%` }} />+ </div>+ </div>+ )+}++export function AccountPanel() {+ const { status, login, signup, logout } = useCloudAuth()+ const user = useCloudAuthStore((s) => s.user)+ const licenseActive = useCloudAuthStore((s) => s.licenseActive)+ const quota = useCloudAuthStore((s) => s.quota)++ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [mode, setMode] = useState<'signin' | 'signup'>('signin')+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)++ const submit = async (e: React.FormEvent) => {+ e.preventDefault()+ if (busy || !email || !password) return+ setBusy(true)+ setError(null)+ try {+ if (mode === 'signin') await login(email, password)+ else await signup(email, password)+ setPassword('')+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ } finally {+ setBusy(false)+ }+ }++ if (status === 'probing') {+ return (+ <div className="flex items-center gap-2 py-1 text-[0.7rem] text-gray-500">+ <Loader2 size={11} className="animate-spin" /> Checking account…+ </div>+ )+ }++ if (status === 'signed-out' || !user) {+ return (+ <form onSubmit={submit} className="space-y-2">+ <p className="text-[0.7rem] text-gray-600 dark:text-gray-400">+ Sign in to render images, video and chat on LU's cloud GPUs. Local features never need an account.+ </p>+ <input+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder="Email"+ autoComplete="email"+ className="w-full px-2 py-1.5 rounded text-[0.7rem] bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-gray-900 dark:text-gray-100 placeholder-gray-400 outline-none focus:border-gray-400 dark:focus:border-white/30"+ />+ <input+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Password"+ autoComplete={mode === 'signin' ? 'current-password' : 'new-password'}+ className="w-full px-2 py-1.5 rounded text-[0.7rem] bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-gray-900 dark:text-gray-100 placeholder-gray-400 outline-none focus:border-gray-400 dark:focus:border-white/30"+ />+ {error && <p className="text-[0.65rem] text-red-500 dark:text-red-400">{error}</p>}+ <div className="flex items-center gap-2">+ <button+ type="submit"+ disabled={busy || !email || !password}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded text-[0.7rem] font-medium bg-gray-900 text-white dark:bg-white dark:text-gray-900 disabled:opacity-40 hover:opacity-90 transition-opacity"+ >+ {busy ? <Loader2 size={11} className="animate-spin" /> : <Cloud size={11} />}+ {mode === 'signin' ? 'Sign in' : 'Create account'}+ </button>+ <button+ type="button"+ onClick={() => { setMode(mode === 'signin' ? 'signup' : 'signin'); setError(null) }}+ className="text-[0.65rem] text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"+ >+ {mode === 'signin' ? 'No account yet? Sign up' : 'Have an account? Sign in'}+ </button>+ </div>+ </form>+ )+ }++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <div>+ <div className="text-[0.7rem] text-gray-900 dark:text-gray-100">{user.email ?? user.id}</div>+ <div className="text-[0.65rem] text-gray-500">+ {licenseActive ? `Plan: ${quota?.tier ?? 'active'}` : 'No active plan'}+ </div>+ </div>+ <button+ onClick={() => void logout()}+ className="flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ >+ <LogOut size={10} /> Sign out+ </button>+ </div>++ {licenseActive && quota ? (+ <div className="space-y-2">+ <Meter+ label="Media credits (this month)"+ used={Number(quota.used.credits_used)}+ limit={quota.limits.credits}+ />+ {quota.limits.tokens > 0 && (+ <Meter+ label="Chat tokens (this month)"+ used={Number(quota.used.tokens_used)}+ limit={quota.limits.tokens}+ />+ )}+ </div>+ ) : (+ <p className="text-[0.7rem] text-gray-600 dark:text-gray-400">+ Pick a plan to unlock cloud rendering and chat.+ </p>+ )}++ <button+ onClick={() => void openExternal(`${CLOUD_BASE}/${licenseActive ? 'account' : 'pricing'}`)}+ className="flex items-center gap-1 text-[0.65rem] text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 transition-colors"+ >+ <ExternalLink size={10} /> {licenseActive ? 'Manage subscription' : 'View plans'} on lu-labs.ai+ </button>+ </div>+ )+}diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxindex 123511ce..50aaab99 100644--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@ -1,5 +1,7 @@import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'import { useCreate } from '../../../hooks/useCreate'+import { useCloudCreate } from '../../../hooks/useCloudCreate'+import { useCloudSession } from '../../../hooks/useCloudSession'import { useCreateStore } from '../../../stores/createStore'import { useUIStore } from '../../../stores/uiStore'import { getLoraModels, getVAEModels } from '../../../api/comfyui'@@ -46,10 +48,8 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {generate, cancel, samplerList, schedulerList,connected, modelsLoaded, modelLoadError, checkConnection, fetchModels,} = useCreate()- // Desktop build: no hosted rendering — the cloud axis is permanently off.- const cloudAvailable = false- const quota: CloudQuota | null = null- const refreshQuota = useCallback(async () => {}, [])+ const { cloudAvailable, quota, refreshQuota } = useCloudSession()+ const cloud = useCloudCreate({ onQuotaChange: refreshQuota })const backend = useCreateStore((s) => s.backend)const setBackend = useCreateStore((s) => s.setBackend)const setView = useUIStore((s) => s.setView)@@ -115,8 +115,8 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {const installCapability = useCallback((_cap: 'rmbg') => { setView('models') }, [setView])const value: CreateExpValue = {- generate,- cancel,+ generate: backend === 'cloud' ? cloud.generate : generate,+ cancel: backend === 'cloud' ? cloud.cancel : cancel,samplerList, schedulerList, loraList, vaeList,connected, modelsLoaded, modelLoadError, installCapability,cloudAvailable, quota, refreshQuota,diff --git a/src/components/create/experimental/CreditsMeter.tsx b/src/components/create/experimental/CreditsMeter.tsxindex fce4a207..b15b6b4f 100644--- a/src/components/create/experimental/CreditsMeter.tsx+++ b/src/components/create/experimental/CreditsMeter.tsx@@ -2,6 +2,8 @@ import { useCreateStore } from '../../../stores/createStore'import { useCreateExp } from './CreateContext'import { intentToJob } from '../../../lib/render/cloud-jobs'import { Tooltip } from '../ui/Tooltip'+import { openExternal } from '../../../api/backend'+import { CLOUD_BASE } from '../../../api/cloud/config'import { cn } from '../ui/cn'// Compact credits meter for the cloud backend: remaining vs monthly budget,@@ -22,12 +24,12 @@ export function CreditsMeter() {if (!enough) {return (- <a- href="/pricing"+ <button+ onClick={() => void openExternal(`${CLOUD_BASE}/pricing`)}className="t-control px-2 h-[var(--control-h-sm)] inline-flex items-center rounded-md bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 transition-colors">{remaining <= 0 ? 'Out of credits — upgrade' : `Needs ${cost} credits (${remaining} left)`}- </a>+ </button>)}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex d58a6715..91e17d40 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -23,6 +23,7 @@ import { extractMemoriesFromPair } from '../../hooks/useMemory'import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'import { backendCall, isTauri } from '../../api/backend'import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'+import { useCloudAuth } from '../../hooks/useCloudAuth'import { ShortcutsModal } from './ShortcutsModal'import { Titlebar } from './Titlebar'@@ -39,6 +40,9 @@ export function AppShell() {const [showSelector, setShowSelector] = useState(false)useKeyboardShortcuts()+ // LU Cloud account boot: keychain session restore + /api/me probe; keeps+ // the cloud Create axis and the lu-cloud chat provider in sync.+ useCloudAuth()// ── Store backup/restore: survive NSIS updates that wipe WebView2 data ──const STORE_KEYS = [diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex e643a70b..220f8010 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -7,6 +7,7 @@ import { usePermissionStore } from '../../stores/permissionStore'import { useUIStore } from '../../stores/uiStore'import { SliderControl } from './SliderControl'import { PersonaPanel } from '../personas/PersonaPanel'+import { AccountPanel } from '../auth/AccountPanel'import { useVoiceStore } from '../../stores/voiceStore'import { checkWhisperAvailable, checkTtsAvailable, downloadPiperVoice, listInstalledPiperVoices } from '../../api/voice'@@ -947,6 +948,9 @@ export function SettingsPage() {{/* ── General tab ──────────────────────────────── */}{tab === 'general' && (<>+ <Section title="LU Cloud Account" defaultOpen>+ <AccountPanel />+ </Section><Section title="Appearance"><div className="flex items-center justify-between"><span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Theme</span>diff --git a/src/hooks/useCloudAuth.ts b/src/hooks/useCloudAuth.tsnew file mode 100644index 00000000..6577be6a--- /dev/null+++ b/src/hooks/useCloudAuth.ts@@ -0,0 +1,89 @@+// Account lifecycle for the LU Cloud tier: keychain session restore on boot,+// email+password login/logout, and a 5-minute /api/me + quota probe while+// signed in. Also auto-enables the 'lu-cloud' chat provider whenever the+// account has token budget, so cloud models appear in the chat picker without+// any manual provider setup.++import { useCallback, useEffect, useRef } from 'react'+import { supabaseCloud } from '../api/cloud/supabase'+import { getMe, getQuota } from '../api/cloud/jobs'+import { useCloudAuthStore } from '../stores/cloudAuthStore'+import { useProviderStore } from '../stores/providerStore'+import type { CloudQuota } from '../lib/render/cloud-jobs'++const REFRESH_MS = 5 * 60_000++async function probeAccount(): Promise<void> {+ const store = useCloudAuthStore.getState()+ try {+ const me = await getMe()+ if (!me.user) {+ store.setSignedOut()+ syncChatProvider(null)+ return+ }+ const licenseActive = me.license?.status === 'active'+ let quota: CloudQuota | null = null+ if (licenseActive) {+ quota = await getQuota().catch(() => null)+ }+ store.setSignedIn({ id: me.user.id, email: me.user.email }, licenseActive, quota)+ syncChatProvider(quota)+ } catch {+ // 401 = no/expired session; network = cloud unreachable. Either way the+ // cloud axis is off for now — local features are unaffected.+ store.setSignedOut()+ syncChatProvider(null)+ }+}++// Chat side of the account: the lu-cloud provider is enabled exactly when the+// tier has a token budget. Uses the store action so the registry cache clears.+function syncChatProvider(quota: CloudQuota | null): void {+ const enabled = (quota?.limits.tokens ?? 0) > 0+ const current = useProviderStore.getState().providers['lu-cloud']+ if (current && current.enabled !== enabled) {+ useProviderStore.getState().setProviderConfig('lu-cloud', { enabled })+ }+}++export function useCloudAuth() {+ const status = useCloudAuthStore((s) => s.status)+ const user = useCloudAuthStore((s) => s.user)+ const armed = useRef(false)++ useEffect(() => {+ if (armed.current) return+ armed.current = true+ void probeAccount()+ const timer = setInterval(() => {+ if (useCloudAuthStore.getState().status === 'signed-in') void probeAccount()+ }, REFRESH_MS)+ return () => clearInterval(timer)+ }, [])++ const login = useCallback(async (email: string, password: string): Promise<void> => {+ const { error } = await supabaseCloud().auth.signInWithPassword({ email, password })+ if (error) throw new Error(error.message)+ await probeAccount()+ }, [])++ const signup = useCallback(async (email: string, password: string): Promise<void> => {+ const { error } = await supabaseCloud().auth.signUp({ email, password })+ if (error) throw new Error(error.message)+ // Autoconfirm is on server-side — a fresh signup is immediately signed in.+ await probeAccount()+ }, [])++ const logout = useCallback(async (): Promise<void> => {+ await supabaseCloud().auth.signOut().catch(() => {})+ useCloudAuthStore.getState().setSignedOut()+ syncChatProvider(null)+ }, [])++ const refresh = useCallback(async (): Promise<void> => {+ await probeAccount()+ }, [])++ return { status, user, login, signup, logout, refresh }+}diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsnew file mode 100644index 00000000..3de138f3--- /dev/null+++ b/src/hooks/useCloudCreate.ts@@ -0,0 +1,209 @@+// Cloud twin of useCreate's generate/cancel — port of uselu's useCloudCreate+// onto the desktop cloud client (bearer auth via api/cloud/jobs). Submits the+// current Create state to the hosted render queue instead of local ComfyUI,+// then polls to completion. Store choreography (isGenerating, progress,+// gallery) mirrors the local path so every downstream component works+// unchanged. useCreate itself is untouched: the seam lives in CreateExpProvider.+//+// Desktop delta vs uselu: image results are downloaded into a self-contained+// dataUrl gallery item (signed URLs expire — the local copy never rots and+// works offline). Videos would blow localStorage as base64, so they keep+// remoteUrl + jobId and re-sign lazily via refreshResultUrl().++import { useCallback, useRef } from 'react'+import { useCreateStore } from '../stores/createStore'+import { intentToJob } from '../lib/render/cloud-jobs'+import {+ cancelJob,+ pollJob,+ submitCloudJob,+ uploadInput,+ CloudJobError,+ type CloudJobParams,+} from '../api/cloud/jobs'+import { defaultCloudModel } from '../lib/render/cloud-models'+import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../lib/render/safety'++async function dataUrlToBlob(dataUrl: string): Promise<Blob> {+ const res = await fetch(dataUrl)+ return res.blob()+}++async function fetchAsDataUrl(url: string): Promise<string | null> {+ try {+ const res = await fetch(url)+ if (!res.ok) return null+ const blob = await res.blob()+ return await new Promise<string | null>((resolve) => {+ const reader = new FileReader()+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : null)+ reader.onerror = () => resolve(null)+ reader.readAsDataURL(blob)+ })+ } catch {+ return null+ }+}++export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {+ const activeJob = useRef<string | null>(null)+ const abort = useRef<AbortController | null>(null)+ const { onQuotaChange } = opts++ const generate = useCallback(async () => {+ const s = useCreateStore.getState()+ if (s.isGenerating) return+ const intent = s.intent()+ const { kind, op } = intentToJob(intent)+ const model =+ (kind === 'video' ? s.cloudVideoModel : s.cloudImageModel) || defaultCloudModel(kind).id++ s.setError(null)+ if (op === 'generate' && s.prompt.trim().length === 0) {+ s.setError('Please enter a prompt.')+ return+ }+ // Client-side CSAM gate (UX). The server additionally enforces its+ // SFW-cloud policy — its 422 message lands in setError below.+ if (checkPromptSafety(`${s.prompt} ${s.negativePrompt}`).blocked) {+ s.setError(SAFETY_BLOCK_MESSAGE)+ return+ }+ if (op !== 'generate' && !s.source) {+ s.setError('Add a source image first.')+ return+ }++ s.setIsGenerating(true)+ s.setProgressPhase('queued')+ s.setProgress(5, 'Uploading inputs…')++ try {+ const params: CloudJobParams = {+ op,+ negative_prompt: s.negativePrompt || undefined,+ width: s.width,+ height: s.height,+ steps: s.steps,+ cfg: s.cfgScale,+ seed: s.seed === -1 ? undefined : s.seed,+ }+ if (kind === 'video') {+ params.frames = s.frames+ params.fps = s.fps+ }+ if (op === 'edit') {+ params.denoise = s.denoise+ params.grow_mask_by = s.growMaskBy+ }+ // ImageRef.url is always a data URL preview; the cloud path re-uploads+ // from it, so a source picked while on the local backend still works.+ if (op !== 'generate' && s.source) {+ params.source_path = await uploadInput(await dataUrlToBlob(s.source.url), 'source')+ }+ if (op === 'edit') {+ if (!s.mask) {+ s.setError('Paint a mask first — the edit only changes the painted area.')+ s.setIsGenerating(false)+ return+ }+ params.mask_path = await uploadInput(await dataUrlToBlob(s.mask.url), 'mask')+ }++ s.setProgress(10, 'Submitting to the render queue…')+ const { id } = await submitCloudJob({ kind, model, prompt: s.prompt, params })+ activeJob.current = id+ abort.current = new AbortController()+ onQuotaChange?.()+ if (s.prompt.trim()) s.addToPromptHistory(s.prompt.trim())++ const startedAt = Date.now()+ // Video renders routinely run several minutes and can queue behind+ // other jobs on the shared fleet — give them a much longer client+ // deadline than images.+ const job = await pollJob(id, {+ timeoutMs: kind === 'video' ? 45 * 60_000 : 15 * 60_000,+ signal: abort.current.signal,+ onTick: (j) => {+ const st = useCreateStore.getState()+ const elapsed = Math.round((Date.now() - startedAt) / 1000)+ if (j.status === 'queued') {+ st.setProgressPhase('queued')+ st.setProgress(15, `Waiting for a cloud GPU… ${elapsed}s`)+ } else if (j.status === 'running') {+ st.setProgressPhase('sampling')+ st.setProgress(Math.min(90, 20 + elapsed), `Rendering in the cloud… ${elapsed}s`)+ }+ },+ })++ const st = useCreateStore.getState()+ if (job.status === 'succeeded' && job.result_url) {+ st.setProgressPhase('complete')+ st.setProgress(100, 'Complete!')+ // Images: pull the bytes now — the local copy never expires.+ const dataUrl = kind === 'image' ? await fetchAsDataUrl(job.result_url) : null+ st.addToGallery({+ id: job.id,+ type: kind,+ filename: '',+ subfolder: '',+ prompt: s.prompt,+ negativePrompt: s.negativePrompt,+ model,+ modelType: 'unknown',+ seed: s.seed === -1 ? 0 : s.seed,+ steps: s.steps,+ cfgScale: s.cfgScale,+ sampler: s.sampler,+ scheduler: s.scheduler,+ width: s.width,+ height: s.height,+ batchSize: 1,+ createdAt: Date.now(),+ ...(dataUrl ? { dataUrl } : { remoteUrl: job.result_url }),+ attestation: job.attestation,+ jobId: job.id,+ intent,+ })+ } else if (job.status === 'canceled') {+ st.setError(null)+ } else {+ st.setError(job.error ?? 'Cloud render failed.')+ onQuotaChange?.() // failure refunds — refresh the meter+ }+ } catch (err) {+ const st = useCreateStore.getState()+ if (err instanceof CloudJobError && err.status === 429) {+ st.setError('Monthly credit budget exhausted — upgrade your plan or wait for the next period.')+ } else if (err instanceof CloudJobError && err.status === 401) {+ st.setError('Sign in to your LU Cloud account to render in the cloud.')+ } else if (err instanceof CloudJobError && err.message === 'render timed out') {+ st.setError('Still rendering — this is taking longer than expected. It will appear in your history when it completes.')+ } else if (!(err instanceof CloudJobError && err.message === 'polling aborted')) {+ st.setError(err instanceof Error ? err.message : String(err))+ }+ onQuotaChange?.()+ } finally {+ activeJob.current = null+ abort.current = null+ const st = useCreateStore.getState()+ st.setIsGenerating(false)+ st.setProgress(0)+ }+ }, [onQuotaChange])++ const cancel = useCallback(async () => {+ const id = activeJob.current+ abort.current?.abort() // stop polling immediately either way+ if (!id) return+ try {+ await cancelJob(id)+ onQuotaChange?.() // queued-cancel refunds+ } catch {+ // 409 (already running/finished) — poll stop is all the client can do+ }+ }, [onQuotaChange])++ return { generate, cancel }+}diff --git a/src/hooks/useCloudSession.ts b/src/hooks/useCloudSession.tsnew file mode 100644index 00000000..5a5fc21b--- /dev/null+++ b/src/hooks/useCloudSession.ts@@ -0,0 +1,40 @@+// The Create surface's view of the cloud axis — same contract as uselu's+// useCloudSession, but derived from the shared cloudAuthStore (fed by+// useCloudAuth's probes) instead of its own /api/me polling.++import { useCallback } from 'react'+import { useCloudAuthStore, deriveCloudAvailable } from '../stores/cloudAuthStore'+import { getQuota } from '../api/cloud/jobs'+import type { CloudQuota } from '../lib/render/cloud-jobs'++export interface CloudSession {+ user: { id: string; email?: string } | null+ licenseActive: boolean+ quota: CloudQuota | null+ /** true ⇔ signed in + active license + a tier with a media-credit budget. */+ cloudAvailable: boolean+ refreshQuota: () => Promise<void>+}++export function useCloudSession(): CloudSession {+ const user = useCloudAuthStore((s) => s.user)+ const licenseActive = useCloudAuthStore((s) => s.licenseActive)+ const quota = useCloudAuthStore((s) => s.quota)++ const refreshQuota = useCallback(async () => {+ try {+ const q = await getQuota()+ useCloudAuthStore.getState().setQuota(q)+ } catch {+ useCloudAuthStore.getState().setQuota(null)+ }+ }, [])++ return {+ user,+ licenseActive,+ quota,+ cloudAvailable: deriveCloudAvailable({ user, licenseActive, quota }),+ refreshQuota,+ }+}diff --git a/src/lib/render/cloud-models.ts b/src/lib/render/cloud-models.tsnew file mode 100644index 00000000..a74e7292--- /dev/null+++ b/src/lib/render/cloud-models.ts@@ -0,0 +1,44 @@+// The hosted render fleet's model catalog (verbatim from uselu+// apps/web/lib/render/cloud-models.ts — keep in sync). Local backends list+// whatever the user installed; the cloud path renders on the operator's+// ComfyUI images, so the choice set is fixed and versioned here. `file` is+// the checkpoint name the worker's workflow templates load (%MODEL%); `id`+// is the stable slug the UI stores and the API accepts.++import type { RenderKind } from './cloud-jobs'++export interface CloudModel {+ id: string+ label: string+ kind: RenderKind+ file: string+}++export const CLOUD_MODELS: CloudModel[] = [+ {+ id: 'qwen-image-2512',+ label: 'Qwen Image 2512',+ kind: 'image',+ file: 'qwen_image_2512_fp8.safetensors',+ },+ {+ id: 'sdxl-base-1.0',+ label: 'SDXL 1.0',+ kind: 'image',+ file: 'sd_xl_base_1.0.safetensors',+ },+ {+ id: 'wan-2.2-a14b',+ label: 'Wan 2.2 A14B',+ kind: 'video',+ file: 'wan2.2_a14b_fp8.safetensors',+ },+]++export function cloudModelsFor(kind: RenderKind): CloudModel[] {+ return CLOUD_MODELS.filter((m) => m.kind === kind)+}++export function defaultCloudModel(kind: RenderKind): CloudModel {+ return cloudModelsFor(kind)[0]+}diff --git a/src/stores/__tests__/cloudAuthStore.test.ts b/src/stores/__tests__/cloudAuthStore.test.tsnew file mode 100644index 00000000..d7d954c9--- /dev/null+++ b/src/stores/__tests__/cloudAuthStore.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useCloudAuthStore, deriveCloudAvailable } from '../cloudAuthStore'+import type { CloudQuota } from '../../lib/render/cloud-jobs'++const quota = (credits: number, tokens = 0): CloudQuota => ({+ tier: 'hosted',+ period: '2026-07',+ limits: { tokens, credits },+ costs: { image: 5, video: 80 },+ used: { tokens_used: 0, credits_used: 0 },+ remaining: { tokens, credits },+})++beforeEach(() => {+ useCloudAuthStore.getState().setSignedOut()+})++describe('cloudAuthStore', () => {+ it('setSignedIn stores user, license and quota', () => {+ useCloudAuthStore.getState().setSignedIn({ id: 'u1', email: '[email protected]' }, true, quota(800))+ const s = useCloudAuthStore.getState()+ expect(s.status).toBe('signed-in')+ expect(s.user?.email).toBe('[email protected]')+ expect(s.licenseActive).toBe(true)+ expect(s.quota?.limits.credits).toBe(800)+ })++ it('setSignedOut clears everything', () => {+ useCloudAuthStore.getState().setSignedIn({ id: 'u1' }, true, quota(800))+ useCloudAuthStore.getState().setSignedOut()+ const s = useCloudAuthStore.getState()+ expect(s.status).toBe('signed-out')+ expect(s.user).toBeNull()+ expect(s.licenseActive).toBe(false)+ expect(s.quota).toBeNull()+ })+})++describe('deriveCloudAvailable', () => {+ it('requires signed-in + active license + credit budget', () => {+ expect(deriveCloudAvailable({ user: null, licenseActive: false, quota: null })).toBe(false)+ expect(deriveCloudAvailable({ user: { id: 'u' }, licenseActive: false, quota: quota(800) })).toBe(false)+ expect(deriveCloudAvailable({ user: { id: 'u' }, licenseActive: true, quota: null })).toBe(false)+ // self-host tier: licensed but 0 media credits+ expect(deriveCloudAvailable({ user: { id: 'u' }, licenseActive: true, quota: quota(0) })).toBe(false)+ expect(deriveCloudAvailable({ user: { id: 'u' }, licenseActive: true, quota: quota(800) })).toBe(true)+ })+})diff --git a/src/stores/__tests__/providerStore.test.ts b/src/stores/__tests__/providerStore.test.tsindex a90ed542..b2aa4305 100644--- a/src/stores/__tests__/providerStore.test.ts+++ b/src/stores/__tests__/providerStore.test.ts@@ -35,6 +35,14 @@ const DEFAULT_PROVIDERS = {apiKey: '',isLocal: false,},+ 'lu-cloud': {+ id: 'lu-cloud' as const,+ name: 'LU Cloud',+ enabled: false,+ baseUrl: 'https://lu-labs.ai/api/inference/v1',+ apiKey: '',+ isLocal: false,+ },}// ═══════════════════════════════════════════════════════════════@@ -50,9 +58,10 @@ describe('providerStore', () => {// ── Initial state ──────────────────────────────────────────describe('initial state', () => {- it('has three default providers', () => {+ it('has four default providers', () => {const providers = useProviderStore.getState().providers- expect(Object.keys(providers)).toHaveLength(3)+ expect(Object.keys(providers)).toHaveLength(4)+ expect(providers['lu-cloud']).toBeDefined()expect(providers.ollama).toBeDefined()expect(providers.openai).toBeDefined()expect(providers.anthropic).toBeDefined()diff --git a/src/stores/cloudAuthStore.ts b/src/stores/cloudAuthStore.tsnew file mode 100644index 00000000..79980766--- /dev/null+++ b/src/stores/cloudAuthStore.ts@@ -0,0 +1,47 @@+// LU Cloud account state. Deliberately NOT persisted: the session itself+// lives in the OS keychain (api/cloud/supabase.ts storage adapter) and+// user/tier/quota are re-derived from /api/me + /api/jobs/quota on boot —+// a persisted copy could only ever be stale.++import { create } from 'zustand'+import type { CloudQuota } from '../lib/render/cloud-jobs'++export interface CloudUser {+ id: string+ email?: string+}++interface CloudAuthState {+ /** 'probing' until the keychain session restore + first /api/me resolve. */+ status: 'probing' | 'signed-out' | 'signed-in'+ user: CloudUser | null+ licenseActive: boolean+ quota: CloudQuota | null++ setSignedOut: () => void+ setSignedIn: (user: CloudUser, licenseActive: boolean, quota: CloudQuota | null) => void+ setQuota: (quota: CloudQuota | null) => void+}++export const useCloudAuthStore = create<CloudAuthState>()((set) => ({+ status: 'probing',+ user: null,+ licenseActive: false,+ quota: null,++ setSignedOut: () =>+ set({ status: 'signed-out', user: null, licenseActive: false, quota: null }),+ setSignedIn: (user, licenseActive, quota) =>+ set({ status: 'signed-in', user, licenseActive, quota }),+ setQuota: (quota) => set({ quota }),+}))++/** The whole cloud axis in one predicate: signed in, actively licensed, and+ * on a tier whose monthly media budget is > 0 (self-host tiers report 0). */+export function deriveCloudAvailable(state: {+ user: CloudUser | null+ licenseActive: boolean+ quota: CloudQuota | null+}): boolean {+ return Boolean(state.user && state.licenseActive && (state.quota?.limits.credits ?? 0) > 0)+}diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.tsindex dc2ce656..80e8408e 100644--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@ -10,6 +10,7 @@ import { persist } from 'zustand/middleware'import type { ProviderId, ProviderConfig } from '../api/providers/types'import { clearProviderCache } from '../api/providers/registry'import { secretGet, secretSet, secretDelete } from '../api/backend'+import { CLOUD_BASE } from '../api/cloud/config'// ── API Key storage ────────────────────────────────────────────// Two-tier (H5):@@ -77,6 +78,17 @@ const DEFAULT_PROVIDERS: Record<ProviderId, ProviderConfig> = {apiKey: '',isLocal: false,},+ // LU Cloud chat (lu-labs.ai inference proxy). apiKey stays empty forever —+ // auth is the user's Supabase session token, injected per request by+ // LuCloudProvider. useCloudAuth flips `enabled` with the account state.+ 'lu-cloud': {+ id: 'lu-cloud',+ name: 'LU Cloud',+ enabled: false,+ baseUrl: `${CLOUD_BASE}/api/inference/v1`,+ apiKey: '',+ isLocal: false,+ },}// ── Store Interface ────────────────────────────────────────────@@ -209,6 +221,17 @@ export const useProviderStore = create<ProviderState>()({name: 'lu-providers',version: 1,+ // Blobs persisted before the lu-cloud provider existed lack its entry —+ // backfill every missing provider from defaults so getProvider() can't+ // hit an undefined config after an update.+ merge: (persisted: unknown, current: ProviderState): ProviderState => {+ const p = (persisted ?? {}) as Partial<ProviderState>+ return {+ ...current,+ ...p,+ providers: { ...DEFAULT_PROVIDERS, ...(p.providers ?? {}) },+ }+ },// Don't persist transient state, only configs + user's "don't show again" preference.// When the OS keychain is active (H5), strip apiKey so the secret never// touches localStorage; otherwise keep the obfuscated key as before.