Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create): move a picked LoRA up or down, the run chains them in that order (D4)

purplec548b186e35d
diff --git a/e2e/create-d4-lora-reihenfolge.spec.ts b/e2e/create-d4-lora-reihenfolge.spec.ts
new file mode 100644
index 00000000..7ab31d7a
--- /dev/null
+++ b/e2e/create-d4-lora-reihenfolge.spec.ts
@@ -0,0 +1,153 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { gradientPng } from './support/png'
+
+/**
+ * 3.0.9 D4, clicked through on a stand-in ComfyUI (Windows or Linux, local):
+ * two LoRAs picked, the second moved up with its button, and the graph posted
+ * to /prompt chains them in the new order. The order is saved with the picks
+ * and is still there after a reload. LU_SHOTS=<folder> writes the screenshots.
+ * The stand-in is the one of create-q1-309.spec.ts.
+ */
+
+const MODEL = 'juggernautXL.safetensors'
+const VIDEO = 'wan2.2_t2v_14B_fp8.safetensors'
+const LORAS = ['film_grain_xl.safetensors', 'detail_tweaker_xl.safetensors']
+const SHOTS = process.env.LU_SHOTS
+const PNG = gradientPng(512, 384).toString('base64')
+
+type Posted = { prompt: Record<string, { class_type: string; inputs: Record<string, unknown> }> }
+
+async function boot(page: Page) {
+ await page.addInitScript(tauriMockInit, { assistantReply: 'Turn only her jacket deep red and keep everything else exactly as it is.', modelName: DEFAULT_MODEL_NAME, platform: 'windows' as const })
+ await seedOnboardingDone(page)
+ await page.addInitScript(([list, model, video]) => {
+ const w = window as unknown as { __PROMPTS__: string[]; __TAURI_INTERNALS__: { invoke: (c: string, a: { url?: string; method?: string; body?: string }) => Promise<unknown> } }
+ if (!localStorage.getItem('create-store')) {
+ localStorage.setItem('create-store', JSON.stringify({ state: { backend: 'local', imageModel: model, videoModel: video }, version: 2 }))
+ }
+ w.__PROMPTS__ = []
+ const bridge = w.__TAURI_INTERNALS__
+ const invoke = bridge.invoke
+ const combo = (v: string[]) => [v]
+ const nodes = {
+ CheckpointLoaderSimple: { input: { required: { ckpt_name: combo([model as string]) } } },
+ UNETLoader: { input: { required: { unet_name: combo([video as string]) } } },
+ LoraLoader: { input: { required: { lora_name: combo(list as string[]) } } },
+ VAELoader: { input: { required: { vae_name: combo(['ae.safetensors']) } } },
+ KSampler: { input: { required: { sampler_name: combo(['euler']), scheduler: combo(['simple']) } } },
+ EmptyLatentImage: { input: { required: {} } }, CLIPTextEncode: { input: { required: {} } },
+ VAEEncode: { input: { required: {} } }, VAEDecode: { input: { required: {} } }, SaveImage: { input: { required: {} } },
+ LoadImage: { input: { required: { image: combo(['source.png']) } } }, RepeatLatentBatch: { input: { required: {} } },
+ } as Record<string, unknown>
+ // As many pictures as the graph makes: the repeat of an edit, else one.
+ const made = (body: string) => {
+ const graph = JSON.parse(body).prompt as Record<string, { class_type: string; inputs: Record<string, unknown> }>
+ const repeat = Object.values(graph).find((n) => n.class_type === 'RepeatLatentBatch')
+ return Number(repeat?.inputs.amount ?? 1)
+ }
+ bridge.invoke = (command, args) => {
+ if (command === 'sniff_model_files') return Promise.resolve([])
+ if (command !== 'proxy_localhost' || !args?.url?.includes(':8188')) return invoke(command, args)
+ const url = args.url
+ if (url.includes('/system_stats')) return Promise.resolve(JSON.stringify({ devices: [{ name: 'RTX 3060', type: 'cuda', vram_total: 12 * 1024 ** 3 }] }))
+ if (url.endsWith('/prompt') && args.method === 'POST') {
+ w.__PROMPTS__.push(String(args.body))
+ return Promise.resolve(JSON.stringify({ prompt_id: `p${w.__PROMPTS__.length}`, number: 1, node_errors: {} }))
+ }
+ const hist = /\/history\/(p(\d+))/.exec(url)
+ if (hist) {
+ const n = made(w.__PROMPTS__[Number(hist[2]) - 1])
+ const images = Array.from({ length: n }, (_, i) => ({ filename: `q1_${hist[1]}_${i}.png`, subfolder: '', type: 'output' }))
+ return Promise.resolve(JSON.stringify({ [hist[1]]: { status: { status_str: 'success', completed: true, messages: [] }, outputs: { '9': { images } } } }))
+ }
+ if (url.includes('/queue')) return Promise.resolve(JSON.stringify({ queue_running: [], queue_pending: [] }))
+ const one = /\/object_info\/([^/?]+)/.exec(url)
+ if (one) return Promise.resolve(JSON.stringify(one[1] in nodes ? { [one[1]]: nodes[one[1]] } : {}))
+ if (url.includes('/object_info')) return Promise.resolve(JSON.stringify(nodes))
+ return Promise.resolve('{}')
+ }
+ }, [LORAS, MODEL, VIDEO] as const)
+ // The pictures the stand-in names are served as they would be by ComfyUI.
+ await page.route(/:8188\/view/, (route) => route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(PNG, 'base64') }))
+}
+
+const shot = async (page: Page, name: string) => {
+ if (!SHOTS) return
+ // The large view and the drawer fade in: the picture waits for them.
+ await page.waitForTimeout(600)
+ await page.screenshot({ path: `${SHOTS}/${name}.png` })
+}
+
+async function openCreate(page: Page, tab: string) {
+ await page.goto('/')
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: tab, exact: true }).click()
+}
+
+
+async function pickLora(page: Page, name: string) {
+ await page.getByRole('button', { name: 'Advanced settings' }).click()
+ const expert = page.getByRole('button', { name: 'Expert', exact: true })
+ await expect(expert).toBeVisible({ timeout: 15_000 })
+ if (!(await page.getByText(/^LoRA stack/).isVisible())) await expert.click()
+ await page.getByRole('button', { name: new RegExp(name.replace('.safetensors', '')) }).first().click()
+ await page.keyboard.press('Escape')
+}
+
+const posted = (page: Page) => page.evaluate(() => (window as unknown as { __PROMPTS__: string[] }).__PROMPTS__.map((p) => JSON.parse(p) as Posted))
+const savedLoras = (page: Page) => page.evaluate(() => (JSON.parse(localStorage.getItem('create-store') || '{}').state?.selectedLoras ?? []).map((l: { name: string }) => l.name))
+
+
+/** The LoRAs from the checkpoint to the sampler, in chain order. */
+function chain(graph: Posted['prompt']): string[] {
+ const sampler = Object.values(graph).find((n) => n.class_type === 'KSampler')!
+ const out: string[] = []
+ let at = (sampler.inputs.model as [string, number])[0]
+ while (graph[at]?.class_type === 'LoraLoader') {
+ out.unshift(String(graph[at].inputs.lora_name))
+ at = (graph[at].inputs.model as [string, number])[0]
+ }
+ return out
+}
+
+async function openStack(page: Page) {
+ await page.getByRole('button', { name: 'Advanced settings' }).click()
+ const expert = page.getByRole('button', { name: 'Expert', exact: true })
+ await expect(expert).toBeVisible({ timeout: 15_000 })
+ if (!(await page.getByText(/^LoRA stack/).isVisible())) await expert.click()
+}
+
+test('D4: a LoRA moved up runs first, and the order is kept after a reload', async ({ page }) => {
+ await boot(page)
+ await openCreate(page, 'Image')
+ await pickLora(page, LORAS[0])
+ await pickLora(page, LORAS[1])
+ expect(await savedLoras(page)).toEqual(LORAS)
+
+ // Two picks: the order list stands above the stack, in the order of the clicks.
+ await openStack(page)
+ const order = page.getByTestId('lora-order')
+ await expect(order.getByRole('listitem')).toHaveText([/film_grain_xl/, /detail_tweaker_xl/])
+ await shot(page, 'd4-1-reihenfolge-vorher')
+ await page.getByRole('button', { name: 'Move detail_tweaker_xl up' }).click()
+ await expect(order.getByRole('listitem')).toHaveText([/detail_tweaker_xl/, /film_grain_xl/])
+ await expect.poll(() => savedLoras(page)).toEqual([LORAS[1], LORAS[0]])
+ await shot(page, 'd4-2-reihenfolge-nachher')
+ await page.keyboard.press('Escape')
+
+ await page.getByRole('textbox').filter({ hasText: '' }).first().fill('a lighthouse at dusk')
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+ await expect.poll(async () => (await posted(page)).length, { timeout: 20_000 }).toBe(1)
+ const graph = (await posted(page))[0].prompt
+ expect(chain(graph)).toEqual([LORAS[1], LORAS[0]])
+ console.log(`[D4] LoRA chain in the posted graph: ${chain(graph).join(' -> ')}`)
+
+ // A reload (the app started again) keeps the order.
+ await page.reload()
+ await page.getByRole('button', { name: /^Create$/ }).first().click()
+ await expect.poll(() => savedLoras(page)).toEqual([LORAS[1], LORAS[0]])
+ await openStack(page)
+ await expect(page.getByTestId('lora-order').getByRole('listitem')).toHaveText([/detail_tweaker_xl/, /film_grain_xl/])
+})
diff --git a/src/components/create/experimental/LoraOrder.tsx b/src/components/create/experimental/LoraOrder.tsx
new file mode 100644
index 00000000..99e449a6
--- /dev/null
+++ b/src/components/create/experimental/LoraOrder.tsx
@@ -0,0 +1,50 @@
+import { ArrowDown, ArrowUp } from 'lucide-react'
+import { useCreateStore } from '../../../stores/createStore'
+import type { LoraPick } from '../../../lib/render/lora-lanes'
+
+/**
+ * D4 (3.0.9, Discord, a follow-up to B24): the LoRAs a run chains, in the
+ * order it chains them, with a button to move each one up or down. The list
+ * above it is sorted by file name and says nothing about the order, which was
+ * the order of the clicks. Shown from two picks on; the order is saved with
+ * the picks (createStore `selectedLoras`, per lane in `loraLanes`).
+ */
+export function LoraOrder({ picks, labelOf }: { picks: LoraPick[]; labelOf: (name: string) => string }) {
+ const moveLora = useCreateStore((s) => s.moveLora)
+ if (picks.length < 2) return null
+ const among = picks.map((p) => p.name)
+ return (
+ <div data-testid="lora-order" className="space-y-1">
+ <div className="t-micro text-gray-500">Order of the run, first applied first</div>
+ <ol className="space-y-0.5">
+ {picks.map((p, i) => {
+ const label = labelOf(p.name)
+ return (
+ <li key={p.name} className="flex items-center gap-1.5 t-control text-gray-300">
+ <span className="t-mono text-gray-600 w-4 shrink-0 text-right">{i + 1}</span>
+ <span className="flex-1 min-w-0 [overflow-wrap:anywhere]">{label}</span>
+ <button
+ onClick={() => moveLora(p.name, -1, among)}
+ disabled={i === 0}
+ aria-label={`Move ${label} up`}
+ title="Move up"
+ className="p-0.5 rounded text-gray-500 hover:text-gray-200 disabled:opacity-30 disabled:hover:text-gray-500"
+ >
+ <ArrowUp className="w-3 h-3" />
+ </button>
+ <button
+ onClick={() => moveLora(p.name, 1, among)}
+ disabled={i === picks.length - 1}
+ aria-label={`Move ${label} down`}
+ title="Move down"
+ className="p-0.5 rounded text-gray-500 hover:text-gray-200 disabled:opacity-30 disabled:hover:text-gray-500"
+ >
+ <ArrowDown className="w-3 h-3" />
+ </button>
+ </li>
+ )
+ })}
+ </ol>
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/ParamGroups.tsx b/src/components/create/experimental/ParamGroups.tsx
index 57c3ebe4..cb508c5c 100644
--- a/src/components/create/experimental/ParamGroups.tsx
+++ b/src/components/create/experimental/ParamGroups.tsx
@@ -27,6 +27,7 @@ import { HINWEIS_TEXT } from '../../../lib/hinweis'
import { filterLoraRows, loraCopyText, lorasForRun, loraRows } from '../../../lib/lora-stack'
import { loraStackView, setLoraStackQuery, setLoraStackScroll } from './loraStackView'
import { LoraStrength } from './LoraStrength'
+import { LoraOrder } from './LoraOrder'
import { cfgHint, loraStrengthHint } from '../../../lib/param-hints'
import { MOTION_OWN_WORKFLOW_NOTE, useMotionOwnWorkflow } from './motionWorkflow'
import { supportsTransparent } from '../../../lib/transparent-image'
@@ -112,7 +113,8 @@ export function ParamGroups() {
: !isCloud && !laneWithoutLoras && (!isVideo || VIDEO_LORA_FAMILIES.has(classifyModel(s.videoModel)))
// GH #146: the count is what a run sends, the same rule useCreate applies.
const laneType = (isVideo ? s.videoModelList : s.imageModelList).find((m) => m.name === laneModel)?.type ?? classifyModel(laneModel)
- const activeLoras = lorasForRun(s.selectedLoras, loraList, laneType).use.length
+ const runLoras = lorasForRun(s.selectedLoras, loraList, laneType).use
+ const activeLoras = runLoras.length
const stackRows = loraRows(loraList, s.selectedLoras, laneType)
// The search and the scroll position outlive the drawer (loraStackView.ts).
const [loraQuery, setLoraQuery] = useState(() => loraStackView().query)
@@ -534,6 +536,7 @@ export function ParamGroups() {
</button>
</div>
</div>
+ <LoraOrder picks={runLoras} labelOf={(name) => stackRows.find((r) => r.name === name)?.label ?? name} />
{loraList.length === 0 ? (
isMlxLocal
? <div className="t-control text-gray-600">No LoRAs found yet. Put .safetensors files into the LoRA folder (Open folder) and hit Rescan, or get one under Models, LoRAs.</div>
diff --git a/src/components/create/experimental/__tests__/lora-reihenfolge-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/lora-reihenfolge-oberflaeche.test.tsx
new file mode 100644
index 00000000..ded37c6c
--- /dev/null
+++ b/src/components/create/experimental/__tests__/lora-reihenfolge-oberflaeche.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+/**
+ * D4 (3.0.9, Discord, a follow-up to B24): the LoRA stack shows the picks in
+ * the order the run chains them, with a button to move each one up or down.
+ * A pick kept for another model is not shown and never swallows a click.
+ *
+ * Run: npx vitest run src/components/create/experimental/__tests__/lora-reihenfolge-oberflaeche.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+
+const lists = vi.hoisted(() => ({ loras: [] as string[] }))
+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({
+ samplerList: [], schedulerList: [], loraList: lists.loras, vaeList: [], refreshModelLists: vi.fn(),
+ }),
+}))
+
+import { ParamGroups } from '../ParamGroups'
+import { resetLoraStackView } from '../loraStackView'
+import { useCreateStore } from '../../../../stores/createStore'
+import { classifyModel } from '../../../../api/comfyui'
+
+const MODEL = 'juggernautXL_v9.safetensors'
+const GRAIN = 'styles/film_grain_xl.safetensors'
+const DETAIL = 'detail_slider_xl.safetensors'
+const AGE = 'age_slider_xl.safetensors'
+const CHAR = 'char_mira_zimage.safetensors'
+
+function open() {
+ render(<ParamGroups />)
+ if (!screen.queryByRole('searchbox', { name: 'Search LoRAs' })) {
+ fireEvent.click(screen.getByRole('button', { name: 'Expert' }))
+ }
+}
+const order = () => within(screen.getByTestId('lora-order')).getAllByRole('listitem').map((li) => li.textContent?.replace(/^\d+/, ''))
+const picked = () => useCreateStore.getState().selectedLoras.map((l) => l.name)
+
+beforeEach(() => {
+ lists.loras = [GRAIN, DETAIL, AGE, CHAR]
+ resetLoraStackView()
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, cloudOp: null, utilityOp: null, removebg: false,
+ expertOpen: false, selectedLoras: [], loraStrengths: {}, loraLanes: {}, selectedCharacter: null,
+ imageModel: MODEL, imageModelList: [{ name: MODEL, type: classifyModel(MODEL) }],
+ } as never)
+ useCreateStore.getState().setIntent('image')
+})
+afterEach(() => cleanup())
+
+describe('D4: the order of the picked LoRAs', () => {
+ it('one pick shows no order, two show it in the order of the clicks', () => {
+ useCreateStore.getState().toggleLora(DETAIL)
+ open()
+ expect(screen.queryByTestId('lora-order')).toBeNull()
+ cleanup()
+ useCreateStore.getState().toggleLora(GRAIN)
+ open()
+ expect(order()).toEqual(['detail_slider_xl', 'styles/film_grain_xl'])
+ })
+
+ it('up and down move the pick, the run order follows', () => {
+ const s = useCreateStore.getState()
+ s.toggleLora(DETAIL)
+ s.toggleLora(GRAIN)
+ s.toggleLora(AGE)
+ open()
+ fireEvent.click(screen.getByRole('button', { name: 'Move age_slider_xl up' }))
+ expect(order()).toEqual(['detail_slider_xl', 'age_slider_xl', 'styles/film_grain_xl'])
+ fireEvent.click(screen.getByRole('button', { name: 'Move detail_slider_xl down' }))
+ expect(picked()).toEqual([AGE, DETAIL, GRAIN])
+ expect((screen.getByRole('button', { name: 'Move age_slider_xl up' }) as HTMLButtonElement).disabled).toBe(true)
+ expect((screen.getByRole('button', { name: 'Move styles/film_grain_xl down' }) as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('a pick this model does not run is left out of the order and skipped by a move', () => {
+ // A Z-Image character stays picked on SDXL (it runs on Z-Image only).
+ useCreateStore.setState({ selectedLoras: [{ name: DETAIL, strength: 0.8 }, { name: CHAR, strength: 1 }, { name: GRAIN, strength: 0.8 }] } as never)
+ open()
+ expect(order()).toEqual(['detail_slider_xl', 'styles/film_grain_xl'])
+ fireEvent.click(screen.getByRole('button', { name: 'Move styles/film_grain_xl up' }))
+ expect(order()).toEqual(['styles/film_grain_xl', 'detail_slider_xl'])
+ expect(picked()).toEqual([GRAIN, CHAR, DETAIL])
+ })
+})
diff --git a/src/components/create/experimental/__tests__/mac-lora-stack.test.tsx b/src/components/create/experimental/__tests__/mac-lora-stack.test.tsx
index 2edf4fa0..0b7655e9 100644
--- a/src/components/create/experimental/__tests__/mac-lora-stack.test.tsx
+++ b/src/components/create/experimental/__tests__/mac-lora-stack.test.tsx
@@ -130,7 +130,7 @@ describe('the stack is handled as on Windows', () => {
expect(stack()[0]).toEqual({ name: SLIDER, strength: -4 })
expect(strength.value).toBe('-4.00')
- fireEvent.click(screen.getByRole('button', { name: /slider/ }))
+ fireEvent.click(screen.getByRole('button', { name: /^slider/ }))
expect(stack().map((l) => l.name)).toEqual([DETAIL])
expect(screen.getByText('· 1 active')).toBeTruthy()
diff --git a/src/lib/render/lora-lanes.ts b/src/lib/render/lora-lanes.ts
index f2d5da50..e0a8619e 100644
--- a/src/lib/render/lora-lanes.ts
+++ b/src/lib/render/lora-lanes.ts
@@ -43,6 +43,22 @@ export function switchLoraLane(
return { selectedLoras: [...back, ...character], loraLanes: trimmed }
}
+/** D4 (3.0.9): the picks with one moved a place up (-1) or down (1). The
+ * run chains the LoRAs in this order. `among` names the picks the stack
+ * shows (the ones this model runs): the move swaps with the next of those,
+ * so a pick kept for another model never swallows a click. The same list
+ * comes back when the move goes past either end or the name is not picked. */
+export function moveLoraPick(picks: LoraPick[], name: string, delta: -1 | 1, among?: string[]): LoraPick[] {
+ const from = picks.findIndex((p) => p.name === name)
+ if (from < 0) return picks
+ let to = from + delta
+ while (to >= 0 && to < picks.length && among && !among.includes(picks[to].name)) to += delta
+ if (to < 0 || to >= picks.length) return picks
+ const next = [...picks]
+ ;[next[from], next[to]] = [next[to], next[from]]
+ return next
+}
+
/** A trained character's LoRA (`char_<name>_zimage.safetensors`, the trainer's
* own naming, api/trainer parseLocalCharacterLora). It belongs to the picked
* character, not to a lane. */
diff --git a/src/stores/__tests__/lora-reihenfolge-aendern.test.ts b/src/stores/__tests__/lora-reihenfolge-aendern.test.ts
new file mode 100644
index 00000000..006547a8
--- /dev/null
+++ b/src/stores/__tests__/lora-reihenfolge-aendern.test.ts
@@ -0,0 +1,123 @@
+/**
+ * D4 (3.0.9, Discord, a follow-up to B24): the picked LoRAs ran in the order
+ * they were clicked, and the only way to change it was to turn them off and
+ * on again. A pick now moves up or down in the stack, the order is kept with
+ * the picks (on the lane B24 files them under, and across a restart), and the
+ * run chains the LoRAs in that order.
+ *
+ * Run: npx vitest run src/stores/__tests__/lora-reihenfolge-aendern.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../../api/comfyui-nodes', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../api/comfyui-nodes')>()
+ return { ...actual, getAllNodeInfo: vi.fn() }
+})
+
+import { useCreateStore } from '../createStore'
+import { buildDynamicWorkflow } from '../../api/dynamic-workflow'
+import { getAllNodeInfo } from '../../api/comfyui-nodes'
+import { moveLoraPick } from '../../lib/render/lora-lanes'
+import type { ComfyApiGraph } from '../../types/comfy-graph'
+
+const A = 'pixel-art-xl.safetensors'
+const B = 'detail-tweaker.safetensors'
+const C = 'film-grain-xl.safetensors'
+const names = () => useCreateStore.getState().selectedLoras.map((l) => l.name)
+
+beforeEach(() => {
+ useCreateStore.setState({
+ mode: 'image', imageSubMode: 'text2img', videoSubMode: 't2v', removebg: false, utilityOp: null, cloudOp: null,
+ imageModel: 'Juggernaut-XL_v9.safetensors', imageModelType: 'sdxl', videoModel: 'wan2.2_t2v_14B.safetensors',
+ selectedLoras: [], loraStrengths: {}, loraLanes: {}, selectedCharacter: null,
+ } as never)
+})
+
+describe('D4: moving a pick', () => {
+ it('up and down swap it with its neighbour, the strength goes along', () => {
+ const picks = [{ name: A, strength: 0.8 }, { name: B, strength: 0.4 }, { name: C, strength: 1 }]
+ expect(moveLoraPick(picks, B, -1).map((p) => p.name)).toEqual([B, A, C])
+ expect(moveLoraPick(picks, B, 1)).toEqual([{ name: A, strength: 0.8 }, { name: C, strength: 1 }, { name: B, strength: 0.4 }])
+ })
+
+ it('the first one up, the last one down, or an unknown name change nothing', () => {
+ const picks = [{ name: A, strength: 0.8 }, { name: B, strength: 0.4 }]
+ expect(moveLoraPick(picks, A, -1)).toBe(picks)
+ expect(moveLoraPick(picks, B, 1)).toBe(picks)
+ expect(moveLoraPick(picks, C, 1)).toBe(picks)
+ })
+
+ it('the store moves the pick', () => {
+ const s = useCreateStore.getState()
+ s.toggleLora(A)
+ s.toggleLora(B)
+ s.toggleLora(C)
+ s.moveLora(C, -1)
+ expect(names()).toEqual([A, C, B])
+ s.moveLora(A, 1)
+ expect(names()).toEqual([C, A, B])
+ })
+})
+
+describe('D4: the order is kept with the picks', () => {
+ it('leaving the lane and coming back brings the order back (B24)', () => {
+ const s = useCreateStore.getState()
+ s.toggleLora(A)
+ s.toggleLora(B)
+ s.moveLora(B, -1)
+ s.setIntent('edit')
+ expect(names()).toEqual([])
+ s.setIntent('image')
+ expect(names()).toEqual([B, A])
+ })
+
+ it('the saved state carries the order (a restart keeps it)', () => {
+ const s = useCreateStore.getState()
+ s.toggleLora(A)
+ s.toggleLora(B)
+ s.moveLora(B, -1)
+ const saved = useCreateStore.persist.getOptions().partialize!(useCreateStore.getState()) as { selectedLoras: { name: string }[] }
+ expect(saved.selectedLoras.map((l) => l.name)).toEqual([B, A])
+ })
+})
+
+describe('D4: the run chains the LoRAs in the order of the stack', () => {
+ const NODES = {
+ CheckpointLoaderSimple: { input: { required: { ckpt_name: [['Juggernaut-XL_v9.safetensors']] } } },
+ LoraLoader: { input: { required: { lora_name: [[A, B, C]] } } },
+ KSampler: { input: { required: {} } },
+ EmptyLatentImage: { input: { required: {} } },
+ CLIPTextEncode: { input: { required: {} } },
+ VAEDecode: { input: { required: {} } },
+ SaveImage: { input: { required: {} } },
+ }
+
+ /** The LoRAs from the checkpoint to the sampler, in chain order. */
+ function chain(wf: ComfyApiGraph): string[] {
+ const [samplerId] = Object.entries(wf).find(([, n]) => n.class_type === 'KSampler')!
+ const out: string[] = []
+ let at = (wf[samplerId].inputs?.model as [string, number])[0]
+ while (wf[at]?.class_type === 'LoraLoader') {
+ out.unshift(String(wf[at].inputs!.lora_name))
+ at = (wf[at].inputs!.model as [string, number])[0]
+ }
+ return out
+ }
+
+ it('the moved pick runs first', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue(NODES as never)
+ const s = useCreateStore.getState()
+ s.toggleLora(A)
+ s.toggleLora(B)
+ s.toggleLora(C)
+ s.moveLora(C, -1)
+ s.moveLora(C, -1)
+ const picks = useCreateStore.getState().selectedLoras
+ const wf = await buildDynamicWorkflow({
+ model: 'Juggernaut-XL_v9.safetensors', prompt: 'a knight', negativePrompt: '',
+ sampler: 'euler', scheduler: 'normal', steps: 20, cfgScale: 7, width: 1024, height: 1024, seed: 42, batchSize: 1,
+ lora: picks.map((l) => l.name), loraStrength: picks.map((l) => l.strength),
+ })
+ expect(chain(wf)).toEqual([C, A, B])
+ })
+})
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index 7589fad9..cac607a0 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -66,7 +66,7 @@ import { createRunModel } from '../lib/render/create-studio'
import { DEFAULT_UPSCALE_FACTOR, normalizeUpscaleFactor, type UpscaleFactor } from '../lib/local-upscale'
import { characterLoraFile, isLocalCharacter, type CharacterRef } from '../lib/character-ref'
import { triggerWordNote, typedTriggerWord } from '../lib/train-trigger'
-import { loraLaneKey, sanitizeLoraLanes, switchLoraLane, type LoraPick } from '../lib/render/lora-lanes'
+import { loraLaneKey, moveLoraPick, sanitizeLoraLanes, switchLoraLane, type LoraPick } from '../lib/render/lora-lanes'
// ModelType includes: flux, flux2, zimage, sdxl, sd15, wan, hunyuan, unknown
export type ProgressPhase = 'idle' | 'queued' | 'loading-model' | 'loading-clip' | 'loading-vae' | 'sampling' | 'decoding' | 'complete'
@@ -661,6 +661,9 @@ export interface CreateState {
setExpertOpen: (open: boolean) => void
toggleLora: (name: string) => void
setLoraStrengthFor: (name: string, strength: number) => void
+ /** D4: moves a pick a place up (-1) or down (1) among `among` (the picks
+ * the stack shows); the run chains them in this order. */
+ moveLora: (name: string, delta: -1 | 1, among?: string[]) => void
clearLoras: () => void
/** Drops picks whose file ComfyUI no longer lists (GH #146), and the local
* character that rode on one of them. */
@@ -1387,6 +1390,7 @@ export const useCreateStore = create<CreateState>()(
loraStrengths: { ...s.loraStrengths, [name]: value },
}
}),
+ moveLora: (name, delta, among) => set((s) => ({ selectedLoras: moveLoraPick(s.selectedLoras, name, delta, among) })),
clearLoras: () => set((s) => ({
selectedLoras: [],
selectedCharacter: isLocalCharacter(s.selectedCharacter) ? null : s.selectedCharacter,