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
test(create-3d): picture first, chain, hook, phone and a mocked browser run
purpled55d6040d090
diff --git a/e2e/create-3d-picture-first.spec.ts b/e2e/create-3d-picture-first.spec.tsnew file mode 100644index 00000000..d99fc4c1--- /dev/null+++ b/e2e/create-3d-picture-first.spec.ts@@ -0,0 +1,156 @@+import { test, expect, type Page, type Route } from '@playwright/test'+import { deflateSync } from 'node:zlib'+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'++/**+ * 3D from words in the cloud, "Picture first" (3.1.0): the picker offers it+ * first on the Text way with the price of picture plus model, the run books+ * a picture on the open image model, shows it on the Stage, has the server+ * copy it (adopt) and builds the model from it. Nothing leaves this machine:+ * every cloud call is answered here.+ */++const WINDOWS_OPTS: TauriMockOptions = { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, platform: 'windows' }+const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS' }++/** A plain 256 px picture: a light ground with a dark square, so the Stage shows something. */+function picturePng(): Buffer {+ const n = 256+ const raw = Buffer.alloc((n * 3 + 1) * n)+ for (let y = 0; y < n; y++) {+ raw[y * (n * 3 + 1)] = 0+ for (let x = 0; x < n; x++) {+ const inside = x > 80 && x < 176 && y > 80 && y < 176+ const o = y * (n * 3 + 1) + 1 + x * 3+ raw[o] = inside ? 120 : 235; raw[o + 1] = inside ? 90 : 235; raw[o + 2] = inside ? 60 : 230+ }+ }+ const crcTable = Array.from({ length: 256 }, (_, k) => { let c = k; for (let i = 0; i < 8; i++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0 })+ const crc = (b: Buffer) => { let c = 0xffffffff; for (const v of b) c = crcTable[(c ^ v) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0 }+ const chunk = (type: string, data: Buffer) => {+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length)+ const td = Buffer.concat([Buffer.from(type), data])+ const c = Buffer.alloc(4); c.writeUInt32BE(crc(td))+ return Buffer.concat([len, td, c])+ }+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(n, 0); ihdr.writeUInt32BE(n, 4); ihdr[8] = 8; ihdr[9] = 2+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])+}+const PICTURE = picturePng()++/** One triangle as a GLB, the smallest model the viewer opens. */+function triangleGlb(): Buffer {+ const bin = Buffer.alloc(36)+ ;[0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4))+ const gltf = {+ asset: { version: '2.0' },+ scenes: [{ nodes: [0] }], scene: 0, nodes: [{ mesh: 0 }],+ meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],+ buffers: [{ byteLength: 36 }], bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }],+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] }],+ }+ let json = Buffer.from(JSON.stringify(gltf))+ json = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)])+ const head = Buffer.alloc(12)+ head.write('glTF', 0); head.writeUInt32LE(2, 4); head.writeUInt32LE(12 + 8 + json.length + 8 + bin.length, 8)+ const chunk = (b: Buffer, type: number) => { const h = Buffer.alloc(8); h.writeUInt32LE(b.length, 0); h.writeUInt32LE(type, 4); return Buffer.concat([h, b]) }+ return Buffer.concat([head, chunk(json, 0x4e4f534a), chunk(bin, 0x004e4942)])+}++interface Seen { submits: { kind: string; model: string; prompt: string; params: Record<string, unknown> }[]; adopted: string[] }++async function routePictureFirst(page: Page, meshStatus: 'succeeded' | 'failed'): Promise<Seen> {+ const seen: Seen = { submits: [], adopted: [] }+ const json = (route: Route, status: number, body: unknown) => route.fulfill({ status, headers: { ...CORS, 'content-type': 'application/json' }, body: JSON.stringify(body) })+ const job = (id: string, kind: string, model: string, status: string, url: string | null) => ({+ job: { id, kind, model, provider: 'upstream', status, result_url: url, attestation: null, cost_units: 0, created_at: new Date().toISOString(), completed_at: new Date().toISOString(), error: status === 'failed' ? 'The provider could not build this one.' : null },+ })+ await page.route('https://lu-labs.ai/**', async (route) => {+ const req = route.request()+ if (req.method() === 'OPTIONS') return route.fallback()+ const path = new URL(req.url()).pathname+ if (path === '/api/jobs/studio-quote') {+ const body = req.postDataJSON() as { model: string }+ return json(route, 200, { credits: body.model === 'z-image' ? 1000 : 20000 })+ }+ if (path === '/api/jobs' && req.method() === 'POST') {+ const body = req.postDataJSON() as Seen['submits'][number]+ seen.submits.push(body)+ return json(route, 202, { id: body.kind === 'image' ? 'job-pic-1' : 'job-mesh-1', status: 'queued', created_at: new Date().toISOString(), quota: { kind: body.kind, cost: 0 } })+ }+ if (path === '/api/jobs/adopt') {+ seen.adopted.push((req.postDataJSON() as { job_id: string }).job_id)+ return json(route, 201, { path: 'e2e-user-1/job-job-pic-1-copy.png', role: 'image', contentType: 'image/png' })+ }+ if (path === '/api/jobs/job-pic-1') return json(route, 200, job('job-pic-1', 'image', 'z-image', 'succeeded', 'https://lu-labs.ai/e2e/picture.png'))+ if (path === '/api/jobs/job-mesh-1') return json(route, 200, job('job-mesh-1', '3d', 'trellis-2', meshStatus, meshStatus === 'succeeded' ? 'https://lu-labs.ai/e2e/model.glb' : null))+ if (path === '/e2e/picture.png') return route.fulfill({ status: 200, headers: { ...CORS, 'content-type': 'image/png' }, body: PICTURE })+ if (path === '/e2e/model.glb') return route.fulfill({ status: 200, headers: { ...CORS, 'content-type': 'model/gltf-binary' }, body: triangleGlb() })+ return route.fallback()+ })+ return seen+}++async function bootInto3dText(page: Page, meshStatus: 'succeeded' | 'failed' = 'succeeded'): Promise<Seen> {+ await page.addInitScript(tauriMockInit, WINDOWS_OPTS)+ await seedOnboardingDone(page)+ await routeCloud(page, {+ license: 'active', access: true, mediaLive: true,+ extraCatalogModels: [+ { id: 'z-image', label: 'Z-Image Base', kind: 'image', adult: true, ops: ['studio'], quote_required: true, tier: 'best', weights: 'open' },+ { id: 'trellis-2', label: 'TRELLIS.2', kind: '3d', ops: ['studio'], quote_required: true, tier: 'best', weights: 'open', mesh: 'image' },+ { id: 'hunyuan-3d-3.1-text', label: 'Hunyuan3D 3.1 Rapid', kind: '3d', ops: ['studio'], quote_required: true, tier: 'standard', weights: 'open-family', mesh: 'text' },+ ],+ })+ const seen = await routePictureFirst(page, meshStatus)+ await page.goto('/')+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })+ await signInViaGate(page)+ await expect(cloudSwitch(page)).toBeChecked({ timeout: 20_000 })+ await page.getByRole('button', { name: /^Create$/ }).click()+ await page.getByRole('radio', { name: /3D/ }).first().click()+ await page.getByRole('radio', { name: 'From text' }).click()+ return seen+}++test('Picture first is the default on the Text way, priced as picture plus model', async ({ page }) => {+ await bootInto3dText(page)+ await expect(page.getByTestId('three-d-picture-first')).toHaveText('LU paints a picture first, then builds the model from it.')+ await page.screenshot({ path: test.info().outputPath('picture-first-ready.png') })+ const chip = page.locator('button[aria-haspopup="listbox"]').last()+ await expect(chip).toContainText('Picture first')+ await chip.click()+ await expect(page.getByRole('option', { name: /Picture first/ })).toContainText('21k cr')+ await expect(page.getByRole('option', { name: /Hunyuan3D/ })).toBeVisible()+ await page.screenshot({ path: test.info().outputPath('picture-first-picker.png') })+})++test('the run paints, shows the picture, and builds the model from it', async ({ page }) => {+ const seen = await bootInto3dText(page)+ await page.locator('textarea').first().fill('classical marble statue of an athlete')+ await page.getByRole('button', { name: /^Create$/ }).last().click()+ await expect.poll(() => seen.submits.length, { timeout: 30_000 }).toBe(2)+ expect(seen.submits.map((s) => [s.kind, s.model])).toEqual([['image', 'z-image'], ['3d', 'trellis-2']])+ expect(seen.submits[0].prompt).toContain('a single object, whole and centered')+ expect(seen.submits[0].params).toMatchObject({ op: 'studio', max_credits: 1000 })+ expect(seen.adopted).toEqual(['job-pic-1'])+ expect(seen.submits[1].params).toMatchObject({ op: 'studio', max_credits: 20000, source_path: 'e2e-user-1/job-job-pic-1-copy.png' })+ expect(String(seen.submits[1].params.source_prompt)).toContain('classical marble statue of an athlete')+ // The picture stands on the Stage under "From image".+ await expect(page.getByRole('radio', { name: 'From image' })).toBeChecked({ timeout: 15_000 })+ await page.screenshot({ path: test.info().outputPath('picture-first-done.png') })+})++test('a failed model keeps the picture and says so', async ({ page }) => {+ const seen = await bootInto3dText(page, 'failed')+ await page.locator('textarea').first().fill('a clay teapot with a bamboo handle')+ await page.getByRole('button', { name: /^Create$/ }).last().click()+ await expect(page.getByText(/Your picture is in the gallery and on the Stage/)).toBeVisible({ timeout: 30_000 })+ expect(seen.submits).toHaveLength(2)+ // On the Stage, and one entry in the gallery.+ await expect(page.getByRole('img', { name: 'source' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Open the gallery' })).toContainText('1')+ await expect(page.getByRole('radio', { name: 'From image' })).toBeChecked()+ await page.screenshot({ path: test.info().outputPath('picture-first-failed.png') })+})diff --git a/src/hooks/__tests__/useCloudCreate-picture-first.test.ts b/src/hooks/__tests__/useCloudCreate-picture-first.test.tsnew file mode 100644index 00000000..f519a14e--- /dev/null+++ b/src/hooks/__tests__/useCloudCreate-picture-first.test.ts@@ -0,0 +1,165 @@+/**+ * "Picture first" through the real cloud hook (3.1.0): 3D from words on the+ * picture-first pick books a picture on an open image model, lands it in the+ * gallery and on the Stage, then builds the model from it. Nothing is+ * generated: submit, quote, adopt and polling are mocked.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('react', async (orig) => {+ const actual = (await orig()) as Record<string, unknown>+ return { ...actual, useCallback: (fn: unknown) => fn }+})++const hoisted = vi.hoisted(() => {+ class FakeCloudJobError extends Error {+ status: number+ code?: string+ constructor(message: string, status: number, meta?: { code?: string }) {+ super(message)+ this.status = status+ this.code = meta?.code+ }+ }+ class FakeQuoteChangedError extends FakeCloudJobError {+ credits: number+ constructor(message: string, credits: number) {+ super(message, 409, { code: 'quote_changed' })+ this.credits = credits+ }+ }+ const submitted: Array<{ kind: string; model: string; prompt: string; params: Record<string, unknown> }> = []+ const meshResult = { status: 'succeeded' as string, error: null as string | null }+ return {+ FakeCloudJobError,+ FakeQuoteChangedError,+ submitted,+ meshResult,+ uploadInput: vi.fn(async () => 'user-1/staged-source.png'),+ adoptInput: vi.fn(async (jobId: string) => `user-1/job-${jobId}-copy.jpg`),+ submitCloudJob: vi.fn(async (payload: (typeof submitted)[number]) => {+ submitted.push(payload)+ return { id: payload.kind === 'image' ? 'job-picture' : payload.kind === '3d' ? 'job-mesh' : 'job-other', quota: { cost: 1, used: 1, limit: 100 } }+ }),+ pollJob: vi.fn(async (id: string) => (id === 'job-picture'+ ? { id, kind: 'image', model: 'z-image', status: 'succeeded', result_url: 'https://storage.example/picture.jpg', attestation: null, created_at: '', error: null }+ : { id, kind: '3d', model: 'trellis-2', status: meshResult.status, result_url: meshResult.status === 'succeeded' ? 'https://storage.example/model.glb' : null, attestation: null, created_at: '', error: meshResult.error })),+ cancelJob: vi.fn(async () => ({ status: 'canceled' })),+ getJob: vi.fn(),+ studioQuote: vi.fn(async (model: string) => ({ credits: model === 'z-image' ? 1000 : 20000 })),+ }+})+const { submitted } = hoisted++vi.mock('../useContentPolicy', () => ({+ contentPolicySnapshot: () => 'off' as const,+ loadContentPolicy: async () => 'off' as const,+}))+vi.mock('../../api/cloud/jobs', () => ({+ uploadInput: hoisted.uploadInput,+ adoptInput: hoisted.adoptInput,+ getJob: hoisted.getJob,+ submitCloudJob: hoisted.submitCloudJob,+ pollJob: hoisted.pollJob,+ cancelJob: hoisted.cancelJob,+ CloudJobError: hoisted.FakeCloudJobError,+ QuoteChangedError: hoisted.FakeQuoteChangedError,+}))+vi.mock('../../api/cloud/studio', () => ({+ studioQuote: hoisted.studioQuote,+ StudioQuoteChangedError: hoisted.FakeQuoteChangedError,+}))+vi.mock('../../components/create/experimental/loadImage', () => ({+ loadImageRef: vi.fn(async (f: File) => ({ filename: f.name, name: f.name, url: 'data:image/jpeg;base64,AA', width: 1024, height: 1024 })),+}))++import { useCloudCreate } from '../useCloudCreate'+import { useCreateStore } from '../../stores/createStore'+import { useCloudCatalogStore } from '../../stores/cloudCatalogStore'+import { neuerServer } from '../../lib/render/__tests__/fixtures/test-catalogs'+import { threeDPicturePrompt } from '../../lib/three/run-local-3d'+import { THREE_D_TEXT } from '../../lib/three/three-d-text'++const PROMPT = 'classical marble statue of an athlete'++beforeEach(() => {+ submitted.length = 0+ hoisted.meshResult.status = 'succeeded'+ hoisted.meshResult.error = null+ hoisted.adoptInput.mockClear()+ hoisted.studioQuote.mockClear()+ hoisted.studioQuote.mockImplementation(async (model: string) => ({ credits: model === 'z-image' ? 1000 : 20000 }))+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, blob: async () => new Blob(['x'], { type: 'image/jpeg' }) })))+ useCloudCatalogStore.setState({+ models: [+ ...neuerServer(),+ { id: 'z-image', label: 'Z-Image Base', kind: 'image', adult: true, quote_required: true, tier: 'best', weights: 'open' },+ { id: 'trellis-2', label: 'TRELLIS.2', kind: '3d', quote_required: true, tier: 'best', weights: 'open' },+ { id: 'hunyuan-3d-3.1-text', label: 'Hunyuan3D 3.1 Rapid', kind: '3d', quote_required: true, tier: 'standard', weights: 'open-family' },+ ] as ReturnType<typeof neuerServer>,+ })+ useCreateStore.setState({+ isGenerating: false, error: null, backend: 'cloud', source: null, gallery: [],+ cloudStudioOptions: {}, cloudStudioCredits: 20000, cloudOpModel: '', threeDViews: [],+ })+ const s = useCreateStore.getState()+ s.setIntent('3d')+ s.setThreeDWay('text')+ s.setPrompt(PROMPT)+})++describe('Picture first in the cloud', () => {+ it('paints on the open model, shows the picture, then builds from the copied picture', async () => {+ const before = useCreateStore.getState().cloudImageModel+ await useCloudCreate().generate()+ const st = useCreateStore.getState()+ expect(st.error).toBeNull()+ expect(submitted.map((j) => [j.kind, j.model])).toEqual([['image', 'z-image'], ['3d', 'trellis-2']])+ expect(submitted[0].prompt).toBe(threeDPicturePrompt(PROMPT))+ expect(submitted[0].params).toMatchObject({ op: 'studio', max_credits: 1000 })+ expect(hoisted.adoptInput).toHaveBeenCalledWith('job-picture', 'image')+ expect(submitted[1].params).toMatchObject({ op: 'studio', max_credits: 20000, source_path: 'user-1/job-job-picture-copy.jpg' })+ expect(String(submitted[1].params.source_prompt)).toContain(PROMPT)+ // Both land: the model first in the gallery, the picture behind it.+ expect(st.gallery.map((g) => [g.type, g.jobId])).toEqual([['3d', 'job-mesh'], ['image', 'job-picture']])+ // The picture is on the Stage under "From image", the Image tab's pick untouched.+ expect(st.threeDWay).toBe('image')+ expect(st.source?.url).toBe('data:image/jpeg;base64,AA')+ expect(st.cloudImageModel).toBe(before)+ expect(st.isGenerating).toBe(false)+ })++ it('a failed model keeps the picture and says so', async () => {+ hoisted.meshResult.status = 'failed'+ hoisted.meshResult.error = 'provider error'+ await useCloudCreate().generate()+ const st = useCreateStore.getState()+ expect(st.gallery.map((g) => g.type)).toEqual(['image'])+ expect(st.error).toContain(THREE_D_TEXT.meshFailed)+ expect(st.source).not.toBeNull()+ expect(st.isGenerating).toBe(false)+ })++ it('a refused prompt books nothing', async () => {+ useCreateStore.getState().setPrompt('nude schoolgirl')+ await useCloudCreate().generate()+ expect(submitted).toHaveLength(0)+ expect(hoisted.studioQuote).not.toHaveBeenCalled()+ expect(useCreateStore.getState().error).toBeTruthy()+ })++ it('a higher confirmed price books nothing and shows the new sum', async () => {+ hoisted.studioQuote.mockImplementation(async (model: string) => ({ credits: model === 'z-image' ? 1000 : 40000 }))+ await useCloudCreate().generate()+ expect(submitted).toHaveLength(0)+ expect(useCreateStore.getState().error).toContain('41,000 credits')+ expect(useCreateStore.getState().cloudStudioCredits).toBe(40000)+ })++ it('a direct text model still runs as one job', async () => {+ useCreateStore.getState().setCloudOpModel('hunyuan-3d-3.1-text')+ await useCloudCreate().generate()+ expect(submitted.map((j) => j.model)).toEqual(['hunyuan-3d-3.1-text'])+ expect(hoisted.adoptInput).not.toHaveBeenCalled()+ })+})diff --git a/src/lib/render/__tests__/data-url-fetch-guard.test.ts b/src/lib/render/__tests__/data-url-fetch-guard.test.tsindex 0f21fbda..71d564df 100644--- a/src/lib/render/__tests__/data-url-fetch-guard.test.ts+++ b/src/lib/render/__tests__/data-url-fetch-guard.test.ts@@ -26,7 +26,7 @@ const SERVER_ONLY: Record<string, Record<string, string>> = {// web address the call named itself is fetched by the browser.'api/vram-handoff.ts': { url: 'an http(s) address the call named, never a file of the local image engine' },'lib/backend-detector.ts': { url: 'probes of local server ports' },- 'hooks/useCloudCreate.ts': { 'vj.result_url': 'signed result URL of a cloud job', 'src.result_url': 'signed result URL of a cloud job' },+ 'hooks/useCloudCreate.ts': { 'vj.result_url': 'signed result URL of a cloud job', 'src.result_url': 'signed result URL of a cloud job', 'job.result_url!': 'signed result URL of a cloud job' },'components/create/experimental/PresetWorkshop.tsx': { 'fresh.result_url': 'signed result URL of a cloud job' },'components/chat/create/save-media.ts': { url: 'result URL of an order card, always a server file' },// The phone. None of the seven reads media; each sends a request to a server address the app builds.diff --git a/src/lib/three/__tests__/cloud-picture-first.test.ts b/src/lib/three/__tests__/cloud-picture-first.test.tsnew file mode 100644index 00000000..e20a5fff--- /dev/null+++ b/src/lib/three/__tests__/cloud-picture-first.test.ts@@ -0,0 +1,204 @@+// "Picture first" in the cloud: the order of the two runs, the price the+// button shows, the content gate before each run, and that a failed or+// stopped second run keeps the picture.+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import schemas from '../../render/provider-schemas.json'+import { STUDIO_MODELS, type Schema } from '../../render/studio-contract'+import { useCloudCatalogStore } from '../../../stores/cloudCatalogStore'+import { checkPromptSafety } from '../../render/safety'+import { installContentPolicyCap } from '../../content-policy-cap'+import { intentPickerModels, resolveIntentPick } from '../../render/create-studio'+import type { CloudJob } from '../../../api/cloud/jobs'+import { runCloudPictureFirst, pictureFirstProvenance, type PictureFirstDeps, type PictureFirstPlan } from '../cloud-picture-first'+import { PICTURE_FIRST_MESH, isPictureFirstRun, pictureFirstOffered, pictureFirstPictureCredits, pictureFirstPictureModel, pictureStepCredits } from '../picture-first'+import { threeDPicturePrompt } from '../run-local-3d'+import { THREE_D_TEXT } from '../three-d-text'+import { MESH_TEXT, installThreeDStudio, threeDCatalogEntries } from '../../../mobile/screens/create/__tests__/fixtures/three-d-models'++let undo: () => void = () => {}+let catalogBefore: ReturnType<typeof useCloudCatalogStore.getState>['models']+const OPEN = { id: 'z-image', label: 'Z-Image Base', kind: 'image', adult: true, quote_required: true, tier: 'best', weights: 'open' }+const CAPPED = { id: 'qwen-image-2.1', label: 'Qwen Image 2.1', kind: 'image', quote_required: true, tier: 'best', weights: 'open' }++beforeAll(() => {+ undo = installThreeDStudio(STUDIO_MODELS, schemas as Record<string, Schema>)+ catalogBefore = useCloudCatalogStore.getState().models+})+afterAll(() => {+ undo()+ useCloudCatalogStore.setState({ models: catalogBefore })+})+beforeEach(() => {+ useCloudCatalogStore.setState({ models: [...catalogBefore, ...threeDCatalogEntries(), OPEN, CAPPED] as typeof catalogBefore })+})++describe('the pick', () => {+ it('paints with the open image model that has the filter off', () => {+ expect(STUDIO_MODELS['z-image']).toMatchObject({ kind: 'image', adult: true, weights: 'open', inputs: {} })+ expect(pictureFirstPictureModel()).toBe('z-image')+ expect(pictureFirstOffered()).toBe(true)+ })++ it('a build that caps the content policy paints with a filtered open model', () => {+ const off = installContentPolicyCap(() => 'soft')+ try {+ expect(pictureFirstPictureModel()).toBe('qwen-image-2.1')+ } finally {+ off()+ }+ })++ it('leads the "From text" list and is its default, next to the direct models', () => {+ const list = intentPickerModels('3d-text')+ expect(list.map((m) => m.id)).toEqual([PICTURE_FIRST_MESH, MESH_TEXT])+ expect(list[0].label).toBe(THREE_D_TEXT.pictureFirstSwitch)+ expect(resolveIntentPick('3d-text', '')).toBe(PICTURE_FIRST_MESH)+ expect(resolveIntentPick('3d-text', MESH_TEXT)).toBe(MESH_TEXT)+ // The picture way keeps its own list and name.+ expect(intentPickerModels('3d-image').find((m) => m.id === PICTURE_FIRST_MESH)?.label).toBe('TRELLIS.2')+ })++ it('is not offered when the server lists no open image model or no image-to-3D model', () => {+ useCloudCatalogStore.setState({ models: [...catalogBefore, ...threeDCatalogEntries()] as typeof catalogBefore })+ expect(pictureFirstOffered()).toBe(false)+ expect(intentPickerModels('3d-text').map((m) => m.id)).toEqual([MESH_TEXT])+ useCloudCatalogStore.setState({ models: [...catalogBefore, ...threeDCatalogEntries().filter((m) => m.id !== PICTURE_FIRST_MESH), OPEN] as typeof catalogBefore })+ expect(pictureFirstOffered()).toBe(false)+ })++ it('only an image-to-3D model on the text way is a picture-first run', () => {+ expect(isPictureFirstRun('text', PICTURE_FIRST_MESH)).toBe(true)+ expect(isPictureFirstRun('image', PICTURE_FIRST_MESH)).toBe(false)+ expect(isPictureFirstRun('text', MESH_TEXT)).toBe(false)+ expect(isPictureFirstRun('text', 'z-image')).toBe(false)+ })++ it('the price shown is the picture plus the model', () => {+ // Z-Image Base is a flat 0.01 USD, 1,000 credits.+ expect(pictureFirstPictureCredits('a clay teapot')).toBe(1000)+ expect(pictureStepCredits('3d', 'text', PICTURE_FIRST_MESH, 'a clay teapot')).toBe(1000)+ expect(pictureStepCredits('3d', 'image', PICTURE_FIRST_MESH, 'a clay teapot')).toBe(0)+ expect(pictureStepCredits('3d', 'text', MESH_TEXT, 'a clay teapot')).toBe(0)+ expect(pictureStepCredits('image', 'text', PICTURE_FIRST_MESH, 'a clay teapot')).toBe(0)+ })+})++// ---------- the chain ----------++const job = (id: string, over: Partial<CloudJob> = {}): CloudJob => ({+ id, kind: 'image', model: 'z-image', provider: null, status: 'succeeded', result_url: `https://store.example/${id}.png`,+ attestation: null, cost_units: 0, created_at: '', completed_at: '', error: null, ...over,+})++function rig(over: { prices?: Record<string, number>; second?: Partial<CloudJob>; first?: Partial<CloudJob>; gate?: PictureFirstDeps['gate']; stopAfterPicture?: boolean } = {}) {+ const log: string[] = []+ const submits: Parameters<PictureFirstDeps['submit']>[0][] = []+ const gated: string[] = []+ let stop = false+ const prices = over.prices ?? { 'z-image': 1000, [PICTURE_FIRST_MESH]: 20000 }+ const deps: PictureFirstDeps = {+ gate: (text) => {+ gated.push(text)+ return over.gate ? over.gate(text) : checkPromptSafety(text, { tier: 'cloud', policy: 'off' })+ },+ quote: async (model) => { log.push(`quote ${model}`); return prices[model] },+ submit: async (j) => { submits.push(j); log.push(`submit ${j.model}`); return { id: j.kind === 'image' ? 'job-1' : 'job-2' } },+ poll: async (id) => { log.push(`poll ${id}`); return id === 'job-1' ? job(id, over.first) : job(id, { kind: '3d', model: PICTURE_FIRST_MESH, ...over.second }) },+ adopt: async (id) => { log.push(`adopt ${id}`); return `user/job-${id}-x.png` },+ onPicture: async (j) => { log.push(`picture ${j.id}`); if (over.stopAfterPicture) stop = true },+ onBooked: (id) => { log.push(`booked ${id}`) },+ stopped: () => stop,+ }+ return { deps, log, submits, gated }+}++const plan = (over: Partial<PictureFirstPlan> = {}): PictureFirstPlan => ({+ prompt: 'classical marble statue of an athlete', pictureModel: 'z-image', meshModel: PICTURE_FIRST_MESH,+ meshOptions: { resolution: 1024 }, shown: { mesh: 20000, picture: 1000 }, requestIds: ['r1', 'r2'], ...over,+})++describe('the chain', () => {+ it('paints, shows the picture, then builds the model from the copied picture', async () => {+ const r = rig()+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out.kind).toBe('done')+ expect(r.log).toEqual([+ 'quote z-image', `quote ${PICTURE_FIRST_MESH}`,+ 'submit z-image', 'booked job-1', 'poll job-1', 'picture job-1',+ 'adopt job-1', `submit ${PICTURE_FIRST_MESH}`, 'booked job-2', 'poll job-2',+ ])+ const [one, two] = r.submits+ expect(one).toMatchObject({ kind: 'image', model: 'z-image', prompt: threeDPicturePrompt(plan().prompt) })+ expect(one.params).toMatchObject({ op: 'studio', studio_options: {}, client_request_id: 'r1', max_credits: 1000 })+ expect(two).toMatchObject({ kind: '3d', model: PICTURE_FIRST_MESH, prompt: '' })+ expect(two.params).toMatchObject({+ op: 'studio', studio_options: { resolution: 1024 }, client_request_id: 'r2', max_credits: 20000,+ source_path: 'user/job-job-1-x.png', source_prompt: pictureFirstProvenance(plan().prompt),+ label: plan().prompt,+ })+ // The server's gate reads the user's words with the picture.+ expect(two.params.source_prompt).toContain(plan().prompt)+ })++ it('runs the gate on the prompt before the first run and with the provenance before the second', async () => {+ const r = rig()+ await runCloudPictureFirst(plan(), r.deps)+ expect(r.gated).toEqual([`${plan().prompt} ${threeDPicturePrompt(plan().prompt)}`, pictureFirstProvenance(plan().prompt)])+ })++ it('a refused prompt books nothing and asks for no price', async () => {+ const r = rig()+ const out = await runCloudPictureFirst(plan({ prompt: 'nude schoolgirl' }), r.deps)+ expect(out).toMatchObject({ kind: 'blocked', step: 1 })+ expect(r.log).toEqual([])+ })++ it('a refusal before the second run keeps the picture and books no model', async () => {+ let calls = 0+ const r = rig({ gate: () => ({ blocked: ++calls === 2, reason: 'csam' }) })+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out).toMatchObject({ kind: 'blocked', step: 2 })+ expect(r.log).toContain('picture job-1')+ expect(r.log.some((l) => l.startsWith('adopt'))).toBe(false)+ expect(r.submits).toHaveLength(1)+ })++ it('a higher confirmed sum books nothing and names the new sum', async () => {+ const r = rig({ prices: { 'z-image': 1000, [PICTURE_FIRST_MESH]: 40000 } })+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out).toEqual({ kind: 'price', total: 41000, mesh: 40000 })+ expect(r.submits).toHaveLength(0)+ })++ it('a lower or equal sum books, each run capped at its own confirmed price', async () => {+ const r = rig({ prices: { 'z-image': 1000, [PICTURE_FIRST_MESH]: 10000 } })+ expect((await runCloudPictureFirst(plan(), r.deps)).kind).toBe('done')+ expect(r.submits.map((s) => s.params.max_credits)).toEqual([1000, 10000])+ })++ it('a failed second run keeps the picture', async () => {+ const r = rig({ second: { status: 'failed', result_url: null, error: 'provider error' } })+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out.kind).toBe('mesh-failed')+ if (out.kind === 'mesh-failed') {+ expect(out.picture.id).toBe('job-1')+ expect(out.job.error).toBe('provider error')+ }+ expect(r.log).toContain('picture job-1')+ })++ it('a failed picture builds no model', async () => {+ const r = rig({ first: { status: 'failed', result_url: null, error: 'no' } })+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out.kind).toBe('picture-failed')+ expect(r.submits).toHaveLength(1)+ expect(r.log.some((l) => l.startsWith('picture'))).toBe(false)+ })++ it('Stop after the picture keeps it and books no model', async () => {+ const r = rig({ stopAfterPicture: true })+ const out = await runCloudPictureFirst(plan(), r.deps)+ expect(out).toMatchObject({ kind: 'stopped', picture: { id: 'job-1' } })+ expect(r.submits).toHaveLength(1)+ })+})diff --git a/src/mobile/screens/create/__tests__/three-d-picture-first.test.ts b/src/mobile/screens/create/__tests__/three-d-picture-first.test.tsnew file mode 100644index 00000000..518a53bb--- /dev/null+++ b/src/mobile/screens/create/__tests__/three-d-picture-first.test.ts@@ -0,0 +1,77 @@+/**+ * "Picture first" on the phone (3.1.0, cloud only): the 3D tool's Text way+ * offers it first, prices it as picture plus model, and names it.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import schemas from '../../../../lib/render/provider-schemas.json'+import { STUDIO_MODELS, type Schema } from '../../../../lib/render/studio-contract'+import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'+import { useCreateStore } from '../../../../stores/createStore'+import { installContentPolicyCap } from '../../../../lib/content-policy-cap'+import { pictureFirstPictureModel } from '../../../../lib/three/picture-first'+import { CREATE_STRINGS as T } from '../../../strings/create'+import { runModel, toolModels } from '../parts/catalog'+import { threeDModelFacts } from '../parts/three-d'+import { MESH_IMAGE, MESH_TEXT, installThreeDStudio, threeDCatalogEntries } from './fixtures/three-d-models'++const picks = { cloudImageModel: '', cloudVideoModel: '', cloudOpModel: '' }+const fallbackCredits = { image: null, video: null, audio: null }+const rows = (way: 'text' | 'image') => toolModels('3d', { character: null, characterUse: false, musicSeconds: 0, fallbackCredits, threeDWay: way })++let undo: () => void = () => {}+let catalogBefore: ReturnType<typeof useCloudCatalogStore.getState>['models']++beforeAll(() => {+ undo = installThreeDStudio(STUDIO_MODELS, schemas as Record<string, Schema>)+ catalogBefore = useCloudCatalogStore.getState().models+})+afterAll(() => {+ undo()+ useCloudCatalogStore.setState({ models: catalogBefore })+})+beforeEach(() => {+ useCloudCatalogStore.setState({+ models: [+ ...catalogBefore, ...threeDCatalogEntries(),+ { id: 'z-image', label: 'Z-Image Base', kind: 'image', adult: true, quote_required: true, tier: 'best', weights: 'open' },+ { id: 'qwen-image-2.1', label: 'Qwen Image 2.1', kind: 'image', quote_required: true, tier: 'best', weights: 'open' },+ ] as typeof catalogBefore,+ })+ useCreateStore.getState().setIntent('3d')+ useCreateStore.setState({ threeDWay: 'text', threeDViews: [], source: null, cloudStudioOptions: {}, cloudOpModel: '' })+})++describe('Picture first on the phone', () => {+ it('leads the Text way and is the model that runs by default', () => {+ const list = rows('text')+ expect(list.map((r) => r.id).sort()).toEqual([MESH_IMAGE, MESH_TEXT].sort())+ expect(list.find((r) => r.id === MESH_IMAGE)?.label).toBe('Picture first')+ expect(runModel('3d', picks, null, false, 'text')).toMatchObject({ id: MESH_IMAGE, studio: true })+ expect(runModel('3d', { ...picks, cloudOpModel: MESH_TEXT }, null, false, 'text').id).toBe(MESH_TEXT)+ })++ it('its row costs the picture and the model together, the picture way only the model', () => {+ const text = rows('text').find((r) => r.id === MESH_IMAGE)+ const image = rows('image').find((r) => r.id === MESH_IMAGE)+ // TRELLIS.2 at its default 1024 is 20,000 credits, the picture 1,000.+ expect(image?.credits).toBe(20000)+ expect(text?.credits).toBe(21000)+ expect(image?.label).toBe('TRELLIS.2')+ })++ it('says what it does, on the Text way only', () => {+ expect(threeDModelFacts(MESH_IMAGE, 'text').pictureFirst).toBe(true)+ expect(threeDModelFacts(MESH_IMAGE, 'image').pictureFirst).toBe(false)+ expect(threeDModelFacts(MESH_TEXT, 'text').pictureFirst).toBe(false)+ expect(T.threeD.pictureFirst).toBe('LU paints a picture first, then builds the model from it.')+ })++ it('a store build that caps the content policy paints with a model that keeps its filter', () => {+ const off = installContentPolicyCap(() => 'soft')+ try {+ expect(pictureFirstPictureModel()).toBe('qwen-image-2.1')+ } finally {+ off()+ }+ })+})diff --git a/src/mobile/screens/create/__tests__/three-d.test.ts b/src/mobile/screens/create/__tests__/three-d.test.tsindex 25b15870..41f1d4c7 100644--- a/src/mobile/screens/create/__tests__/three-d.test.ts+++ b/src/mobile/screens/create/__tests__/three-d.test.ts@@ -118,10 +118,10 @@ describe('the catalog decides', () => {})it('a model says how many pictures it takes and whether it has a detail step', () => {- expect(threeDModelFacts(MESH_VIEWS)).toEqual({ maxViews: 4, hasDetail: true })- expect(threeDModelFacts(MESH_IMAGE)).toEqual({ maxViews: 1, hasDetail: true })- expect(threeDModelFacts(MESH_TEXT)).toEqual({ maxViews: 1, hasDetail: false })- expect(threeDModelFacts(undefined)).toEqual({ maxViews: 1, hasDetail: false })+ expect(threeDModelFacts(MESH_VIEWS)).toEqual({ maxViews: 4, hasDetail: true, pictureFirst: false })+ expect(threeDModelFacts(MESH_IMAGE)).toEqual({ maxViews: 1, hasDetail: true, pictureFirst: false })+ expect(threeDModelFacts(MESH_TEXT)).toEqual({ maxViews: 1, hasDetail: false, pictureFirst: false })+ expect(threeDModelFacts(undefined)).toEqual({ maxViews: 1, hasDetail: false, pictureFirst: false })})})