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(create): prompt assistant, keywords to a prompt for the picked model (B43)
purplee77244930d11
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsxindex a31c03b1..e1aaab9c 100644--- a/src/components/create/experimental/Composer.tsx+++ b/src/components/create/experimental/Composer.tsx@@ -32,6 +32,7 @@ import { MOTION_OWN_WORKFLOW_NOTE, useMotionOwnWorkflow } from './motionWorkflowimport { ImageCountChip } from './ImageCountChip'import { CharacterChip, CharacterNote, characterMakesStart } from './CharacterChip'import { PromptHistory } from './PromptHistory'+import { PromptAssistant } from './PromptAssistant'import { SpecialControls } from './SpecialIntentControls'import { CreditsMeter } from './CreditsMeter'import { Button } from '../ui/Button'@@ -504,6 +505,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {Negative</button>)}+ {needPrompt && <PromptAssistant onUse={setPrompt} />}{needPrompt && <PromptHistory onPick={setPrompt} />}<div className="flex-1" />{/* The backend axis moved to the global header switch (2.5.7) —diff --git a/src/components/create/experimental/PromptAssistant.tsx b/src/components/create/experimental/PromptAssistant.tsxnew file mode 100644index 00000000..236fbd5f--- /dev/null+++ b/src/components/create/experimental/PromptAssistant.tsx@@ -0,0 +1,157 @@+import { useRef, useState } from 'react'+import { usePopoverPlatz } from '../../../hooks/usePopoverPlatz'+import { motion, AnimatePresence } from 'framer-motion'+import { Sparkles, Wand2 } from 'lucide-react'+import { useCreateStore } from '../../../stores/createStore'+import { classifyModel } from '../../../api/comfyui'+import { improveKindForIntent } from '../../../lib/render/improve-prompt'+import { improvePrompt, useImproveAvailability } from '../../../lib/render/improve-prompt-run'+import {+ FAMILY_LABEL, TEMPLATES, buildFromTemplate, familyFor, refineTarget,+} from '../../../lib/render/prompt-assistant'+import { Button } from '../ui/Button'+import { cn } from '../ui/cn'+import { useClickAway } from '../ui/useClickAway'++/**+ * The prompt assistant (B43): a few keywords and a template for the model's+ * family make a draft at once, offline. "Refine" hands the draft to the chat+ * model through the same call as "Improve my prompt". Nothing replaces the+ * prompt until the user presses Use.+ */+export function PromptAssistant({ onUse }: { onUse: (prompt: string) => void }) {+ const intent = useCreateStore((s) => s.intent())+ const kind = improveKindForIntent(intent)+ const runModel = useCreateStore((s) =>+ kind === 'music' ? s.localOpModel : kind === 'video' ? s.videoModel : s.imageModel,+ )+ const listType = useCreateStore((s) =>+ (kind === 'video' ? s.videoModelList : s.imageModelList).find((m) => m.name === runModel)?.type,+ )+ const chat = useImproveAvailability()+ const [open, setOpen] = useState(false)+ const [keywords, setKeywords] = useState('')+ const [templateId, setTemplateId] = useState<string | null>(null)+ const [refined, setRefined] = useState<string | null>(null)+ const [refining, setRefining] = useState(false)+ const [note, setNote] = useState('')+ const abort = useRef<AbortController | null>(null)+ const ref = useRef<HTMLDivElement>(null)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6 })++ const close = () => {+ abort.current?.abort()+ setOpen(false)+ }+ useClickAway(ref, close, open)++ if (!kind) return null+ const family = familyFor(kind, listType ?? classifyModel(runModel), runModel)+ const templates = TEMPLATES[family]+ const template = templates.find((t) => t.id === templateId) ?? templates[0]+ const draft = buildFromTemplate(template, keywords)+ const result = refined ?? draft++ const refine = async () => {+ if (!draft) return+ const own = new AbortController()+ abort.current = own+ setRefining(true)+ setNote('')+ const out = await improvePrompt(draft, refineTarget(kind, family, runModel), own.signal)+ abort.current = null+ setRefining(false)+ if (out.status === 'improved') setRefined(out.prompt)+ else if (out.status === 'unchanged') setNote('The chat model kept the draft as it is.')+ else if (!own.signal.aborted) setNote('The chat model did not answer. The draft is still yours to use.')+ }++ return (+ <div ref={ref} className="relative">+ <Button+ variant="ghost"+ size="sm"+ icon={Sparkles}+ iconOnly+ title="Prompt assistant"+ onClick={() => (open ? close() : setOpen(true))}+ />+ <AnimatePresence>+ {open && (+ <motion.div+ ref={panelRef}+ style={panel.style}+ initial={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}+ transition={{ duration: 0.12 }}+ className={cn('lu-elevated absolute left-0 z-50 w-80 rounded-lg p-2.5 space-y-2 overflow-y-auto scrollbar-thin', panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5')}+ data-testid="prompt-assistant"+ data-family={family}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="t-label text-gray-400">Prompt assistant</span>+ <span className="t-micro text-gray-500" title={runModel || undefined}>{FAMILY_LABEL[family]}</span>+ </div>+ <textarea+ value={keywords}+ onChange={(e) => { setKeywords(e.target.value); setRefined(null); setNote('') }}+ placeholder="A few keywords, separated by commas: red fox, snowy forest, dusk"+ rows={2}+ className="w-full resize-none rounded-md bg-white/[0.04] border border-white/[0.08] px-2 py-1.5 t-control text-gray-200 placeholder:text-gray-600 focus:outline-none focus:border-white/20"+ data-testid="prompt-assistant-keywords"+ autoFocus+ />+ <div role="radiogroup" aria-label="Template" className="flex flex-wrap gap-1">+ {templates.map((t) => (+ <button+ key={t.id}+ type="button"+ role="radio"+ aria-checked={t.id === template.id}+ onClick={() => { setTemplateId(t.id); setRefined(null); setNote('') }}+ className={cn(+ 'rounded-md border px-2 py-0.5 t-control transition-colors',+ t.id === template.id ? 'border-white/20 bg-white/[0.07] text-gray-200' : 'border-white/[0.07] text-gray-500 hover:text-gray-300',+ )}+ >+ {t.label}+ </button>+ ))}+ </div>+ <p+ className={cn('rounded-md bg-black/20 px-2 py-1.5 t-control min-h-[3rem] whitespace-pre-wrap break-words', result ? 'text-gray-300' : 'text-gray-600')}+ data-testid="prompt-assistant-result"+ >+ {result || 'The prompt appears here as you type.'}+ </p>+ {note && <p className="t-micro text-gray-500">{note}</p>}+ <div className="flex items-center justify-end gap-1.5">+ <button+ type="button"+ disabled={!refining && (!draft || !chat.available)}+ onClick={() => (refining ? abort.current?.abort() : void refine())}+ title={refining ? 'Stop refining' : chat.hint}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 t-control text-gray-400 hover:text-gray-200 hover:bg-white/[0.05] disabled:opacity-50 disabled:cursor-not-allowed"+ data-testid="prompt-assistant-refine"+ >+ <Wand2 size={12} />+ {refining ? 'Refining… (stop)' : 'Refine with chat model'}+ </button>+ <button+ type="button"+ disabled={!result || refining}+ onClick={() => { onUse(result); close() }}+ className="rounded-md px-2.5 py-1 t-control bg-white/10 text-gray-100 hover:bg-white/15 disabled:opacity-50 disabled:cursor-not-allowed"+ data-testid="prompt-assistant-use"+ >+ Use+ </button>+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ )+}diff --git a/src/components/create/experimental/__tests__/prompt-assistant-b43.test.tsx b/src/components/create/experimental/__tests__/prompt-assistant-b43.test.tsxnew file mode 100644index 00000000..35b991f3--- /dev/null+++ b/src/components/create/experimental/__tests__/prompt-assistant-b43.test.tsx@@ -0,0 +1,130 @@+// @vitest-environment jsdom+/**+ * B43 (3.0.9): a prompt assistant in Create. A few keywords and a template of+ * the picked model's family give a prompt at once, offline; Refine hands that+ * draft to the existing "Improve my prompt" call, aimed at the same family;+ * the prompt only changes when the user presses Use.+ *+ * Run: npx vitest run src/components/create/experimental/__tests__/prompt-assistant-b43.test.tsx+ */+import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'++const improve = vi.hoisted(() => ({ calls: [] as Array<{ prompt: string; target: unknown }>, answer: { status: 'improved', prompt: 'REFINED' } as unknown }))+vi.mock('../../../../lib/render/improve-prompt-run', () => ({+ improvePrompt: async (prompt: string, target: unknown) => {+ improve.calls.push({ prompt, target })+ return improve.answer+ },+ useImproveAvailability: () => ({ available: true, hint: 'Your chat model rewrites your prompt.' }),+}))++import {+ TEMPLATES, buildFromTemplate, familyFor, refineTarget, splitKeywords, type PromptFamily,+} from '../../../../lib/render/prompt-assistant'+import { PromptAssistant } from '../PromptAssistant'+import { useCreateStore } from '../../../../stores/createStore'++describe('B43: the family a prompt is written for', () => {+ it('SD checkpoints read tags, Pony gets its score tags, newer models read prose', () => {+ expect(familyFor('image', 'sd15')).toBe('tags-sd15')+ expect(familyFor('image', 'sdxl', 'juggernautXL_v9.safetensors')).toBe('tags-sdxl')+ expect(familyFor('image', 'sdxl', 'ponyDiffusionV6XL.safetensors')).toBe('tags-pony')+ for (const t of ['flux', 'flux2', 'qwenimage', 'zimage', 'hidream', 'sd3', 'chroma', 'unknown']) {+ expect(familyFor('image', t)).toBe('prose')+ }+ expect(familyFor('video', 'wan')).toBe('video')+ expect(familyFor('music', 'ace')).toBe('music')+ })++ it('every family has a library of at least three templates, each with a slot for the keywords', () => {+ for (const fam of Object.keys(TEMPLATES) as PromptFamily[]) {+ expect(TEMPLATES[fam].length).toBeGreaterThanOrEqual(3)+ for (const t of TEMPLATES[fam]) expect(t.pattern).toContain('{k}')+ }+ })+})++describe('B43: the draft, offline', () => {+ it('keeps every keyword, in order, once', () => {+ expect(splitKeywords(' red fox, snowy forest\n dusk , Red Fox ;')).toEqual(['red fox', 'snowy forest', 'dusk'])+ const out = buildFromTemplate(TEMPLATES.prose[0], 'red fox, snowy forest, dusk')+ expect(out).toMatch(/^A photograph of red fox, snowy forest, dusk\./)+ })++ it('Pony puts the score tags first, then the keywords', () => {+ const out = buildFromTemplate(TEMPLATES['tags-pony'][0], 'knight, castle')+ expect(out.startsWith('score_9, score_8_up, score_7_up')).toBe(true)+ expect(out).toContain('knight, castle')+ })++ it('no keywords, no prompt: a template alone is not a prompt', () => {+ expect(buildFromTemplate(TEMPLATES.video[0], ' , ')).toBe('')+ })++ it('Refine is the Improve call with tags for the tag families', () => {+ expect(refineTarget('image', 'tags-sdxl', 'x.safetensors')).toEqual({ kind: 'image', modelLabel: 'x.safetensors', tags: true })+ expect(refineTarget('image', 'prose', '')).toEqual({ kind: 'image', modelLabel: undefined, tags: false })+ })+})++describe('B43: the assistant in the composer', () => {+ beforeEach(() => {+ improve.calls = []+ improve.answer = { status: 'improved', prompt: 'REFINED' }+ useCreateStore.setState({+ imageModel: 'ponyDiffusionV6XL.safetensors',+ imageModelList: [{ name: 'ponyDiffusionV6XL.safetensors', type: 'sdxl' }] as never,+ })+ })+ afterEach(cleanup)++ function openAssistant(onUse = vi.fn()) {+ render(<PromptAssistant onUse={onUse} />)+ fireEvent.click(screen.getByTitle('Prompt assistant'))+ return onUse+ }++ it('the picked model decides the library, and Use hands the draft over', () => {+ const onUse = openAssistant()+ expect(screen.getByTestId('prompt-assistant').dataset.family).toBe('tags-pony')+ fireEvent.change(screen.getByTestId('prompt-assistant-keywords'), { target: { value: 'knight, castle' } })+ fireEvent.click(screen.getByRole('radio', { name: 'Realistic' }))+ const draft = screen.getByTestId('prompt-assistant-result').textContent+ expect(draft).toBe(buildFromTemplate(TEMPLATES['tags-pony'][1], 'knight, castle'))+ expect(onUse).not.toHaveBeenCalled()+ fireEvent.click(screen.getByTestId('prompt-assistant-use'))+ expect(onUse).toHaveBeenCalledWith(draft)+ })++ it('Refine sends the draft through Improve, and Use takes the refined text', async () => {+ const onUse = openAssistant()+ fireEvent.change(screen.getByTestId('prompt-assistant-keywords'), { target: { value: 'knight' } })+ fireEvent.click(screen.getByTestId('prompt-assistant-refine'))+ await waitFor(() => expect(screen.getByTestId('prompt-assistant-result').textContent).toBe('REFINED'))+ expect(improve.calls).toHaveLength(1)+ expect(improve.calls[0].prompt).toContain('knight')+ expect(improve.calls[0].target).toEqual({ kind: 'image', modelLabel: 'ponyDiffusionV6XL.safetensors', tags: true })+ fireEvent.click(screen.getByTestId('prompt-assistant-use'))+ expect(onUse).toHaveBeenCalledWith('REFINED')+ })++ it('a failed refine keeps the draft and says so', async () => {+ improve.answer = { status: 'failed' }+ openAssistant()+ fireEvent.change(screen.getByTestId('prompt-assistant-keywords'), { target: { value: 'knight' } })+ const draft = screen.getByTestId('prompt-assistant-result').textContent+ fireEvent.click(screen.getByTestId('prompt-assistant-refine'))+ await screen.findByText(/did not answer/)+ expect(screen.getByTestId('prompt-assistant-result').textContent).toBe(draft)+ })+})++describe('B43: where it sits', () => {+ it('next to the prompt history in the composer, writing into the prompt', async () => {+ const { readFileSync } = await import('node:fs')+ const { resolve } = await import('node:path')+ const src = readFileSync(resolve(__dirname, '../Composer.tsx'), 'utf8')+ expect(src).toMatch(/\{needPrompt && <PromptAssistant onUse=\{setPrompt\} \/>\}\n\s*\{needPrompt && <PromptHistory/)+ })+})diff --git a/src/lib/render/prompt-assistant.ts b/src/lib/render/prompt-assistant.tsnew file mode 100644index 00000000..75974d50--- /dev/null+++ b/src/lib/render/prompt-assistant.ts@@ -0,0 +1,124 @@+// The prompt assistant in Create (B43, 3.0.9): a few keywords in, a prompt+// written the way the picked model reads best out. The pure half: which model+// family the run is for, the built-in templates of each family, and the draft+// a template makes from the keywords without any model. Refining the draft+// with the chat model is the existing "Improve my prompt" call+// (improve-prompt-run.ts), with the same rules: it keeps every subject, never+// censors and adds nothing the user did not ask for.++import type { ImproveKind, ImproveTarget } from './improve-prompt'++/**+ * How a model wants its prompt.+ *+ * - `tags-sd15`, `tags-sdxl`: Stable Diffusion checkpoints, trained on comma+ * separated tags (the same split "Improve my prompt" makes with `tags`).+ * - `tags-pony`: Pony Diffusion and its merges, SDXL underneath but trained+ * with the score and source tags in front.+ * - `prose`: every newer image model (Flux, Qwen-Image, Z-Image, HiDream,+ * SD3, Chroma, Lumina, …) reads natural sentences.+ * - `video`, `music`: one family each, the brief differs per kind, not per model.+ */+export type PromptFamily = 'tags-sd15' | 'tags-sdxl' | 'tags-pony' | 'prose' | 'video' | 'music'++export const FAMILY_LABEL: Record<PromptFamily, string> = {+ 'tags-sd15': 'Stable Diffusion 1.5 (tags)',+ 'tags-sdxl': 'SDXL (tags)',+ 'tags-pony': 'Pony (score tags)',+ prose: 'Natural language',+ video: 'Video',+ music: 'Music',+}++/** The family of the model a run is for. `modelType` is what the model list+ * or `classifyModel` says, `modelName` catches Pony, which classifies as SDXL. */+export function familyFor(kind: ImproveKind, modelType: string, modelName = ''): PromptFamily {+ if (kind === 'music') return 'music'+ if (kind === 'video') return 'video'+ if (modelType === 'sd15') return 'tags-sd15'+ if (modelType === 'sdxl') return /pony/i.test(modelName) ? 'tags-pony' : 'tags-sdxl'+ return 'prose'+}++export function isTagFamily(family: PromptFamily): boolean {+ return family === 'tags-sd15' || family === 'tags-sdxl' || family === 'tags-pony'+}++export interface PromptTemplate {+ id: string+ label: string+ /** `{k}` is where the keywords go. For tag families the text is a tag list. */+ pattern: string+}++/** The keywords as the user typed them: split on commas and new lines,+ * trimmed, empty pieces dropped, duplicates kept once. */+export function splitKeywords(input: string): string[] {+ const seen = new Set<string>()+ const out: string[] = []+ for (const raw of input.split(/[,\n;]+/)) {+ const k = raw.trim().replace(/\s+/g, ' ')+ if (!k || seen.has(k.toLowerCase())) continue+ seen.add(k.toLowerCase())+ out.push(k)+ }+ return out+}++const PONY = 'score_9, score_8_up, score_7_up'++/** The built-in library, per family. Every template keeps the user's words+ * first and only adds the craft a good prompt for that family has. */+export const TEMPLATES: Record<PromptFamily, PromptTemplate[]> = {+ 'tags-sd15': [+ { id: 'photo', label: 'Photo', pattern: 'masterpiece, best quality, {k}, photorealistic, natural lighting, sharp focus, detailed skin texture, 85mm, bokeh' },+ { id: 'anime', label: 'Anime', pattern: 'masterpiece, best quality, {k}, anime style, clean lineart, vibrant colors, detailed eyes, soft shading' },+ { id: 'fantasy', label: 'Fantasy art', pattern: 'masterpiece, best quality, {k}, fantasy art, epic composition, dramatic lighting, intricate details, concept art' },+ { id: 'portrait', label: 'Portrait', pattern: 'masterpiece, best quality, {k}, portrait, looking at viewer, upper body, studio lighting, detailed face' },+ ],+ 'tags-sdxl': [+ { id: 'photo', label: 'Photo', pattern: '{k}, photograph, realistic, natural light, shallow depth of field, 50mm lens, high detail, film grain' },+ { id: 'cinematic', label: 'Cinematic', pattern: '{k}, cinematic still, dramatic lighting, anamorphic, color graded, atmospheric, wide shot' },+ { id: 'anime', label: 'Anime', pattern: '{k}, anime illustration, clean lineart, cel shading, vibrant colors, detailed background' },+ { id: 'portrait', label: 'Portrait', pattern: '{k}, portrait, close-up, soft key light, rim light, detailed eyes, sharp focus' },+ ],+ 'tags-pony': [+ { id: 'anime', label: 'Anime', pattern: `${PONY}, source_anime, {k}, detailed, vibrant colors` },+ { id: 'realistic', label: 'Realistic', pattern: `${PONY}, source_photo, photorealistic, {k}, natural lighting, detailed skin` },+ { id: 'cartoon', label: 'Cartoon', pattern: `${PONY}, source_cartoon, {k}, bold outlines, flat colors` },+ { id: 'furry', label: 'Furry', pattern: `${PONY}, source_furry, {k}, detailed fur, expressive` },+ ],+ prose: [+ { id: 'photo', label: 'Photo', pattern: 'A photograph of {k}. Natural light, shallow depth of field, shot on a 50mm lens, sharp focus and realistic textures.' },+ { id: 'cinematic', label: 'Cinematic', pattern: 'A cinematic film still of {k}. Dramatic lighting, anamorphic framing, rich color grading and atmospheric depth.' },+ { id: 'illustration', label: 'Illustration', pattern: 'A detailed digital illustration of {k}. Clean line work, vibrant colors and painterly shading.' },+ { id: 'portrait', label: 'Portrait', pattern: 'A close portrait of {k}. Soft key light from the side, a gentle rim light, detailed eyes, a calm neutral background.' },+ { id: 'product', label: 'Product', pattern: 'A studio product photo of {k} on a seamless background. Softbox lighting, crisp reflections, high detail.' },+ ],+ video: [+ { id: 'push-in', label: 'Slow push-in', pattern: '{k}. The camera slowly pushes in from a wide shot to a medium shot. Soft natural light, gentle motion, realistic detail.' },+ { id: 'action', label: 'Action', pattern: '{k}. Fast, energetic motion, the handheld camera follows the subject closely. Dynamic lighting, motion blur.' },+ { id: 'orbit', label: 'Orbit', pattern: '{k}. The camera orbits slowly around the subject at eye level. Smooth, steady movement, cinematic lighting.' },+ { id: 'b-roll', label: 'Nature b-roll', pattern: '{k}. A calm, steady wide shot, subtle movement in the scene, golden hour light, ambient sound of the place.' },+ ],+ music: [+ { id: 'song', label: 'Song', pattern: '{k}. Verse and chorus structure, a clear lead vocal, full band arrangement, builds into a big final chorus.' },+ { id: 'instrumental', label: 'Instrumental', pattern: '{k}. Instrumental, no vocals, a memorable main melody, steady groove, builds layer by layer.' },+ { id: 'ambient', label: 'Ambient', pattern: '{k}. Slow ambient soundscape, soft pads, wide reverb, gentle evolving textures, no drums.' },+ { id: 'beat', label: 'Beat', pattern: '{k}. Punchy drums, deep bass, catchy loop, around 90 BPM, modern mix.' },+ ],+}++/** The draft a template makes from the keywords, no model involved. Empty+ * keywords give an empty draft: a template alone is not a prompt. */+export function buildFromTemplate(template: PromptTemplate, keywords: string): string {+ const parts = splitKeywords(keywords)+ if (parts.length === 0) return ''+ return template.pattern.replace('{k}', parts.join(', '))+}++/** What "Refine" asks the chat model for: the existing Improve call, aimed at+ * this family and this model. */+export function refineTarget(kind: ImproveKind, family: PromptFamily, modelLabel?: string): ImproveTarget {+ return { kind, modelLabel: modelLabel || undefined, tags: isTagFamily(family) }+}