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
fix(create): a finished character training waits until it is on the shelf
purple887239ed5d3e
diff --git a/src/api/cloud/__tests__/trained-lora-shows-up.test.ts b/src/api/cloud/__tests__/trained-lora-shows-up.test.tsnew file mode 100644index 00000000..815c6ab5--- /dev/null+++ b/src/api/cloud/__tests__/trained-lora-shows-up.test.ts@@ -0,0 +1,102 @@+/**+ * Fall E7 (07.11.2026): a customer trained two characters in the desktop app,+ * both trainings went through and both characters are on his account, yet the+ * app showed "No characters yet" each time and the photos were gone.+ *+ * The render worker marks a training done first and writes the character to+ * the shelf about a second later. The app read the shelf the moment the job+ * said done. waitForTrainedLora asks until the new character is there.+ */+import { describe, it, expect, vi } from 'vitest'++vi.mock('../supabase', () => ({ getAccessToken: vi.fn() }))+vi.mock('../../backend', () => ({ isTauri: () => false }))++import { shelfHasTraining, waitForTrainedLora, type CloudLora } from '../loras'++const DONE = '2026-11-07T23:48:21.651Z'++function lora(id: string, createdAt: string): CloudLora {+ return { id, name: id, trigger_word: id, base_family: 'flux', created_at: createdAt }+}++const older = lora('alt', '2026-11-07T20:00:00.000Z')+const fresh = lora('neu', '2026-11-07T23:48:22.421978+00:00')+const noSleep = () => Promise.resolve()++describe('shelfHasTraining', () => {+ it('finds the character written just after the job was done', () => {+ expect(shelfHasTraining([fresh], DONE)).toBe(true)+ })++ it('does not take an older character for the new one', () => {+ expect(shelfHasTraining([older], DONE)).toBe(false)+ expect(shelfHasTraining([], DONE)).toBe(false)+ })++ it('allows for a worker clock a little ahead of the database', () => {+ expect(shelfHasTraining([lora('x', '2026-11-07T23:48:10.000Z')], DONE)).toBe(true)+ })++ it('says no without a completion time', () => {+ expect(shelfHasTraining([fresh], null)).toBe(false)+ })+})++describe('waitForTrainedLora', () => {+ it('asks again until the new character is on the shelf', async () => {+ const list = vi.fn()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([fresh])+ const shelf = await waitForTrainedLora({ completed_at: DONE }, { list, sleep: noSleep })+ expect(shelf).toEqual([fresh])+ expect(list).toHaveBeenCalledTimes(3)+ })++ it('does not stop at a shelf that only holds older characters', async () => {+ const list = vi.fn()+ .mockResolvedValueOnce([older])+ .mockResolvedValueOnce([fresh, older])+ const shelf = await waitForTrainedLora({ completed_at: DONE }, { list, sleep: noSleep })+ expect(shelf).toEqual([fresh, older])+ })++ it('takes a failed read as one more try', async () => {+ const list = vi.fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce([fresh])+ await expect(waitForTrainedLora({ completed_at: DONE }, { list, sleep: noSleep })).resolves.toEqual([fresh])+ })++ it('gives up after the waits and says so with null', async () => {+ const list = vi.fn().mockResolvedValue([older])+ const sleep = vi.fn(noSleep)+ const shelf = await waitForTrainedLora({ completed_at: DONE }, { list, sleep, waitsMs: [1, 2, 3] })+ expect(shelf).toBeNull()+ expect(list).toHaveBeenCalledTimes(4)+ expect(sleep).toHaveBeenCalledTimes(3)+ })++ it('stops when the run is ended', async () => {+ const ac = new AbortController()+ ac.abort()+ const list = vi.fn().mockResolvedValue([fresh])+ await expect(waitForTrainedLora({ completed_at: DONE }, { list, signal: ac.signal, sleep: noSleep })).resolves.toBeNull()+ expect(list).not.toHaveBeenCalled()+ })+})++describe('the desktop run waits for the shelf before it flips to Use character', () => {+ it('reads the shelf until the character is there, then clears the photos', async () => {+ const { readFileSync } = await import('node:fs')+ const { join } = await import('node:path')+ const src = readFileSync(join(__dirname, '../../../hooks/useCloudCreate.ts'), 'utf8')+ const branch = src.slice(src.indexOf("if (job.status === 'succeeded' && op === 'lora-train')"))+ const waitAt = branch.indexOf('await waitForTrainedLora(job')+ expect(waitAt).toBeGreaterThan(0)+ expect(branch.indexOf('clearTrainImages()')).toBeGreaterThan(waitAt)+ expect(branch.indexOf("setCharacterTab('use')")).toBeGreaterThan(waitAt)+ expect(branch.indexOf('bumpCharactersVersion()')).toBeGreaterThan(waitAt)+ })+})diff --git a/src/api/cloud/loras.ts b/src/api/cloud/loras.tsindex 59811beb..763092db 100644--- a/src/api/cloud/loras.ts+++ b/src/api/cloud/loras.ts@@ -24,6 +24,71 @@ export async function listLoras(): Promise<CloudLora[]> {return loras}+/** How long the app waits, step by step, for a finished training to show up+ * on the shelf. About 17 seconds in all. */+export const TRAINED_LORA_WAITS_MS = [500, 1000, 1500, 2000, 3000, 4000, 5000]++/** When the first waits were not enough: asked again in the background for+ * about two more minutes. */+export const TRAINED_LORA_LATE_WAITS_MS = [10_000, 20_000, 30_000, 60_000]++/** A shelf entry counts as the new one when the server wrote it at most this+ * long before the job said it was done. The worker and the database each+ * keep their own clock; an older character is minutes older, not seconds. */+const SAME_TRAINING_SLACK_MS = 30_000++/** Said when a training is done but its character did not show up on the+ * shelf within the waits. The character is on the account either way. */+export const TRAINED_NOT_YET_LISTED =+ 'Your character is trained and saved to your account. It can take a minute to show up here. Open Use character again in a moment.'++/** True when the shelf holds the character a training finished at+ * `completedAt` (ISO time of the job). */+export function shelfHasTraining(shelf: CloudLora[], completedAt: string | null | undefined): boolean {+ const done = completedAt ? Date.parse(completedAt) : NaN+ if (!Number.isFinite(done)) return false+ return shelf.some((l) => {+ const at = Date.parse(l.created_at)+ return Number.isFinite(at) && at >= done - SAME_TRAINING_SLACK_MS+ })+}++/** Waits until a finished training is on the shelf.+ *+ * The server marks a training job done first and puts the character on the+ * shelf about a second later (render worker: succeed, then persistLora). An+ * app that reads the shelf the moment the job says done gets the list+ * without the new character, and the customer sees "No characters yet" after+ * a paid training (Fall E7, 07.11.2026). So this asks again a few times.+ *+ * Resolves the shelf that holds the character, or null when it did not show+ * within the waits (or `signal` ended the wait). A failed read is just+ * another try. Never throws. */+export async function waitForTrainedLora(+ job: { completed_at: string | null },+ opts: {+ waitsMs?: number[]+ signal?: AbortSignal+ list?: () => Promise<CloudLora[]>+ sleep?: (ms: number) => Promise<void>+ } = {},+): Promise<CloudLora[] | null> {+ const list = opts.list ?? listLoras+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))+ const waits = opts.waitsMs ?? TRAINED_LORA_WAITS_MS+ for (let i = 0; i <= waits.length; i++) {+ if (opts.signal?.aborted) return null+ try {+ const shelf = await list()+ if (shelfHasTraining(shelf, job.completed_at)) return shelf+ } catch {+ // The next try asks again.+ }+ if (i < waits.length) await sleep(waits[i])+ }+ return null+}+export async function deleteLora(id: string): Promise<void> {const res = await cloudFetch(`/api/loras/${encodeURIComponent(id)}`, { method: 'DELETE' })await jsonOrError<{ ok: boolean }>(res)diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex 59e11271..ac3983a3 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -54,6 +54,7 @@ import { studioQuote, StudioQuoteChangedError } from '../api/cloud/studio'import { outageAfterFailure } from '../lib/cloud-outage-watch'import { MIN_TRAIN_IMAGES, maxTrainImages } from '../lib/train-image-cap'import { forgetStaged, stagedMayBeStale, uploadTrainPhotos } from '../lib/train-upload'+import { waitForTrainedLora, TRAINED_NOT_YET_LISTED, TRAINED_LORA_LATE_WAITS_MS } from '../api/cloud/loras'// B3 (review-w2ui.md, 18.09.2026): the CSAM floor above runs regardless of// tier, but the adult half of safety.ts (ADULT_SOFT_TERMS/ADULT_HARD_TERMS)@@ -916,11 +917,33 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {if (job.status === 'succeeded' && op === 'lora-train') {// Training output is a LoRA on the user's shelf, not a media item —// flip Character-Studio to the use-surface with a fresh shelf.+ //+ // Fall E7 (07.11.2026): the server says "succeeded" about a second+ // before the character is on the shelf. Reading the shelf at once+ // showed "No characters yet" after a paid training, the photos were+ // gone and nothing said why. So the shelf is asked until the new+ // character is there, and only then does the surface flip.st.setProgressPhase('complete')- st.setProgress(100, 'Character trained!')- st.clearTrainImages()- st.setCharacterTab('use')- st.bumpCharactersVersion()+ st.setProgress(100, 'Character trained! Putting it on your shelf…')+ const shelf = await waitForTrainedLora(job, { signal: ac.signal })+ const now = useCreateStore.getState()+ now.setProgress(100, 'Character trained!')+ now.clearTrainImages()+ now.setCharacterTab('use')+ now.bumpCharactersVersion()+ if (!shelf && !ac.signal.aborted) {+ // Still not there: keep asking in the background and refresh the+ // shelf when it comes. The desktop says so meanwhile; the phone's+ // character page reads an error as a failed training, so it only+ // gets the late refresh.+ if (!isMobile()) now.setError(TRAINED_NOT_YET_LISTED)+ void waitForTrainedLora(job, { waitsMs: TRAINED_LORA_LATE_WAITS_MS }).then((late) => {+ if (!late) return+ const later = useCreateStore.getState()+ if (later.error === TRAINED_NOT_YET_LISTED) later.setError(null)+ later.bumpCharactersVersion()+ })+ }} else if (job.status === 'succeeded' && job.result_url) {st.setProgressPhase('complete')st.setProgress(100, 'Complete!')diff --git a/src/lib/__tests__/mobile-cloud-jobs-resume.test.ts b/src/lib/__tests__/mobile-cloud-jobs-resume.test.tsindex a259f9d7..9ff4d76a 100644--- a/src/lib/__tests__/mobile-cloud-jobs-resume.test.ts+++ b/src/lib/__tests__/mobile-cloud-jobs-resume.test.ts@@ -43,6 +43,9 @@ vi.mock('../../api/cloud/jobs', () => ({pollJob: cloud.pollJob,CloudJobError: cloud.FakeCloudJobError,}))+// Fall E7: the shelf is read again once the trained character is on it.+const shelf = vi.hoisted(() => ({ waitForTrainedLora: vi.fn(async () => null as unknown) }))+vi.mock('../../api/cloud/loras', () => ({ waitForTrainedLora: shelf.waitForTrainedLora }))import { useCreateStore } from '../../stores/createStore'import { useCloudAuthStore } from '../../stores/cloudAuthStore'@@ -221,6 +224,17 @@ describe('after a kill, the result still lands', () => {expect(useCreateStore.getState().gallery).toEqual([])})+ it('a trained character that reaches the shelf late refreshes it once more (Fall E7)', async () => {+ standOn('iphone')+ shelf.waitForTrainedLora.mockResolvedValueOnce([{ id: 'c1' }])+ const before = useCreateStore.getState().charactersVersion+ afterAKill(entry('train-2', { op: 'lora-train', landing: 'character' }))+ cloud.pollJob.mockResolvedValue(finished('train-2', { result_url: null, completed_at: '2026-11-07T23:48:21.651Z' }))+ await resumePendingCloudJobs()+ await vi.waitFor(() => expect(useCreateStore.getState().charactersVersion).toBe(before + 2))+ expect(shelf.waitForTrainedLora).toHaveBeenCalledWith(expect.objectContaining({ id: 'train-2' }))+ })+it('a finished voice is in the gallery and picked for the talking character', async () => {standOn('iphone')afterAKill(entry('voice-1', { kind: 'audio', op: 'tts', landing: 'voice', prompt: 'Hello there', item: { prompt: 'Hello there', intent: 'lipsync' } }))diff --git a/src/lib/cloud-job-resume.ts b/src/lib/cloud-job-resume.tsindex d503a9cb..d573c5c6 100644--- a/src/lib/cloud-job-resume.ts+++ b/src/lib/cloud-job-resume.ts@@ -13,6 +13,7 @@// session lands quietly, the screen stays free for the next run.import { getJob, pollJob, CloudJobError } from '../api/cloud/jobs'+import { waitForTrainedLora } from '../api/cloud/loras'import type { CloudJob } from '../api/cloud/jobs'import { galleryItemFromJob } from './render/cloud-jobs'import { useCreateStore } from '../stores/createStore'@@ -84,6 +85,11 @@ function land(entry: PendingCloudJob, job: CloudJob): Outcome {if (job.status !== 'succeeded') return 'failed'if (entry.landing === 'character') {st.bumpCharactersVersion()+ // Fall E7: the character reaches the shelf a moment after the job says+ // done. Read the shelf once more when it is there.+ void waitForTrainedLora(job).then((shelf) => {+ if (shelf) useCreateStore.getState().bumpCharactersVersion()+ })return 'landed'}if (!job.result_url) return 'failed'