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(chat): chat look, reading zoom and editable memory quick menu (C58, C42, C38)
purple0ad238031947
diff --git a/e2e/chat-look.spec.ts b/e2e/chat-look.spec.tsnew file mode 100644index 00000000..8a629a8b--- /dev/null+++ b/e2e/chat-look.spec.ts@@ -0,0 +1,168 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'+import { gradientPng } from './support/png'++/**+ * 3.1.0 P-M: the chat look (C58), the reading zoom (C42) and the Memory quick+ * menu (C38), in the real app with the Tauri bridge mocked.+ *+ * - Ctrl + wheel over the transcript zooms the messages, the prompt box keeps+ * its size, and the zoom survives a reload. Ctrl + 0 resets it.+ * - A right click in a zoomed transcript opens the menu AT the pointer.+ * - A preset colours quoted speech; custom CSS with url() loads nothing.+ * - A background picture from a file shows under a scrim and survives a reload.+ * - A long memory opens in full and can be edited in place.+ *+ * Run: LU_E2E_PORT=5391 CI=1 npx playwright test e2e/chat-look.spec.ts --project=chromium+ */++const CONV = 'look-chat'+const REPLY = '*She smiles.* "Welcome back," she says. The harbour is quiet tonight.'++function seed(): string {+ const now = Date.now()+ return JSON.stringify({+ state: {+ conversations: [{+ id: CONV, title: 'Harbour', model: DEFAULT_MODEL_NAME, systemPrompt: '', mode: 'lu',+ createdAt: now - 20_000, updatedAt: now - 10_000, personaEnabled: false,+ messages: [+ { id: 'u1', role: 'user', content: '*I wave.* "Hello!"', timestamp: now - 10_000 },+ { id: 'a1', role: 'assistant', content: REPLY, timestamp: now - 9_000, modelId: 'qwen2.5-7b-instruct-q4_k_m' },+ ],+ }],+ activeConversationId: CONV,+ },+ version: 0,+ })+}++const LONG = 'The user writes slow fantasy roleplay in the port city of Kessel. Their character is Arin, a courier who owes the harbour guild money. Avoid modern slang.'++async function boot(page: Page) {+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, attachmentStore: true })+ await seedOnboardingDone(page)+ await page.addInitScript(({ raw, mem }) => {+ if (sessionStorage.getItem('e2e-seeded')) return+ sessionStorage.setItem('e2e-seeded', '1')+ localStorage.setItem('chat-conversations', raw)+ const now = Date.now()+ localStorage.setItem('locally-uncensored-memory', JSON.stringify({ state: { entries: [+ { id: 'mem1', type: 'user', title: 'Roleplay setting', description: mem.slice(0, 120), content: mem, tags: [], createdAt: now, updatedAt: now, source: 'manual' },+ ] }, version: 0 }))+ }, { raw: seed(), mem: LONG })+ await page.goto('/')+ await expect(reply(page)).toBeVisible({ timeout: 30_000 })+}++function reply(page: Page) {+ return page.getByText('The harbour is quiet tonight.', { exact: false }).first()+}++async function zoomOf(page: Page): Promise<number> {+ return page.getByTestId('chat-look-chat').evaluate((el) => Number(getComputedStyle(el).getPropertyValue('--lu-chat-zoom')))+}++test('Ctrl + wheel zooms the messages only, and the zoom stays', async ({ page }) => {+ await boot(page)+ const composer = page.getByPlaceholder('Message...')+ const composerBefore = (await composer.boundingBox())!.height+ const textBefore = (await reply(page).boundingBox())!.height++ await reply(page).hover()+ await page.keyboard.down('Control')+ await page.mouse.wheel(0, -100)+ await page.mouse.wheel(0, -100)+ await page.mouse.wheel(0, -100)+ await page.keyboard.up('Control')++ await expect.poll(() => zoomOf(page)).toBeCloseTo(1.3, 2)+ await expect(page.getByTestId('chat-zoom-badge')).toContainText('130%')+ expect((await reply(page).boundingBox())!.height).toBeGreaterThan(textBefore * 1.2)+ expect((await composer.boundingBox())!.height).toBeCloseTo(composerBefore, 0)++ await page.reload()+ await expect(reply(page)).toBeVisible({ timeout: 30_000 })+ expect(await zoomOf(page)).toBeCloseTo(1.3, 2)++ await page.keyboard.press('Control+0')+ await expect.poll(() => zoomOf(page)).toBe(1)+})++test('a right click in a zoomed transcript opens the menu at the pointer', async ({ page }) => {+ await boot(page)+ await page.evaluate(() => localStorage.setItem('lu-chat-look', JSON.stringify({ state: { look: {}, zoom: 1.5, backgrounds: {} }, version: 0 })))+ await page.reload()+ await expect(reply(page)).toBeVisible({ timeout: 30_000 })+ const box = (await reply(page).boundingBox())!+ const x = box.x + 40+ const y = box.y + box.height / 2+ await page.mouse.click(x, y, { button: 'right' })+ const menu = page.getByRole('menu')+ await expect(menu).toBeVisible()+ const m = (await menu.boundingBox())!+ expect(Math.abs(m.x - x)).toBeLessThan(24)+ expect(Math.abs(m.y - y)).toBeLessThan(24)+})++test('the Roleplay preset colours quotes; custom CSS with url() loads nothing', async ({ page }) => {+ const asked: string[] = []+ page.on('request', (r) => { if (r.url().includes('evil.example')) asked.push(r.url()) })+ await boot(page)+ await page.getByTestId('chat-look-button').click()+ const panel = page.getByTestId('chat-look-panel')+ await panel.getByRole('button', { name: 'Roleplay' }).click()+ const quote = page.locator('.lu-msg-model-text .lu-quote').first()+ await expect(quote).toHaveText('"Welcome back,"')+ const colours = await quote.evaluate((el) => [getComputedStyle(el).color, getComputedStyle(el.parentElement!).color])+ expect(colours[0]).not.toBe(colours[1])+ await expect(page.locator('.lu-msg-user-text .lu-action')).toHaveText('*I wave.*')++ await panel.getByRole('button', { name: /Custom CSS/ }).click()+ await panel.getByLabel('Use custom CSS').click()+ await panel.getByRole('textbox', { name: 'Custom CSS' }).fill('.lu-quote { font-weight: 700; background: url(https://evil.example/t.png) }\n@import url(https://evil.example/x.css);\nbody { display: none }')+ await expect(panel.getByTestId('chat-css-dropped')).toBeVisible()+ await expect(quote).toHaveCSS('font-weight', '700')+ await expect(page.locator('body')).toBeVisible()+ const css = await page.getByTestId('chat-custom-css').textContent()+ expect(css).not.toMatch(/url|@import|evil/)+ await page.waitForTimeout(500)+ expect(asked).toEqual([])+})++test('a background from a file shows under a scrim and stays after a reload', async ({ page }) => {+ await boot(page)+ await page.getByTestId('chat-look-button').click()+ const panel = page.getByTestId('chat-look-panel')+ await panel.locator('input[type="file"]').setInputFiles({ name: 'harbour.png', mimeType: 'image/png', buffer: gradientPng(640, 360) })+ const bg = page.getByTestId('chat-background')+ await expect(bg.locator('img')).toHaveAttribute('src', /^data:image\/jpeg/)+ await expect(panel.getByLabel('Background dimming')).toBeVisible()+ const shots = process.env.LU_SHOTS_DIR+ if (shots) {+ await page.keyboard.press('Escape')+ await expect(panel).toBeHidden()+ await page.screenshot({ path: `${shots}/nachher-hintergrund-${await page.evaluate(() => document.documentElement.classList.contains('dark') ? 'dark' : 'light')}-1280.png` })+ }+ await page.reload()+ await expect(reply(page)).toBeVisible({ timeout: 30_000 })+ await expect(page.getByTestId('chat-background').locator('img')).toHaveAttribute('src', /^data:image\/jpeg/)+})++test('the Memory quick menu opens a long memory in full and edits it', async ({ page }) => {+ await boot(page)+ await page.getByTitle('Memory: view, add or delete the context injected into prompts').click()+ await page.getByRole('button', { name: /Roleplay setting/, expanded: false }).click()+ await expect(page.getByTestId('memory-full')).toHaveText(LONG)+ await page.getByLabel('Edit Roleplay setting').click()+ await page.getByRole('textbox', { name: 'Memory', exact: true }).fill(LONG + ' Arin carries a brass key.')+ await page.getByTestId('memory-save').click()+ await expect(page.getByTestId('memory-full')).toContainText('Arin carries a brass key.')+ await page.reload()+ await expect(reply(page)).toBeVisible({ timeout: 30_000 })+ // Read back through the app, wherever the store keeps it.+ await page.getByTitle('Memory: view, add or delete the context injected into prompts').click()+ await page.getByRole('button', { name: /Roleplay setting/, expanded: false }).click()+ await expect(page.getByTestId('memory-full')).toContainText('Arin carries a brass key.')+})diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.tsindex 29e48973..c3c17e0d 100644--- a/e2e/support/tauri-mock.ts+++ b/e2e/support/tauri-mock.ts@@ -17,6 +17,9 @@*/export interface TauriMockOptions {+ /** Keep chat attachments (write/read_chat_attachment) for real, in+ * sessionStorage. Off by default: other specs keep the old no-op. */+ attachmentStore?: boolean/** Assistant text the mocked built-in engine "generates" for the first chat. */assistantReply: string/** Picker id of the bundled starter model the engine reports as loaded. */@@ -2052,6 +2055,20 @@ export function tauriMockInit(opts: TauriMockOptions) {case 'repo_map':return Promise.resolve({ files: [], count: 0 })+ // The attachment store (lib/chat-attachments.ts): in memory, kept in+ // sessionStorage so a reload in the same test still finds the file,+ // as the native folder would.+ case 'write_chat_attachment': {+ if (!opts.attachmentStore) return Promise.resolve(null)+ sessionStorage.setItem(`e2e-attachment:${m.id}`, String(m.data))+ return Promise.resolve(null)+ }+ case 'read_chat_attachment': {+ if (!opts.attachmentStore) return Promise.resolve(null)+ const data = sessionStorage.getItem(`e2e-attachment:${m.id}`)+ return data === null ? Promise.reject('Chat attachment is missing. Please attach the original image again.') : Promise.resolve(data)+ }+default:// Tauri v2 unlisten calls the injected event registry before IPC.// Use the already unique callback ID as this fixture's listener ID.diff --git a/src/components/__tests__/ein-massstab.test.ts b/src/components/__tests__/ein-massstab.test.tsindex 6657d369..eae50353 100644--- a/src/components/__tests__/ein-massstab.test.ts+++ b/src/components/__tests__/ein-massstab.test.ts@@ -100,7 +100,14 @@ describe('die 15 % sind ein Token und werden genau einmal angewandt', () => {})it('es gibt genau EINE zoom-Deklaration, und sie liest das Token', () => {- const withZoom = RULES.filter(([, body]) => /(^|[;\s])zoom\s*:/.test(body))+ // Ausnahme mit Namen (3.1.0, C42): der Lese-Zoom des Transkripts. Er ist+ // kein Layout-Massstab, sondern die Textgroesse, die der Nutzer selbst+ // mit Strg/Cmd + Mausrad waehlt, wie der Zoom eines Browsers, und er+ // steht auf 1, bis der Nutzer ihn aendert. Genau diese eine Regel, genau+ // dieses Token, sonst keine.+ const reading = RULES.filter(([sel, body]) => sel === '.lu-chat-zoom' && /zoom\s*:\s*var\(--lu-chat-zoom,\s*1\)/.test(body))+ expect(reading).toHaveLength(1)+ const withZoom = RULES.filter(([sel, body]) => sel !== '.lu-chat-zoom' && /(^|[;\s])zoom\s*:/.test(body))expect(withZoom).toHaveLength(1)const [selector, body] = withZoom[0]expect(/zoom\s*:\s*var\(--ui-scale\)/.test(body)).toBe(true)diff --git a/src/components/chat/ChatLookPanel.tsx b/src/components/chat/ChatLookPanel.tsxnew file mode 100644index 00000000..2edf71c1--- /dev/null+++ b/src/components/chat/ChatLookPanel.tsx@@ -0,0 +1,470 @@+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'+import { createPortal } from 'react-dom'+import { AnimatePresence, motion } from 'framer-motion'+import { Palette, X, RotateCcw, Upload, Images, Sparkles, Trash2, Square, Copy, ClipboardPaste, ChevronDown, ChevronRight, Minus, Plus } from 'lucide-react'+import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'+import { useChatLookStore } from '../../stores/chatLookStore'+import { useChatStore } from '../../stores/chatStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useCreateStore } from '../../stores/createStore'+import { useUIStore } from '../../stores/uiStore'+import {+ DEFAULT_LOOK, LOOK_PRESETS, PANE, SCRIM_DEFAULT, SCRIM_MIN, ZOOM_MAX, ZOOM_MIN, ZOOM_STEP,+ bgKeyForChat, bgKeyForPersona, normalizeLook, readableOn, scenePrompt,+ type ChatFont, type ChatLayout, type ChatLook, type ChatWidth,+} from '../../lib/chat-look'+import { sanitizeChatCss } from '../../lib/chat-css-sanitize'+import { cancelSceneBackground, renderSceneBackground, storeBackground } from '../../lib/chat-background'+import { HEADER_CHIP } from './header-chip'+import { ToggleSwitch } from '../ui/ToggleSwitch'++/**+ * The "Look" button in the chat's session strip and its panel (3.1.0, C58).+ * Every change shows at once in the transcript behind the panel, which is+ * why the panel stands at the right edge and leaves the chat readable. The+ * background part needs an open chat; everything else applies to all chats.+ */+export function ChatLookButton() {+ const [open, setOpen] = useState(false)+ return (+ <>+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ title="Chat look: colours, font, width, background, text size"+ aria-label="Chat look"+ aria-expanded={open}+ data-testid="chat-look-button"+ className={`${HEADER_CHIP} ${open ? 'border-purple-400/50 text-purple-600 dark:text-purple-300' : 'border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500'}`}+ >+ <Palette size={10} />+ </button>+ <AnimatePresence>{open && <ChatLookPanel onClose={() => setOpen(false)} />}</AnimatePresence>+ </>+ )+}++const LABEL = 't-micro font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400'+const ROW = 'flex items-center justify-between gap-2 min-h-[26px]'+const TEXT = 't-micro text-gray-700 dark:text-gray-200'+const QUIET = 't-micro text-gray-500 dark:text-gray-400'+const BTN = 'inline-flex items-center gap-1 rounded-md border border-gray-200 dark:border-white/10 px-2 py-1 t-micro text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.06] disabled:opacity-40 transition-colors'++function Section({ title, children }: { title: string; children: ReactNode }) {+ return (+ <section className="space-y-1.5 px-3 py-2.5 border-b border-gray-100 dark:border-white/[0.06]">+ <h3 className={LABEL}>{title}</h3>+ {children}+ </section>+ )+}++function Segmented<T extends string>({ value, options, onChange, label }: {+ value: T; options: { id: T; label: string }[]; onChange: (v: T) => void; label: string+}) {+ return (+ <div role="radiogroup" aria-label={label} className="inline-flex rounded-md border border-gray-200 dark:border-white/10 p-0.5">+ {options.map((o) => (+ <button+ key={o.id}+ type="button"+ role="radio"+ aria-checked={value === o.id}+ onClick={() => onChange(o.id)}+ className={'px-2 py-0.5 rounded t-micro transition-colors ' + (value === o.id+ ? 'bg-purple-500/15 text-purple-800 dark:text-purple-200 font-semibold'+ : 'text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.06]')}+ >+ {o.label}+ </button>+ ))}+ </div>+ )+}++/** One colour: a swatch that opens the system picker, and a clear button.+ * When the guard had to move the colour for the current mode, it says so. */+function ColorRow({ label, value, onChange, mode, surface, isSurface = false }: {+ label: string; value: string | null; onChange: (v: string | null) => void; mode: 'light' | 'dark'; surface?: string+ /** A bubble is a surface, laid over the pane as a soft tint; it is not+ * read as text, so the readability note does not apply to it. */+ isSurface?: boolean+}) {+ const shown = value && !isSurface ? readableOn(value, surface ?? PANE[mode]) : null+ const moved = !!value && !!shown && shown.toLowerCase() !== value.toLowerCase()+ return (+ <div className={ROW}>+ <span className={TEXT}>{label}</span>+ <span className="flex items-center gap-1.5">+ {moved && <span className={QUIET} title={`Shown as ${shown} so it stays readable in ${mode} mode`}>adjusted</span>}+ <label className="relative h-5 w-8 cursor-pointer rounded border border-gray-300 dark:border-white/15 overflow-hidden"+ style={{ background: value ?? 'repeating-linear-gradient(45deg, transparent 0 3px, rgba(127,127,127,.25) 3px 6px)' }}+ title={value ? `${label}: ${value}` : `${label}: app default`}>+ <input+ type="color"+ aria-label={label}+ value={value ?? '#888888'}+ onChange={(e) => onChange(e.target.value)}+ className="absolute inset-0 opacity-0 cursor-pointer"+ />+ </label>+ <button type="button" onClick={() => onChange(null)} disabled={!value} className="p-0.5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 disabled:opacity-30" aria-label={`Reset ${label}`} title="Back to the app's colour">+ <X size={11} />+ </button>+ </span>+ </div>+ )+}++function ChatLookPanel({ onClose }: { onClose: () => void }) {+ useDismissOnEscape(true, onClose)+ const look = useChatLookStore((s) => s.look)+ const setLook = useChatLookStore((s) => s.setLook)+ const replaceLook = useChatLookStore((s) => s.replaceLook)+ const resetLook = useChatLookStore((s) => s.resetLook)+ const zoom = useChatLookStore((s) => s.zoom)+ const setZoom = useChatLookStore((s) => s.setZoom)+ const theme = useSettingsStore((s) => s.settings.theme)+ const mode = theme === 'light' ? 'light' : 'dark'+ const [cssOpen, setCssOpen] = useState(look.customCssOn || !!look.customCss)+ const [note, setNote] = useState<string | null>(null)++ const set = <K extends keyof ChatLook>(k: K) => (v: ChatLook[K]) => setLook({ [k]: v } as Partial<ChatLook>)+ const dropped = useMemo(() => (look.customCss ? sanitizeChatCss(look.customCss).dropped : []), [look.customCss])++ const copyLook = async () => {+ const { customCssOn: _on, ...rest } = look+ void _on+ try {+ await navigator.clipboard.writeText(JSON.stringify({ luChatLook: 1, look: rest }, null, 2))+ setNote('Look copied. Paste it on another computer with "Paste look".')+ } catch { setNote('Could not copy to the clipboard.') }+ }+ const pasteLook = async () => {+ try {+ const text = await navigator.clipboard.readText()+ const parsed: unknown = JSON.parse(text)+ const raw = parsed && typeof parsed === 'object' && 'look' in parsed ? (parsed as { look: unknown }).look : parsed+ // Custom CSS from someone else stays off until switched on here.+ replaceLook({ ...normalizeLook(raw), customCssOn: false })+ setNote('Look pasted. Custom CSS from it is off until you switch it on.')+ } catch { setNote('The clipboard holds no chat look.') }+ }++ return createPortal(+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ className="fixed inset-0 z-50"+ onClick={onClose}+ >+ <motion.div+ initial={{ x: 16, opacity: 0 }}+ animate={{ x: 0, opacity: 1 }}+ exit={{ x: 16, opacity: 0 }}+ role="dialog"+ aria-label="Chat look"+ data-testid="chat-look-panel"+ className="absolute right-2 top-12 bottom-2 w-[min(340px,calc((100vw-16px)/var(--ui-scale)))] lu-dialog rounded-xl overflow-hidden flex flex-col"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between px-3 py-2 border-b border-gray-100 dark:border-white/[0.06] shrink-0">+ <span className="flex items-center gap-1.5 t-small font-semibold text-gray-800 dark:text-gray-100"><Palette size={13} className="text-purple-500" /> Chat look</span>+ <span className="flex items-center gap-1">+ <button type="button" onClick={() => { resetLook(); setNote('Back to the LU default look.') }} className={BTN} title="Back to the LU default look"><RotateCcw size={10} /> Reset</button>+ <button type="button" onClick={onClose} className="p-1 rounded text-gray-500 hover:bg-gray-100 dark:hover:bg-white/10" aria-label="Close"><X size={13} /></button>+ </span>+ </div>++ <div className="flex-1 overflow-y-auto scrollbar-thin">+ <Section title="Presets">+ <div className="flex flex-wrap gap-1">+ {LOOK_PRESETS.map((p) => (+ <button key={p.id} type="button" className={BTN} onClick={() => replaceLook({ ...DEFAULT_LOOK, customCss: look.customCss, customCssOn: look.customCssOn, ...p.look })}>+ {p.label}+ </button>+ ))}+ </div>+ </Section>++ <Section title="Text size">+ <div className={ROW}>+ <span className={QUIET}>Ctrl/Cmd + mouse wheel, or Ctrl/Cmd + and -</span>+ <span className="flex items-center gap-1">+ <button type="button" className={BTN} aria-label="Smaller text" disabled={zoom <= ZOOM_MIN} onClick={() => setZoom(zoom - ZOOM_STEP)}><Minus size={10} /></button>+ <button type="button" className={`${BTN} min-w-[52px] justify-center`} title="Reset to 100%" onClick={() => setZoom(1)} data-testid="chat-look-zoom">{Math.round(zoom * 100)}%</button>+ <button type="button" className={BTN} aria-label="Larger text" disabled={zoom >= ZOOM_MAX} onClick={() => setZoom(zoom + ZOOM_STEP)}><Plus size={10} /></button>+ </span>+ </div>+ </Section>++ <Section title="Colours">+ <ColorRow label="Reply text" value={look.modelText} onChange={set('modelText')} mode={mode} />+ <ColorRow label="Your text" value={look.userText} onChange={set('userText')} mode={mode} />+ <ColorRow label="Your bubble" value={look.userBubble} onChange={set('userBubble')} mode={mode} isSurface />+ <ColorRow label="Reply bubble" value={look.modelBubble} onChange={set('modelBubble')} mode={mode} isSurface />+ <p className={QUIET}>Every colour is kept readable (4.5:1) in light and in dark mode.</p>+ </Section>++ <Section title="Highlight">+ <div className={ROW}>+ <span className={TEXT}>"Quoted speech"</span>+ <ToggleSwitch enabled={look.highlightQuotes} onChange={set('highlightQuotes')} ariaLabel="Highlight quoted speech" />+ </div>+ {look.highlightQuotes && <ColorRow label="Quote colour" value={look.quoteText} onChange={set('quoteText')} mode={mode} />}+ <div className={ROW}>+ <span className={TEXT}><em>*Actions*</em></span>+ <ToggleSwitch enabled={look.highlightActions} onChange={set('highlightActions')} ariaLabel="Highlight actions" />+ </div>+ {look.highlightActions && <ColorRow label="Action colour" value={look.actionText} onChange={set('actionText')} mode={mode} />}+ </Section>++ <Section title="Text and layout">+ <div className={ROW}>+ <span className={TEXT}>Font</span>+ <select+ value={look.font}+ onChange={(e) => set('font')(e.target.value as ChatFont)}+ aria-label="Font"+ className="rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-white/[0.04] px-1.5 py-0.5 t-micro text-gray-700 dark:text-gray-200"+ >+ <option value="app">App</option>+ <option value="serif">Serif (book)</option>+ <option value="sans">System sans</option>+ <option value="mono">Monospace</option>+ <option value="custom">Installed font...</option>+ </select>+ </div>+ {look.font === 'custom' && (+ <input+ value={look.customFont}+ onChange={(e) => set('customFont')(e.target.value)}+ placeholder="Name of a font on this computer, e.g. Georgia"+ aria-label="Installed font name"+ className="w-full rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-black/20 px-2 py-1 t-micro text-gray-800 dark:text-gray-200 placeholder-gray-400"+ />+ )}+ <div className={ROW}>+ <span className={TEXT}>Line spacing</span>+ <input type="range" min={1.2} max={2.2} step={0.05} value={look.lineHeight} onChange={(e) => set('lineHeight')(Number(e.target.value))} aria-label="Line spacing" className="w-32" />+ </div>+ <div className={ROW}>+ <span className={TEXT}>Width</span>+ <Segmented<ChatWidth> label="Chat width" value={look.width} onChange={set('width')} options={[{ id: 'normal', label: 'Normal' }, { id: 'wide', label: 'Wide' }, { id: 'full', label: 'Full' }]} />+ </div>+ <div className={ROW}>+ <span className={TEXT}>Layout</span>+ <Segmented<ChatLayout> label="Chat layout" value={look.layout} onChange={set('layout')} options={[{ id: 'default', label: 'LU' }, { id: 'bubbles', label: 'Bubbles' }, { id: 'document', label: 'Document' }]} />+ </div>+ </Section>++ <BackgroundSection />++ <section className="px-3 py-2.5 border-b border-gray-100 dark:border-white/[0.06] space-y-1.5">+ <button type="button" onClick={() => setCssOpen((o) => !o)} className={`flex items-center gap-1 ${LABEL}`} aria-expanded={cssOpen}>+ {cssOpen ? <ChevronDown size={11} /> : <ChevronRight size={11} />} Custom CSS (advanced)+ </button>+ {cssOpen && (+ <>+ <div className={ROW}>+ <span className={TEXT}>Use my CSS</span>+ <ToggleSwitch enabled={look.customCssOn} onChange={set('customCssOn')} ariaLabel="Use custom CSS" />+ </div>+ <textarea+ value={look.customCss}+ onChange={(e) => set('customCss')(e.target.value)}+ spellCheck={false}+ rows={7}+ aria-label="Custom CSS"+ placeholder={'.lu-msg-model-text { letter-spacing: .01em }\n.lu-quote { font-weight: 600 }\n:scope[data-mode="dark"] .lu-msg-user-bubble { border-radius: 14px }'}+ className="w-full rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-black/20 px-2 py-1 font-mono t-micro leading-snug text-gray-800 dark:text-gray-200 placeholder-gray-400"+ />+ <p className={QUIET}>+ Applies to the messages only. No url(), @import, fonts or pictures from the web, no fixed boxes.+ Hooks: .lu-msg-user-text, .lu-msg-model-text, .lu-msg-user-bubble, .lu-quote, .lu-action, :scope.+ </p>+ {dropped.length > 0 && (+ <div className="rounded-md border border-red-500/30 bg-red-500/[0.05] px-2 py-1 t-micro text-red-700 dark:text-red-300" data-testid="chat-css-dropped">+ Not applied: {dropped.slice(0, 5).join(' · ')}{dropped.length > 5 ? ` and ${dropped.length - 5} more` : ''}+ </div>+ )}+ </>+ )}+ </section>++ <Section title="Share">+ <div className="flex flex-wrap gap-1">+ <button type="button" className={BTN} onClick={() => void copyLook()}><Copy size={10} /> Copy look</button>+ <button type="button" className={BTN} onClick={() => void pasteLook()}><ClipboardPaste size={10} /> Paste look</button>+ </div>+ {note && <p className={QUIET} role="status">{note}</p>}+ </Section>+ </div>+ </motion.div>+ </motion.div>,+ document.body,+ )+}++function BackgroundSection() {+ const conversation = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId))+ const personas = useSettingsStore((s) => s.personas)+ const appMode = useSettingsStore((s) => s.settings.appMode)+ const backgrounds = useChatLookStore((s) => s.backgrounds)+ const setBackground = useChatLookStore((s) => s.setBackground)+ const patchBackground = useChatLookStore((s) => s.patchBackground)+ const removeBackground = useChatLookStore((s) => s.removeBackground)+ const persona = conversation?.personaId ? personas.find((p) => p.id === conversation.personaId) : undefined+ const [target, setTarget] = useState<'chat' | 'persona'>(() => (persona && conversation && !backgrounds[bgKeyForChat(conversation.id)] && backgrounds[bgKeyForPersona(persona.id)] ? 'persona' : 'chat'))+ const [busy, setBusy] = useState<null | 'file' | 'gallery' | 'render'>(null)+ const [error, setError] = useState<string | null>(null)+ const [picking, setPicking] = useState(false)+ const [prompt, setPrompt] = useState<string | null>(null)+ const fileRef = useRef<HTMLInputElement>(null)++ if (!conversation) {+ return (+ <Section title="Background">+ <p className={QUIET}>Open a chat to give it a background picture.</p>+ </Section>+ )+ }++ const key = target === 'persona' && persona ? bgKeyForPersona(persona.id) : bgKeyForChat(conversation.id)+ const bg = backgrounds[key]++ const apply = async (what: 'file' | 'gallery' | 'render', make: () => Promise<string>) => {+ setBusy(what)+ setError(null)+ try {+ const ref = await make()+ setBackground(key, { ref, scrim: bg?.scrim ?? SCRIM_DEFAULT, blur: bg?.blur ?? 0 })+ setPicking(false)+ if (what === 'render') setPrompt(null)+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))+ } finally {+ setBusy(null)+ }+ }++ const startScene = () => {+ const texts = conversation.messages+ .filter((m) => (m.role === 'assistant' || m.role === 'user') && !m.hidden)+ .slice(-4)+ .map((m) => m.content)+ setPrompt(scenePrompt(texts))+ setError(null)+ }++ const openInCreate = () => {+ if (!prompt) return+ const create = useCreateStore.getState()+ create.setIntent('image')+ create.setPrompt(prompt)+ useUIStore.getState().setView('create')+ }++ return (+ <Section title="Background">+ {persona && (+ <div className={ROW}>+ <span className={TEXT}>For</span>+ <Segmented<'chat' | 'persona'> label="Background for" value={target} onChange={setTarget} options={[{ id: 'chat', label: 'This chat' }, { id: 'persona', label: persona.name.slice(0, 18) }]} />+ </div>+ )}+ {target === 'chat' && persona && !bg && backgrounds[bgKeyForPersona(persona.id)] && (+ <p className={QUIET}>This chat shows the picture of {persona.name}. A picture set here wins.</p>+ )}+ <div className="flex flex-wrap gap-1">+ <button type="button" className={BTN} disabled={!!busy} onClick={() => fileRef.current?.click()}><Upload size={10} /> {busy === 'file' ? 'Saving...' : 'From file'}</button>+ <button type="button" className={BTN} disabled={!!busy} onClick={() => setPicking((p) => !p)} aria-expanded={picking}><Images size={10} /> From gallery</button>+ <button type="button" className={BTN} disabled={!!busy} onClick={startScene} data-testid="chat-bg-scene"><Sparkles size={10} /> From this scene</button>+ {bg && <button type="button" className={`${BTN} hover:text-red-500`} disabled={!!busy} onClick={() => removeBackground(key)}><Trash2 size={10} /> Remove</button>}+ </div>+ <input+ ref={fileRef}+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif,image/avif"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0]+ e.target.value = ''+ if (f) void apply('file', () => storeBackground(f))+ }}+ />+ {picking && <GalleryPicker disabled={!!busy} onPick={(blob) => apply('gallery', () => blob().then(storeBackground))} />}+ {prompt !== null && (+ <div className="space-y-1 rounded-md border border-gray-200 dark:border-white/10 p-2">+ <p className={QUIET}>A picture from the latest messages. Edit the description, then make it.</p>+ <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={4} aria-label="Background description"+ className="w-full rounded border border-gray-200 dark:border-white/10 bg-white dark:bg-black/20 px-2 py-1 t-micro text-gray-800 dark:text-gray-200" />+ <div className="flex flex-wrap items-center gap-1">+ {appMode === 'cloud' ? (+ <>+ <button type="button" className={BTN} onClick={openInCreate}><Sparkles size={10} /> Open in Create</button>+ <span className={QUIET}>Create shows the price first. Then pick the picture here under From gallery.</span>+ </>+ ) : busy === 'render' ? (+ <button type="button" className={BTN} onClick={() => void cancelSceneBackground(conversation.id)}><Square size={10} /> Stop</button>+ ) : (+ <button type="button" className={BTN} disabled={!!busy || !prompt.trim()} onClick={() => void apply('render', () => renderSceneBackground(prompt, conversation.id))} data-testid="chat-bg-render">+ <Sparkles size={10} /> Make picture+ </button>+ )}+ {busy !== 'render' && <button type="button" className={BTN} onClick={() => setPrompt(null)}>Cancel</button>}+ {busy === 'render' && <span className={QUIET}>Rendering with your local image model...</span>}+ </div>+ </div>+ )}+ {bg && (+ <>+ <div className={ROW}>+ <span className={TEXT}>Readability</span>+ <input type="range" min={SCRIM_MIN} max={0.95} step={0.01} value={bg.scrim} onChange={(e) => patchBackground(key, { scrim: Number(e.target.value) })} aria-label="Background dimming" className="w-32" />+ </div>+ <div className={ROW}>+ <span className={TEXT}>Blur</span>+ <input type="range" min={0} max={16} step={1} value={bg.blur} onChange={(e) => patchBackground(key, { blur: Number(e.target.value) })} aria-label="Background blur" className="w-32" />+ </div>+ </>+ )}+ {error && <p className="t-micro text-red-600 dark:text-red-400" role="alert">{error}</p>}+ </Section>+ )+}++function GalleryPicker({ onPick, disabled }: { onPick: (blob: () => Promise<Blob>) => void; disabled: boolean }) {+ const gallery = useCreateStore((s) => s.gallery)+ const images = gallery.filter((g) => g.type === 'image' && !g.unavailable).slice(0, 24)+ const [urls, setUrls] = useState<Record<string, string>>({})+ const ids = images.map((i) => i.id).join('|')+ useEffect(() => {+ let alive = true+ // Loaded on demand: the gallery helpers pull the Create and cloud code.+ void import('../create/experimental/galleryUrl').then(({ galleryItemUrl }) => {+ if (alive) setUrls(Object.fromEntries(images.map((i) => [i.id, galleryItemUrl(i)])))+ })+ return () => { alive = false }+ // `ids` stands for the list; the items themselves are new objects per render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ids])+ if (images.length === 0) return <p className={QUIET}>No pictures in the Create gallery yet.</p>+ return (+ <div className="grid grid-cols-4 gap-1 max-h-40 overflow-y-auto scrollbar-thin" data-testid="chat-bg-gallery">+ {images.map((item) => (+ <button+ key={item.id}+ type="button"+ disabled={disabled}+ title={item.prompt.slice(0, 120)}+ onClick={() => onPick(async () => (await import('../create/experimental/galleryUrl')).fetchGalleryItemBlob(item))}+ className="aspect-square rounded overflow-hidden border border-gray-200 dark:border-white/10 hover:border-purple-400 disabled:opacity-40"+ >+ {urls[item.id] && <img src={urls[item.id]} alt="" loading="lazy" className="h-full w-full object-cover" />}+ </button>+ ))}+ </div>+ )+}diff --git a/src/components/chat/ChatLookScope.tsx b/src/components/chat/ChatLookScope.tsxnew file mode 100644index 00000000..540d5ca2--- /dev/null+++ b/src/components/chat/ChatLookScope.tsx@@ -0,0 +1,195 @@+import { createContext, useContext, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'+import { useChatLookStore } from '../../stores/chatLookStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useChatStore } from '../../stores/chatStore'+import { highlightPlain } from '../../lib/chat-highlight'+import { keyZoom, lookVars, pickBackground, wheelZoom, widthFactor, DEFAULT_LOOK } from '../../lib/chat-look'+import { sanitizeChatCss } from '../../lib/chat-css-sanitize'+import { readAttachment } from '../../lib/chat-attachments'+import { log } from '../../lib/logger'++/**+ * The transcript's look (3.1.0, C58) and reading zoom (C42), in one place.+ *+ * `variant="chat"` (Chat and Agent, MessageList) carries everything: colours,+ * highlighting, font, width, layout, the background picture and the user's+ * custom CSS. `variant="code"` (CodexView) carries the zoom only: the Code+ * transcript is diffs and logs, colouring quotes there would help nobody.+ *+ * The zoom is the one place outside the app root that uses CSS `zoom`+ * (index.css `.lu-chat-zoom`). It is the user's own reading size, like a+ * browser's Ctrl/Cmd + wheel, and it is applied to the column of messages+ * only: the header, the prompt box and the side panels keep their size.+ * Popovers inside the column measure the chain of zooms+ * (hooks/usePopoverPlatz.ts massstab), so a context menu still opens at the+ * pointer.+ */++interface HighlightFlags { quotes: boolean; actions: boolean }+const HighlightContext = createContext<HighlightFlags>({ quotes: false, actions: false })++/** Whether markdown under this scope wraps quoted speech (MarkdownRenderer). */+export function useChatHighlight(): HighlightFlags {+ return useContext(HighlightContext)+}++/** A user's message, plain text, with quotes and *actions* coloured when the+ * look asks for it. Without highlighting it is the text itself, unchanged. */+export function UserText({ text }: { text: string }) {+ const flags = useChatHighlight()+ if (!flags.quotes && !flags.actions) return <>{text}</>+ return (+ <>+ {highlightPlain(text, flags.quotes, flags.actions).map((p, i) =>+ p.kind === 'text' ? p.text+ : <span key={i} className={p.kind === 'quote' ? 'lu-quote' : 'lu-action'}>{p.text}</span>,+ )}+ </>+ )+}++/** The background picture's data URL, read from the attachment store. */+function useBackgroundUrl(ref: string | null): string | null {+ const [url, setUrl] = useState<{ ref: string; url: string } | null>(null)+ useEffect(() => {+ if (!ref) return+ let alive = true+ readAttachment(ref).then(+ (data) => { if (alive && data.startsWith('data:image/')) setUrl({ ref, url: data }) },+ (err: unknown) => log.warn('[chat-look] background picture did not load', { error: err }),+ )+ return () => { alive = false }+ }, [ref])+ return ref && url?.ref === ref ? url.url : null+}++/** On screen. A `display: contents` scope has no box of its own, so its+ * parent answers for it. */+function visible(el: HTMLElement | null): boolean {+ if (!el || !el.isConnected) return false+ return el.getClientRects().length > 0 || (el.parentElement?.getClientRects().length ?? 0) > 0+}++interface ScopeProps {+ variant: 'chat' | 'code'+ className: string+ children: ReactNode+}++export function ChatLookScope({ variant, className, children }: ScopeProps) {+ const zoom = useChatLookStore((s) => s.zoom)+ const setZoom = useChatLookStore((s) => s.setZoom)+ const look = useChatLookStore((s) => (variant === 'chat' ? s.look : DEFAULT_LOOK))+ const backgrounds = useChatLookStore((s) => s.backgrounds)+ const theme = useSettingsStore((s) => s.settings.theme)+ const mode = theme === 'light' ? 'light' : 'dark'+ const conversationId = useChatStore((s) => s.activeConversationId)+ const personaId = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId)?.personaId)+ const rootRef = useRef<HTMLDivElement>(null)+ const [badge, setBadge] = useState(0)++ const bg = variant === 'chat' ? pickBackground(backgrounds, conversationId, personaId) : null+ const bgUrl = useBackgroundUrl(bg?.bg.ref ?? null)++ // Ctrl/Cmd + wheel over the transcript, and a trackpad pinch (which macOS+ // sends as ctrl + wheel). Native and not passive: React's onWheel cannot+ // preventDefault, and WebView2 would otherwise scroll as well.+ useEffect(() => {+ const el = rootRef.current+ if (!el) return+ const onWheel = (e: WheelEvent) => {+ if (!(e.ctrlKey || e.metaKey)) return+ e.preventDefault()+ const now = useChatLookStore.getState().zoom+ const next = wheelZoom(now, e.deltaY, e.deltaMode)+ if (next !== now) setZoom(next)+ setBadge(Date.now())+ }+ el.addEventListener('wheel', onWheel, { passive: false })+ return () => el.removeEventListener('wheel', onWheel)+ }, [setZoom])++ // Ctrl/Cmd with + - 0, while this transcript is on screen.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!(e.ctrlKey || e.metaKey) || e.altKey || !visible(rootRef.current)) return+ const next = keyZoom(useChatLookStore.getState().zoom, e.key)+ if (next === null) return+ e.preventDefault()+ setZoom(next)+ setBadge(Date.now())+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [setZoom])++ useEffect(() => {+ if (!badge) return+ const t = setTimeout(() => setBadge(0), 1400)+ return () => clearTimeout(t)+ }, [badge])++ const custom = useMemo(+ () => (variant === 'chat' && look.customCssOn ? sanitizeChatCss(look.customCss).css : ''),+ [variant, look.customCssOn, look.customCss],+ )++ const vars = useMemo(() => (variant === 'chat' ? lookVars(look, mode) : {}), [variant, look, mode])+ const style = { ...vars, '--lu-chat-zoom': String(zoom) } as CSSProperties+ const factor = widthFactor(look.width)+ // "Full" is a factor no window reaches, so the column is as wide as the pane.+ if (factor !== 1) (style as Record<string, string>)['--lu-chat-width'] = factor === null ? '100' : String(factor)++ const classes = [+ className,+ 'lu-look',+ variant === 'chat' ? 'lu-chat-custom' : '',+ vars['--lu-look-model-text'] ? 'lu-look-model-color' : '',+ vars['--lu-look-user-text'] ? 'lu-look-user-color' : '',+ vars['--lu-look-user-bubble'] ? 'lu-look-user-bubble' : '',+ vars['--lu-look-quote'] ? 'lu-look-quotes' : '',+ vars['--lu-look-action'] ? 'lu-look-actions' : '',+ vars['--lu-look-font'] ? 'lu-look-font' : '',+ variant === 'chat' && look.lineHeight !== DEFAULT_LOOK.lineHeight ? 'lu-look-leading' : '',+ variant === 'chat' && look.layout !== 'default' ? `lu-look-${look.layout}` : '',+ bgUrl ? 'lu-look-has-bg' : '',+ ].filter(Boolean).join(' ')++ const flags = useMemo(+ () => ({ quotes: !!vars['--lu-look-quote'], actions: !!vars['--lu-look-action'] }),+ [vars],+ )++ return (+ <HighlightContext.Provider value={flags}>+ <div ref={rootRef} className={classes} style={style} data-mode={mode} data-testid={`chat-look-${variant}`}>+ {bgUrl && bg && (+ <div aria-hidden className="lu-chat-bg pointer-events-none absolute inset-0 overflow-hidden" data-testid="chat-background">+ <img+ src={bgUrl}+ alt=""+ className="absolute inset-0 h-full w-full object-cover"+ // The blur would show a soft pale rim at the edges; the picture+ // reaches past them by twice the radius instead.+ style={bg.bg.blur ? { filter: `blur(${bg.bg.blur}px)`, inset: `-${bg.bg.blur * 2}px`, width: 'auto', height: 'auto' } : undefined}+ />+ <div className="lu-chat-scrim absolute inset-0" style={{ opacity: bg.bg.scrim }} />+ </div>+ )}+ {custom && <style data-testid="chat-custom-css">{custom}</style>}+ {children}+ {badge > 0 && (+ <button+ type="button"+ onClick={() => { setZoom(1); setBadge(Date.now()) }}+ className="absolute right-3 top-2 z-20 rounded-full lu-elevated px-2 py-0.5 t-micro text-gray-700 dark:text-gray-200"+ title="Reset the text size (Ctrl/Cmd + 0)"+ data-testid="chat-zoom-badge"+ >+ {Math.round(zoom * 100)}%{zoom !== 1 ? ' · Reset' : ''}+ </button>+ )}+ </div>+ </HighlightContext.Provider>+ )+}diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 31d36d0d..4b7766af 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -34,6 +34,7 @@ import { LoopBar } from './LoopBar'import { GroupCostHint } from './GroupCostHint'import { GroupRoundBar } from './GroupRoundBar'import { MemoryDebugToggle } from './MemoryDebugPanel'+import { ChatLookButton } from './ChatLookPanel'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'import { SmallModelModeToggle } from './SmallModelModeToggle'@@ -648,7 +649,7 @@ export function ChatView() {Composers, `COMPOSER_MAX_W` plus dessen `px-3`; zweieigene Zahlen koennten wieder auseinanderlaufen. */}<div className={`w-full ${COMPOSER_MAX_W} mx-auto px-3`}>- <div data-testid="chat-session-strip" data-computer-note-yields="" className="flex items-center gap-1.5 px-2 py-0.5">+ <div data-testid="chat-session-strip" data-computer-note-yields="" className="flex flex-wrap items-center gap-x-1.5 gap-y-1 px-2 py-0.5"><AgentModeToggle />{appMode === 'cloud' && <HowItWorks topic="agent" variant="mark" placement="above-start" markSize={10} />}{appMode !== 'cloud' && <HowItWorks topic="chats" variant="mark" placement="above-start" markSize={10} />}@@ -681,6 +682,10 @@ export function ChatView() {picker; 2026-07-11). View / add / delete injected context. */}<MemoryDebugToggle />+ {/* Chat look (3.1.0, C58): colours, font, width,+ background, text size. */}+ <ChatLookButton />+{/* Shared chats (CHATS-V1.md): this chat on the paired phone. */}<ContinueOnPhoneButton />diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex b8618937..d23516dc 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -16,6 +16,7 @@ import { ToolCallBand } from './ToolCallBand'import { groupAgentBlocks } from '../../lib/tool-call-groups'import { ThinkingBlock } from './ThinkingBlock'import { MarkdownRenderer } from './MarkdownRenderer'+import { ChatLookScope } from './ChatLookScope'import { closeOpenMarkdown } from '../../lib/streaming-markdown'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'@@ -393,6 +394,9 @@ export function CodexView() {{/* Messages */}<div className="relative flex-1 min-h-[10rem] flex flex-col">+ {/* `contents`: the scope adds no box, the floor above stays the one+ box that holds banner, transcript and rail (die-karte-bleibt-erreichbar). */}+ <ChatLookScope variant="code" className="contents"><CompactLayerBanner view={layers} /><divref={scrollRef}@@ -427,7 +431,7 @@ export function CodexView() {)}</div>) : (- <div ref={contentRef} className="py-1">+ <div ref={contentRef} className="lu-chat-zoom py-1">{shownItems.map((item) => {if (item.kind === 'line') return <CompactBlock key={item.cut.key} cut={item.cut} />const msg = item.message@@ -754,6 +758,7 @@ export function CodexView() {)}</div><CompactLayerRail view={layers} />+ </ChatLookScope></div>{/* Die stehenden Sitzungsbaender und die Zeilen, die frueher IMdiff --git a/src/components/chat/MarkdownRenderer.tsx b/src/components/chat/MarkdownRenderer.tsxindex fe93f798..d56bc6dd 100644--- a/src/components/chat/MarkdownRenderer.tsx+++ b/src/components/chat/MarkdownRenderer.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import ReactMarkdown from 'react-markdown'import remarkGfm from 'remark-gfm'import remarkMath from 'remark-math'@@ -10,6 +10,8 @@ import { openExternal } from '../../api/backend'import { useComfyViewRescue, isInlineVideoUrl } from './comfyViewRescue'import { log } from '../../lib/logger'import type { Components, Options } from 'react-markdown'+import { rehypeQuoteHighlight } from '../../lib/chat-highlight'+import { useChatHighlight } from './ChatLookScope'interface Props {content: string@@ -193,7 +195,11 @@ const components: Components = {}export function MarkdownRenderer({ content }: Props) {- const rehypePlugins = useRehypePlugins(content)+ const math = useRehypePlugins(content)+ // Quoted speech in its own colour, only where the chat look asks for it+ // (ChatLookScope, 3.1.0 C58). After KaTeX, so a formula is never split.+ const { quotes } = useChatHighlight()+ const rehypePlugins = useMemo(() => (quotes ? [...math, rehypeQuoteHighlight] : math), [quotes, math])return (// wrap-anywhere: a URL, hash or base64 run without a space used to run out// of the bubble and get cut at the window edge (T1 night test 3.0.9, A5).diff --git a/src/components/chat/MemoryDebugPanel.tsx b/src/components/chat/MemoryDebugPanel.tsxindex 3a9d2c36..9742f86a 100644--- a/src/components/chat/MemoryDebugPanel.tsx+++ b/src/components/chat/MemoryDebugPanel.tsx@@ -1,7 +1,8 @@import { useState, useEffect } from 'react'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'import { createPortal } from 'react-dom'-import { Brain, X, Plus, Trash2, ChevronDown, Archive, ListChecks } from 'lucide-react'+import { Brain, X, Plus, Trash2, ChevronDown, ChevronRight, Archive, ListChecks, Pencil, Check } from 'lucide-react'+import type { MemoryFile, MemoryType } from '../../types/agent-mode'import { useMemoryStore } from '../../stores/memoryStore'import { useModelStore } from '../../stores/modelStore'import { getModelMaxTokens } from '../../lib/context-compaction'@@ -98,8 +99,8 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {// Gruen und Grau haengen an den drei anderen Kategorien, Violett traegt die// Panel-Umrandung, Rot den Loeschknopf.const typeColors: Record<string, string> = {- user: 'text-blue-400', feedback: 'text-green-400',- project: 'text-cyan-400', reference: 'text-gray-400',+ user: 'text-blue-600 dark:text-blue-400', feedback: 'text-green-700 dark:text-green-400',+ project: 'text-cyan-700 dark:text-cyan-400', reference: 'text-gray-500 dark:text-gray-400',}const handleAdd = () => {@@ -150,7 +151,7 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {onClick={() => { setSelecting((on) => !on); setSelected(new Set()); setConfirm(null) }}title="Select several memories to delete"aria-pressed={selecting}- className={'flex items-center gap-1 px-1.5 py-0.5 rounded t-micro font-medium transition-colors ' + (selecting ? 'bg-purple-500/15 text-purple-300' : 'text-gray-500 hover:text-gray-300 hover:bg-white/10')}+ className={'flex items-center gap-1 px-1.5 py-0.5 rounded t-micro font-medium transition-colors ' + (selecting ? 'bg-purple-500/15 text-purple-700 dark:text-purple-300' : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/10')}><ListChecks size={11} /> Select</button>@@ -167,11 +168,11 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {<buttononClick={() => setAdding((a) => !a)}title="Add a memory"- className={'flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.55rem] font-medium transition-colors ' + (adding ? 'bg-purple-500/15 text-purple-300' : 'text-gray-500 hover:text-gray-300 hover:bg-white/10')}+ className={'flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.55rem] font-medium transition-colors ' + (adding ? 'bg-purple-500/15 text-purple-700 dark:text-purple-300' : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/10')}><Plus size={11} /> Add</button>- <button onClick={onClose} className="p-0.5 rounded hover:bg-white/10 text-gray-500"><X size={12} /></button>+ <button onClick={onClose} aria-label="Close" className="p-0.5 rounded hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500"><X size={12} /></button></div></div>@@ -180,10 +181,10 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {)}{selecting && !confirm && (- <div className="flex items-center gap-2 px-3 py-1 border-b border-white/[0.06] t-micro text-gray-500 shrink-0">+ <div className="flex items-center gap-2 px-3 py-1 border-b border-gray-100 dark:border-white/[0.06] t-micro text-gray-500 shrink-0"><buttononClick={() => setSelected(selectedIds.length === entries.length ? new Set() : new Set(entries.map((e) => e.id)))}- className="underline hover:text-gray-300"+ className="underline hover:text-gray-800 dark:hover:text-gray-300">{selectedIds.length === entries.length ? 'Select none' : 'Select all'}</button>@@ -191,7 +192,7 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {<buttononClick={() => setConfirm({ ids: selectedIds, all: selectedIds.length === entries.length })}disabled={selectedIds.length === 0}- className="flex items-center gap-1 px-2 py-0.5 rounded font-medium bg-red-500/15 border border-red-500/30 text-red-300 hover:bg-red-500/25 disabled:opacity-40"+ className="flex items-center gap-1 px-2 py-0.5 rounded font-medium bg-red-500/15 border border-red-500/30 text-red-700 dark:text-red-300 hover:bg-red-500/25 disabled:opacity-40"><Trash2 size={10} /> Delete {selectedIds.length > 0 ? memoriesWord(selectedIds.length) : 'selected'}</button>@@ -200,12 +201,12 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {{/* Add form */}{adding && (- <div className="px-3 py-2 border-b border-white/[0.06] bg-white/[0.02] space-y-1.5 shrink-0">+ <div className="px-3 py-2 border-b border-gray-100 dark:border-white/[0.06] bg-gray-50 dark:bg-white/[0.02] space-y-1.5 shrink-0"><inputvalue={newTitle}onChange={(e) => setNewTitle(e.target.value)}placeholder="Title (optional)"- className="w-full px-2 py-1 rounded bg-black/20 border border-white/10 t-micro text-gray-200 placeholder-gray-600 focus:outline-none focus:border-purple-500/40"+ className={FIELD}/><LongTextFieldvalue={newContent}@@ -214,11 +215,11 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {label="Memory"placeholder="What should the model always remember? (injected into every prompt)"rows={3}- className="block w-full px-2 py-1 rounded bg-black/20 border border-white/10 t-micro text-gray-200 placeholder-gray-600 focus:outline-none focus:border-purple-500/40"+ className={`block ${FIELD}`}/><div className="flex justify-end gap-1.5">- <button onClick={() => { setAdding(false); setNewTitle(''); setNewContent('') }} className="px-2 py-1 rounded t-micro text-gray-400 hover:text-gray-200 hover:bg-white/10">Cancel</button>- <button onClick={handleAdd} disabled={!newContent.trim()} className="flex items-center gap-1 px-2.5 py-1 rounded t-micro font-medium bg-purple-500/20 border border-purple-500/30 text-purple-200 hover:bg-purple-500/30 disabled:opacity-40">+ <button onClick={() => { setAdding(false); setNewTitle(''); setNewContent('') }} className={QUIET_BTN}>Cancel</button>+ <button onClick={handleAdd} disabled={!newContent.trim()} className={SAVE_BTN}><Plus size={10} /> Save memory</button></div>@@ -228,35 +229,21 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {{/* Memory list: every row has its own delete, always visible (A27) */}<div className="overflow-y-auto flex-1 scrollbar-thin">{entries.length === 0 ? (- <p className="t-micro text-gray-600 px-3 py-5 text-center">No memories yet, click <span className="text-purple-400">Add</span> to write one.</p>+ <p className="t-micro text-gray-500 dark:text-gray-400 px-3 py-5 text-center">No memories yet, click <span className="text-purple-600 dark:text-purple-400">Add</span> to write one.</p>) : (// All of them. Until A27 only the first 50 were listed, so number// 51 and later could not be deleted here at all.- entries.map((entry) => {- const stale = entry.stale === true || typeof entry.supersededBy === 'string'- return (- <div key={entry.id} className={`group px-3 py-1.5 border-b border-white/[0.03] hover:bg-white/[0.02] ${stale ? 'opacity-50' : ''}`}>- <div className="flex items-center gap-1.5">- {selecting && (- <input- type="checkbox"- checked={selected.has(entry.id)}- onChange={() => toggleSelected(entry.id)}- aria-label={`Select ${entry.title}`}- className="shrink-0 accent-purple-500"- />- )}- <span className={`text-[0.5rem] uppercase font-bold tracking-wider ${typeColors[entry.type] || 'text-gray-500'}`}>{entry.type}</span>- <span className="t-micro text-gray-300 font-medium truncate flex-1">{entry.title}</span>- {stale && (- <span className="flex items-center gap-0.5 text-[0.45rem] uppercase tracking-wider text-gray-500 shrink-0" title="Outdated, not injected"><Archive size={8} /> outdated</span>- )}- {!selecting && <MemoryRowDelete title={entry.title} onDelete={() => remove([entry.id])} />}- </div>- <p className="text-[0.55rem] text-gray-600 truncate mt-0.5">{entry.content.substring(0, 120)}</p>- </div>- )- })+ entries.map((entry) => (+ <MemoryRow+ key={entry.id}+ entry={entry}+ selecting={selecting}+ selected={selected.has(entry.id)}+ onToggleSelected={() => toggleSelected(entry.id)}+ onDelete={() => remove([entry.id])}+ typeColor={typeColors[entry.type] || 'text-gray-500'}+ />+ )))}</div>@@ -264,12 +251,12 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {{/* Injection preview — exactly what gets prepended to the prompt */}{injectedPreview && (- <div className="border-t border-white/[0.06] px-3 py-2 shrink-0">+ <div className="border-t border-gray-100 dark:border-white/[0.06] px-3 py-2 shrink-0"><div className="flex items-center gap-1 mb-1">- <ChevronDown size={10} className="text-gray-600" />- <span className="text-[0.5rem] uppercase tracking-wider text-gray-600 font-semibold">Injected into prompt</span>+ <ChevronDown size={10} className="text-gray-500" />+ <span className="text-[0.5rem] uppercase tracking-wider text-gray-500 font-semibold">Injected into prompt</span></div>- <pre className="text-[0.5rem] text-gray-500 font-mono whitespace-pre-wrap max-h-20 overflow-y-auto scrollbar-thin leading-relaxed">{injectedPreview.substring(0, 800)}</pre>+ <pre className="text-[0.5rem] text-gray-600 dark:text-gray-400 font-mono whitespace-pre-wrap max-h-20 overflow-y-auto scrollbar-thin leading-relaxed">{injectedPreview.substring(0, 800)}</pre></div>)}</div>@@ -277,3 +264,115 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {document.body,)}++const FIELD = 'w-full px-2 py-1 rounded bg-white dark:bg-black/20 border border-gray-200 dark:border-white/10 t-micro text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none focus:border-purple-500/40'+const QUIET_BTN = 'px-2 py-1 rounded t-micro text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10'+const SAVE_BTN = 'flex items-center gap-1 px-2.5 py-1 rounded t-micro font-medium bg-purple-500/15 dark:bg-purple-500/20 border border-purple-500/30 text-purple-800 dark:text-purple-200 hover:bg-purple-500/25 dark:hover:bg-purple-500/30 disabled:opacity-40'+const MEMORY_TYPES: MemoryType[] = ['user', 'feedback', 'project', 'reference']++/**+ * One memory in the quick menu (C38, testowanie642): the line used to stop+ * after about 90 characters with no way to see or change the rest, so a+ * long memory could only be deleted and typed again. A click on the row+ * opens the whole text; Edit changes title, kind and text in place. The+ * store re-embeds a memory whose title or text changed (memoryStore+ * updateMemory), so search keeps finding it by its new words.+ */+function MemoryRow({ entry, selecting, selected, onToggleSelected, onDelete, typeColor }: {+ entry: MemoryFile+ selecting: boolean+ selected: boolean+ onToggleSelected: () => void+ onDelete: () => void+ typeColor: string+}) {+ const updateMemory = useMemoryStore((s) => s.updateMemory)+ const [open, setOpen] = useState(false)+ const [editing, setEditing] = useState(false)+ const [title, setTitle] = useState(entry.title)+ const [content, setContent] = useState(entry.content)+ const [type, setType] = useState<MemoryType>(entry.type)+ const stale = entry.stale === true || typeof entry.supersededBy === 'string'++ const startEdit = () => {+ setTitle(entry.title)+ setContent(entry.content)+ setType(entry.type)+ setEditing(true)+ setOpen(true)+ }+ const save = () => {+ const text = content.trim()+ if (!text) return+ const derived = !entry.description || entry.description === entry.content.slice(0, 120)+ updateMemory(entry.id, {+ title: title.trim() || text.slice(0, 60),+ content: text,+ type,+ ...(derived ? { description: text.slice(0, 120) } : {}),+ })+ setEditing(false)+ }++ return (+ <div className={`group px-3 py-1.5 border-b border-gray-100 dark:border-white/[0.03] hover:bg-gray-50 dark:hover:bg-white/[0.02] ${stale ? 'opacity-50' : ''}`} data-testid="memory-row">+ <div className="flex items-center gap-1.5">+ {selecting && (+ <input+ type="checkbox"+ checked={selected}+ onChange={onToggleSelected}+ aria-label={`Select ${entry.title}`}+ className="shrink-0 accent-purple-500"+ />+ )}+ <button+ type="button"+ onClick={() => !editing && setOpen((o) => !o)}+ aria-expanded={open}+ className="flex min-w-0 flex-1 items-center gap-1.5 text-left"+ title={open ? 'Collapse' : 'Show the whole memory'}+ >+ {open ? <ChevronDown size={10} className="shrink-0 text-gray-400" /> : <ChevronRight size={10} className="shrink-0 text-gray-400" />}+ <span className={`text-[0.5rem] uppercase font-bold tracking-wider ${typeColor}`}>{entry.type}</span>+ <span className="t-micro text-gray-800 dark:text-gray-300 font-medium truncate flex-1">{entry.title}</span>+ </button>+ {stale && (+ <span className="flex items-center gap-0.5 text-[0.45rem] uppercase tracking-wider text-gray-500 shrink-0" title="Outdated, not injected"><Archive size={8} /> outdated</span>+ )}+ {!selecting && !editing && (+ <button type="button" onClick={startEdit} title="Edit this memory" aria-label={`Edit ${entry.title}`} className="p-0.5 rounded text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10" data-testid="memory-edit">+ <Pencil size={10} />+ </button>+ )}+ {!selecting && <MemoryRowDelete title={entry.title} onDelete={onDelete} />}+ </div>+ {editing ? (+ <div className="mt-1 space-y-1.5" onKeyDown={(e) => { if (e.key === 'Escape') { e.stopPropagation(); setEditing(false) } }}>+ <div className="flex gap-1">+ <select value={type} onChange={(e) => setType(e.target.value as MemoryType)} aria-label="Kind of memory" className={`${FIELD} w-auto`}>+ {MEMORY_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}+ </select>+ <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" aria-label="Memory title" className={FIELD} />+ </div>+ <LongTextField+ value={content}+ onChange={setContent}+ storageKey="memory-edit-content"+ label="Memory"+ rows={5}+ className={`block ${FIELD}`}+ />+ <div className="flex justify-end gap-1.5">+ <button type="button" onClick={() => setEditing(false)} className={QUIET_BTN}>Cancel</button>+ <button type="button" onClick={save} disabled={!content.trim()} className={SAVE_BTN} data-testid="memory-save"><Check size={10} /> Save</button>+ </div>+ </div>+ ) : open ? (+ <p className="mt-1 max-h-48 overflow-y-auto scrollbar-thin whitespace-pre-wrap wrap-anywhere t-micro leading-relaxed text-gray-700 dark:text-gray-300" data-testid="memory-full">{entry.content}</p>+ ) : (+ <p className="text-[0.55rem] text-gray-500 dark:text-gray-500 truncate mt-0.5">{entry.content}</p>+ )}+ </div>+ )+}diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex 83febd88..f0b1a753 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -5,6 +5,7 @@ import { motion } from 'framer-motion'import { User, Copy, Check, Pencil, RefreshCw, Wrench, Trash2, Scissors, Unlink, Film, Music, GitBranch, ListRestart } from 'lucide-react'import { useState, useRef, useEffect, useMemo, memo } from 'react'import { MarkdownRenderer } from './MarkdownRenderer'+import { UserText } from './ChatLookScope'import { closeOpenMarkdown } from '../../lib/streaming-markdown'import { ThinkingBlock } from './ThinkingBlock'import { ToolCallBand } from './ToolCallBand'@@ -336,7 +337,7 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, preturn (<motion.div- className={'flex gap-2 px-3 py-1 group ' + (isUser ? 'flex-row-reverse' : '')}+ className={'flex gap-2 px-3 py-1 group ' + (isUser ? 'flex-row-reverse lu-msg-row lu-msg-row-user' : 'lu-msg-row lu-msg-row-model')}onContextMenu={(e) => {if (!actionsAvailable) returne.preventDefault()@@ -349,20 +350,20 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, p>{/* The avatar column (avatar-slot.ts): a chip for the user, the bare mark for the model. */}{isUser ? (- <div className={AVATAR_SLOT}>+ <div className={AVATAR_SLOT} data-msg-avatar="">{userAvatarDataUrl? <img src={userAvatarDataUrl} alt="" className="w-full h-full object-cover" />: <User size={11} className="text-gray-400" />}</div>) : (- <div className={MODEL_MARK_SLOT} data-testid="model-mark">+ <div className={MODEL_MARK_SLOT} data-msg-avatar="" data-testid="model-mark"><img src={MONOGRAM} alt="" className={`${MODEL_MARK} ${MONOGRAM_INVERT}`} /></div>)}{/* A reply with a Create order takes the full width in a narrow window:the card and the result need the room. */}- <div ref={columnRef} className={(hasCreateOrder ? 'min-w-0 flex-1 sm:flex-none sm:max-w-[80%]' : 'max-w-[80%]') + ' space-y-0.5'}>+ <div ref={columnRef} className={'lu-msg-column ' + (hasCreateOrder ? 'min-w-0 flex-1 sm:flex-none sm:max-w-[80%]' : 'max-w-[80%]') + ' space-y-0.5'}>{/* Name the model that produced this answer. Group chats have alwaysdone this; since the R5 re-measure (2026-08-30) every assistantturn carries it, because the app had no model name at a single@@ -459,7 +460,7 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, pconst istSchluss = gruppenIndex === gruppen.length - 1return (<div key={block.id} className="px-1 py-0.5">- <div data-copy-text className={'text-[0.8rem] leading-relaxed' + (isStreaming && istSchluss ? ' lu-caret' : '')}>+ <div data-copy-text className={'lu-msg-text lu-msg-model-text ' + 'text-[0.8rem] leading-relaxed' + (isStreaming && istSchluss ? ' lu-caret' : '')}><MarkdownRenderer content={isStreaming && istSchluss ? closeOpenMarkdown(clean) : clean} /></div></div>@@ -518,8 +519,8 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, pclassName={'relative ' +(isUser- ? 'rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08] focus-within:border-gray-400 dark:focus-within:border-white/20 transition-colors'- : 'px-1 py-0.5')+ ? 'lu-msg-user-bubble rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08] focus-within:border-gray-400 dark:focus-within:border-white/20 transition-colors'+ : 'lu-msg-model-bubble px-1 py-0.5')}>{isEditing ? (@@ -567,7 +568,7 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, p// long expanded instruction held in content (which drives the model).// The same holds for a message with files: content carries their// summaries for the model, the bubble shows what was typed.- <p data-copy-text className="text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap wrap-anywhere">{message.displayContent || message.content}</p>+ <p data-copy-text className="lu-msg-text lu-msg-user-text text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap wrap-anywhere"><UserText text={message.displayContent || message.content} /></p>) : (// Answer-blocks (when present) already rendered the per-iteration// text chronologically above; skip message.content here to avoid@@ -584,7 +585,7 @@ function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, p// eine reine Funktion des vorhandenen `isStreaming`-Props —// kein Zustand, kein Timer, keine Subscription, also auch// kein Rerender, den der Stream nicht ohnehin ausloest.- <div data-copy-text className={'text-[0.78rem] leading-relaxed' + (isStreaming ? ' lu-caret' : '')}>+ <div data-copy-text className={'lu-msg-text lu-msg-model-text ' + 'text-[0.78rem] leading-relaxed' + (isStreaming ? ' lu-caret' : '')}>{/* While it streams, an open ` or ** is closed for the frame(lib/streaming-markdown.ts); the stored text is untouched. */}<MarkdownRenderer content={isStreaming ? closeOpenMarkdown(cleanContent) : cleanContent} />diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex b8978d13..d267c836 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -12,6 +12,7 @@ import { CompactBlock } from './CompactBlock'import { CompactLayerBanner, CompactLayerRail, useCompactLayers } from './CompactLayerRail'import { Hinweis } from '../ui/Hinweis'import { TRANSCRIPT_MAX_PX } from './composer-width'+import { ChatLookScope } from './ChatLookScope'import { useAgentModeStore } from '../../stores/agentModeStore'import { latestRefusalId, refusalNoticeApplies } from '../../lib/refusal-detect'import { GreetingSwitcher } from './GreetingSwitcher'@@ -244,7 +245,7 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelreturn (<>- <div className="relative flex-1 min-h-0 flex flex-col">+ <ChatLookScope variant="chat" className="relative flex-1 min-h-0 flex flex-col"><CompactLayerBanner view={layers} /><divref={scrollRef}@@ -268,7 +269,7 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelder Promptbox aus, damit hier keine zweite Zahl neben der einensteht; als `style`, weil Tailwind Klassennamen scannt und einegerechnete Breite deshalb keine Regel bekaeme. */}- <div ref={contentRef} className="mx-auto w-full" style={{ maxWidth: TRANSCRIPT_MAX_PX }}>+ <div ref={contentRef} className="lu-chat-zoom mx-auto w-full" style={{ maxWidth: `calc(${TRANSCRIPT_MAX_PX}px * var(--lu-chat-width, 1))` }}>{items.map((item, index) => {if (item.kind === 'line') return <CompactBlock key={item.cut.key} cut={item.cut} />@@ -367,7 +368,7 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel</div></div><CompactLayerRail view={layers} />- </div>+ </ChatLookScope>{/* GH #199: later speakers of this round already answered. Ask beforeanything moves. Outside the scrolling list, whose mask would clip it. */}<Modal open={!!askRegen} onClose={() => setAskRegen(null)} title="Regenerate this answer" maxWidth="max-w-md">diff --git a/src/components/chat/__tests__/lange-woerter-brechen-in-der-blase-um.test.ts b/src/components/chat/__tests__/lange-woerter-brechen-in-der-blase-um.test.tsindex 8c9ee85a..9a22752e 100644--- a/src/components/chat/__tests__/lange-woerter-brechen-in-der-blase-um.test.ts+++ b/src/components/chat/__tests__/lange-woerter-brechen-in-der-blase-um.test.ts@@ -13,6 +13,9 @@ describe('a word without spaces in a chat bubble', () => {expect(src('MarkdownRenderer.tsx')).toMatch(/className="markdown-content[^"]*\bwrap-anywhere\b/)})it('wraps in the user bubble', () => {- expect(src('MessageBubble.tsx')).toMatch(/whitespace-pre-wrap wrap-anywhere">\{message\.displayContent \|\| message\.content\}/)+ // 3.1.0 (C58): the text goes through <UserText>, which only colours+ // quotes and actions when the chat look asks for it; the paragraph and+ // its wrapping are unchanged.+ expect(src('MessageBubble.tsx')).toMatch(/whitespace-pre-wrap wrap-anywhere">(\{message\.displayContent \|\| message\.content\}|<UserText text=\{message\.displayContent \|\| message\.content\} \/>)/)})})diff --git a/src/components/chat/__tests__/memory-panel-edit.test.tsx b/src/components/chat/__tests__/memory-panel-edit.test.tsxnew file mode 100644index 00000000..03d41627--- /dev/null+++ b/src/components/chat/__tests__/memory-panel-edit.test.tsx@@ -0,0 +1,67 @@+// @vitest-environment jsdom+/**+ * C38 (3.1.0, testowanie642): the Memory quick menu cut every memory after+ * about 90 characters, and there was no way to read or change the rest. A row+ * now opens to the whole text, and Edit changes it in place.+ *+ * Run: npx vitest run src/components/chat/__tests__/memory-panel-edit.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useMemoryStore, __setMemoryEmbedFn } from '../../../stores/memoryStore'+import { MemoryDebugToggle } from '../MemoryDebugPanel'++const LONG = 'The user runs a small bakery in Lodz and prefers answers in Polish. ' ++ 'They bake rye bread on Fridays and want recipes in grams, never cups. The oven tops out at 250 C.'++function open() {+ render(<MemoryDebugToggle />)+ fireEvent.click(screen.getByTitle('Memory: view, add or delete the context injected into prompts'))+}++beforeEach(() => {+ __setMemoryEmbedFn(async (texts: string[]) => texts.map(() => []))+ useMemoryStore.setState({ entries: [], forgotten: [], activeMemoryOwner: null })+ useMemoryStore.getState().addMemory({ type: 'user', title: 'Bakery', description: LONG.slice(0, 120), content: LONG, tags: [], source: 'manual' })+})+afterEach(() => cleanup())++describe('Memory quick menu: read and edit the whole memory', () => {+ it('a click on the row shows the whole text, not a cut line', () => {+ open()+ expect(screen.queryByTestId('memory-full')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: /Bakery/, expanded: false }))+ expect(screen.getByTestId('memory-full').textContent).toBe(LONG)+ })++ it('Edit changes title, kind and text, and the short line follows', () => {+ open()+ fireEvent.click(screen.getByLabelText('Edit Bakery'))+ fireEvent.change(screen.getByLabelText('Memory title'), { target: { value: 'Bakery in Lodz' } })+ fireEvent.change(screen.getByLabelText('Kind of memory'), { target: { value: 'project' } })+ const field = screen.getByRole('textbox', { name: 'Memory' })+ fireEvent.change(field, { target: { value: LONG + ' New: gluten free on Mondays.' } })+ fireEvent.click(screen.getByTestId('memory-save'))+ const e = useMemoryStore.getState().entries[0]+ expect(e.title).toBe('Bakery in Lodz')+ expect(e.type).toBe('project')+ expect(e.content.endsWith('gluten free on Mondays.')).toBe(true)+ expect(e.description).toBe(e.content.slice(0, 120))+ expect(screen.getByTestId('memory-full').textContent).toContain('gluten free on Mondays.')+ })++ it('Cancel leaves the memory as it was', () => {+ open()+ fireEvent.click(screen.getByLabelText('Edit Bakery'))+ fireEvent.change(screen.getByRole('textbox', { name: 'Memory' }), { target: { value: 'gone' } })+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(useMemoryStore.getState().entries[0].content).toBe(LONG)+ })++ it('an empty text cannot be saved', () => {+ open()+ fireEvent.click(screen.getByLabelText('Edit Bakery'))+ fireEvent.change(screen.getByRole('textbox', { name: 'Memory' }), { target: { value: ' ' } })+ expect((screen.getByTestId('memory-save') as HTMLButtonElement).disabled).toBe(true)+ })+})diff --git a/src/hooks/usePopoverPlatz.ts b/src/hooks/usePopoverPlatz.tsindex dc7f1543..16d85fd9 100644--- a/src/hooks/usePopoverPlatz.ts+++ b/src/hooks/usePopoverPlatz.ts@@ -64,11 +64,26 @@ const KEIN_STIL: CSSProperties = {}/** Was die Engine ueber Zoom und Kastenmass verraet, an der App-Wurzel des Elements abgelesen. */export function massstab(el: Element): Massstab {+ // Seit 3.1.0 (C42) kann zwischen Wurzel und Element ein zweiter Zoom+ // liegen, der Lese-Zoom des Transkripts (.lu-chat-zoom). Gezaehlt wird+ // deshalb die KETTE: das Produkt aller Zooms bis zum Body, gemessen am+ // tiefsten gezoomten Vorfahren, denn dort ist das Verhaeltnis von Kasten+ // zu CSS-Mass genau dieses Produkt (oder 1, je nach Engine). Ohne Lese-+ // Zoom ist der tiefste gezoomte Vorfahr die Wurzel, alles wie bisher.let wurzel = el- while (wurzel.parentElement && wurzel.parentElement !== document.body) wurzel = wurzel.parentElement- const zoom = parseFloat(getComputedStyle(wurzel).zoom) || 1- const r = wurzel.getBoundingClientRect()- const css = wurzel instanceof HTMLElement ? wurzel.offsetWidth + wurzel.offsetHeight : 0+ let zoom = 1+ let tiefster: Element | null = null+ for (let p: Element | null = el; p && p !== document.body; p = p.parentElement) {+ const z = parseFloat(getComputedStyle(p).zoom) || 1+ if (z !== 1) {+ zoom *= z+ tiefster ??= p+ }+ wurzel = p+ }+ const messen = tiefster ?? wurzel+ const r = messen.getBoundingClientRect()+ const css = messen instanceof HTMLElement ? messen.offsetWidth + messen.offsetHeight : 0return {zoom,verhaeltnis: css > 0 ? (r.width + r.height) / css : zoom,diff --git a/src/index.css b/src/index.cssindex 5d334dcb..90bd39d9 100644--- a/src/index.css+++ b/src/index.css@@ -2969,3 +2969,70 @@ input[type="range"].neuron-range:disabled { cursor: not-allowed; opacity: 0.5; }@media (prefers-reduced-motion: reduce) {.neuron-bar-wait { animation: none; transform: none; }}++/* ── Chat look (3.1.0, C58 / C42) ──────────────────────────────────────+ Rules for components/chat/ChatLookScope.tsx. Every colour arrives as a+ custom property that lib/chat-look.ts has already checked for 4.5:1+ against the pane in the current mode, and a rule only applies when the+ scope carries its class, i.e. when the user picked that colour. With no+ choice made, nothing here matches and the chat looks as before.+ Unlayered on purpose: these must win over the Tailwind utilities on the+ same elements (text-gray-800, leading-relaxed, max-w-[80%]). */++/* The reading zoom. The ONE sanctioned zoom besides --ui-scale on the app+ root (ein-massstab.test.ts): it is the user's own text size, set with+ Ctrl/Cmd + wheel like browser zoom, on the message column only. */+.lu-chat-zoom { zoom: var(--lu-chat-zoom, 1); }++.lu-look-model-color .lu-msg-model-text .markdown-content { color: var(--lu-look-model-text); }+.lu-look-user-color .lu-msg-user-text { color: var(--lu-look-user-text); }+.lu-look-user-bubble .lu-msg-user-bubble {+ background-color: var(--lu-look-user-bubble);+ border-color: color-mix(in srgb, var(--lu-look-user-bubble), currentColor 14%);+}+.lu-look-quotes .lu-quote { color: var(--lu-look-quote); }+.lu-look-actions .lu-msg-text em,+.lu-look-actions .lu-action { color: var(--lu-look-action); font-style: italic; }+.lu-look-font .lu-msg-text { font-family: var(--lu-look-font); }+.lu-look-leading .lu-msg-text,+.lu-look-leading .lu-msg-text :is(p, li) { line-height: var(--lu-look-leading); }++/* Layout "bubbles": the reply gets a bubble too. */+.lu-look-bubbles .lu-msg-model-bubble {+ border-radius: 0.5rem;+ padding: 0.375rem 0.625rem;+ background-color: var(--lu-look-model-bubble, #f3f4f6);+ border: 1px solid rgba(0, 0, 0, 0.06);+}+.lu-look-bubbles[data-mode="dark"] .lu-msg-model-bubble {+ background-color: var(--lu-look-model-bubble, rgba(255, 255, 255, 0.04));+ border-color: rgba(255, 255, 255, 0.07);+}++/* Layout "document": one flowing text, no avatars, every turn left. */+.lu-look-document .lu-msg-row { flex-direction: row; }+.lu-look-document [data-msg-avatar] { display: none; }+.lu-look-document .lu-msg-column { max-width: 100%; flex: 1 1 auto; min-width: 0; }+.lu-look-document .lu-msg-row-user .lu-msg-column > * { justify-content: flex-start; }+.lu-look-document .lu-msg-user-bubble {+ background-color: transparent;+ border-width: 0 0 0 2px;+ border-radius: 0;+ padding-left: 0.625rem;+}++/* The background picture lies BEHIND the transcript (isolation makes the+ scope a stacking context, the picture sits at -1 inside it) under a scrim+ of the pane colour, whose strength has a floor (lib/chat-look SCRIM_MIN). */+.lu-look-has-bg { isolation: isolate; }+.lu-look-has-bg > .lu-chat-bg {+ z-index: -1;+ /* Soft edge toward the session strip and the prompt box below, which+ keep the plain pane colour: no hard line under the last message. */+ -webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - 64px), transparent);+ mask-image: linear-gradient(to bottom, #000 calc(100% - 64px), transparent);+}+.lu-chat-scrim { background-color: #ffffff; }+.lu-look[data-mode="dark"] .lu-chat-scrim { background-color: #1e1e1e; }+.lu-look-has-bg .lu-msg-text { text-shadow: 0 0 6px rgba(255, 255, 255, 0.55); }+.lu-look-has-bg[data-mode="dark"] .lu-msg-text { text-shadow: 0 0 6px rgba(0, 0, 0, 0.6); }diff --git a/src/lib/__tests__/chat-background.test.ts b/src/lib/__tests__/chat-background.test.tsnew file mode 100644index 00000000..dca0f7d4--- /dev/null+++ b/src/lib/__tests__/chat-background.test.ts@@ -0,0 +1,19 @@+import { describe, it, expect } from 'vitest'+import { generatedOk, resultUrl } from '../chat-background'++describe('reading the image_generate result for a scene background', () => {+ it('finds the address on the last line', () => {+ const r = 'Image generated: LU_00012_.png (prompt: "harbour at dusk")\nhttp://127.0.0.1:8188/view?filename=LU_00012_.png&type=output'+ expect(resultUrl(r)).toBe('http://127.0.0.1:8188/view?filename=LU_00012_.png&type=output')+ expect(generatedOk(r)).toBe(true)+ })+ it('a Mac render hands a blob address', () => {+ expect(generatedOk('Image generated: mflux.png (prompt: "x")\nblob:http://localhost/abc')).toBe(true)+ })+ it.each([+ 'Error: No local image model is installed yet.',+ 'Cannot generate: width must be a number from 64 to 4096 pixels',+ 'Image generation cancelled.',+ 'Image generated: but no address',+ ])('refuses %s', (r) => expect(generatedOk(r)).toBe(false))+})diff --git a/src/lib/__tests__/chat-css-sanitize.test.ts b/src/lib/__tests__/chat-css-sanitize.test.tsnew file mode 100644index 00000000..1635aeb1--- /dev/null+++ b/src/lib/__tests__/chat-css-sanitize.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect } from 'vitest'+import { CSS_SCOPE, sanitizeChatCss, scopeSelector } from '../chat-css-sanitize'++const clean = (s: string) => sanitizeChatCss(s).css++describe('chat CSS: what is allowed comes out scoped', () => {+ it('scopes every selector to the transcript', () => {+ expect(clean('.lu-quote { color: red }')).toBe(`${CSS_SCOPE} .lu-quote { color: red }`)+ expect(clean('p, li { font-weight: 600 }')).toBe(`${CSS_SCOPE} p, ${CSS_SCOPE} li { font-weight: 600 }`)+ })+ it(':scope names the transcript itself', () => {+ expect(clean(':scope[data-mode="dark"] em { color: #fff }')).toBe(`${CSS_SCOPE}[data-mode="dark"] em { color: #fff }`)+ })+ it('keeps colours, gradients, calc and transforms', () => {+ const out = clean('.x { background: linear-gradient(90deg, rgb(1 2 3), color-mix(in srgb, red, blue)); width: calc(100% - 2px); transform: rotate(1deg) }')+ expect(out).toContain('linear-gradient(90deg, rgb(1 2 3), color-mix(in srgb, red, blue))')+ expect(out).toContain('calc(100% - 2px)')+ expect(out).toContain('rotate(1deg)')+ })+ it('keeps @media and renames keyframes so they cannot replace the app\'s', () => {+ const out = clean('@media (max-width: 600px) { p { margin: 0 } } @keyframes pulse { from { opacity: 0 } to { opacity: 1 } } .x { animation: pulse 1s }')+ expect(out).toContain(`@media (max-width: 600px) { ${CSS_SCOPE} p { margin: 0 } }`)+ expect(out).toContain('@keyframes lu-pulse')+ expect(out).toContain('animation: lu-pulse 1s')+ })+ it('keeps !important', () => {+ expect(clean('p { color: red !important }')).toBe(`${CSS_SCOPE} p { color: red !important }`)+ })+})++describe('chat CSS: no network, no escape from the scope', () => {+ it.each([+ ['url', '.x { background: url(https://evil.example/t.png) }'],+ ['url quoted', '.x { background-image: url("//evil.example/t") }'],+ ['image-set', '.x { background: image-set("a.png" 1x) }'],+ ['src', '.x { background: src("a.png") }'],+ ['attr', '.x::after { content: attr(data-x) }'],+ ['expression', '.x { width: expression(alert(1)) }'],+ ['javascript', '.x { background: javascript:alert(1) }'],+ ['unknown function', '.x { color: evil(1) }'],+ ['fixed', '.x { position: fixed; inset: 0 }'],+ ['sticky', '.x { position: sticky }'],+ ['binding', '.x { -moz-binding: none }'],+ ])('drops %s', (_name, css) => {+ const out = clean(css)+ expect(out).not.toMatch(/url|image-set|src\(|attr|expression|javascript|evil|fixed|sticky|binding/i)+ })+ it.each([+ '@import url(https://evil.example/x.css);',+ '@import "x.css";',+ '@font-face { font-family: X; src: url(https://evil.example/f.woff) }',+ '@namespace svg url(http://www.w3.org/2000/svg);',+ '@layer base { p { color: red } }',+ ])('drops the at-rule %s', (css) => {+ expect(clean(css)).toBe('')+ })+ it('refuses any backslash (escapes could spell url)', () => {+ const r = sanitizeChatCss('.x { background: u\\72l(https://evil.example) }')+ expect(r.css).toBe('')+ expect(r.dropped[0]).toMatch(/Backslash/)+ })+ it('refuses "<" (no way out of the style element)', () => {+ expect(clean('</style><script>alert(1)</script>')).toBe('')+ })+ it('a comment cannot hide anything', () => {+ expect(clean('.x { background: u/**/rl(https://evil.example) }')).not.toMatch(/evil/)+ })+ it.each(['~ div', '+ p', '> p', 'html p', 'body', ':root', ':host', '& p', '.a:nth-child(2):matches(p)', ':scope ~ div p'])(+ 'refuses the selector %s',+ (sel) => expect(scopeSelector(sel)).toBeNull(),+ )+ it('a rule with one bad selector is dropped whole', () => {+ expect(clean('p, body { color: red }')).toBe('')+ })+ it('a string holding braces does not end the rule early', () => {+ const out = clean('.x::before { content: "}{ url(" } .y { color: red }')+ expect(out).not.toMatch(/url/)+ expect(out).toContain(`${CSS_SCOPE} .y { color: red }`)+ })+ it('reports what it dropped', () => {+ const r = sanitizeChatCss('.x { color: red; background: url(x) }')+ expect(r.css).toBe(`${CSS_SCOPE} .x { color: red }`)+ expect(r.dropped.join(' ')).toMatch(/background/)+ })+})++describe(':scope with a step', () => {+ it.each([':scope + p', ':scope[data-mode="dark"] ~ p', ':scope:hover~p'])('refuses %s', (sel) => expect(scopeSelector(sel)).toBeNull())+ it.each([':scope > p', ':scope[data-mode="dark"] p', ':scope .a ~ .b'])('allows %s', (sel) => expect(scopeSelector(sel)).not.toBeNull())+})diff --git a/src/lib/__tests__/chat-highlight.test.ts b/src/lib/__tests__/chat-highlight.test.tsnew file mode 100644index 00000000..28314af0--- /dev/null+++ b/src/lib/__tests__/chat-highlight.test.ts@@ -0,0 +1,53 @@+import { describe, it, expect } from 'vitest'+import { renderToStaticMarkup } from 'react-dom/server'+import ReactMarkdown from 'react-markdown'+import { createElement } from 'react'+import { highlightPlain, rehypeQuoteHighlight } from '../chat-highlight'++const html = (md: string) => renderToStaticMarkup(createElement(ReactMarkdown, { rehypePlugins: [rehypeQuoteHighlight] }, md))++describe('rehypeQuoteHighlight', () => {+ it('wraps quoted speech, marks included', () => {+ expect(html('She said "hello there" and left.')).toBe('<p>She said <span class="lu-quote">"hello there"</span> and left.</p>')+ })+ it('carries a quote across emphasis', () => {+ const out = html('"Hello *there*, friend" she waves.')+ expect(out).toContain('<span class="lu-quote">"Hello </span><em><span class="lu-quote">there</span></em><span class="lu-quote">, friend"</span>')+ })+ it('curly, low-high and guillemet quotes', () => {+ expect(html('“Hi”')).toContain('<span class="lu-quote">“Hi”</span>')+ expect(html('„Hallo“')).toContain('<span class="lu-quote">„Hallo“</span>')+ expect(html('«Salut»')).toContain('<span class="lu-quote">«Salut»</span>')+ expect(html('»Na?«')).toContain('<span class="lu-quote">»Na?«</span>')+ })+ it('an odd straight quote colours nothing (5\'10")', () => {+ expect(html('He is 5\'10" tall and calm.')).not.toContain('lu-quote')+ })+ it('a new paragraph starts outside a quote', () => {+ const out = html('"open\n\nnext paragraph')+ expect(out).toContain('<p>next paragraph</p>')+ })+ it('leaves code and links alone', () => {+ expect(html('`a "b" c`')).not.toContain('lu-quote')+ expect(html('```\nx = "y"\n```')).not.toContain('lu-quote')+ expect(html('[a "b" c](https://example.com)')).not.toContain('lu-quote')+ })+})++describe('highlightPlain (user messages)', () => {+ it('splits quotes and actions', () => {+ expect(highlightPlain('*waves* "hi" ok', true, true)).toEqual([+ { kind: 'action', text: '*waves*' },+ { kind: 'text', text: ' ' },+ { kind: 'quote', text: '"hi"' },+ { kind: 'text', text: ' ok' },+ ])+ })+ it('does nothing when switched off', () => {+ expect(highlightPlain('*a* "b"', false, false)).toEqual([{ kind: 'text', text: '*a* "b"' }])+ })+ it('keeps the text whole', () => {+ const t = 'a "b" *c* „d“ e'+ expect(highlightPlain(t, true, true).map((p) => p.text).join('')).toBe(t)+ })+})diff --git a/src/lib/__tests__/chat-look.test.ts b/src/lib/__tests__/chat-look.test.tsnew file mode 100644index 00000000..782663d1--- /dev/null+++ b/src/lib/__tests__/chat-look.test.ts@@ -0,0 +1,129 @@+import { describe, it, expect } from 'vitest'+import {+ DEFAULT_LOOK, LOOK_PRESETS, MIN_CONTRAST, PANE, clampZoom, cleanFontName, contrast, keyZoom, lookVars,+ normalizeBackground, normalizeLook, parseHex, pickBackground, readableOn, scenePrompt, wheelZoom, widthFactor,+} from '../chat-look'++const ref = 'lu-attachment:v1:' + 'a'.repeat(64)++describe('readableOn: a picked colour never makes a chat unreadable', () => {+ it('keeps a colour that already reads', () => {+ expect(readableOn('#111111', PANE.light)).toBe('#111111')+ })+ it.each([+ ['#ffff00', 'light'], ['#ffffff', 'light'], ['#a5b4fc', 'light'],+ ['#000000', 'dark'], ['#1e3a8a', 'dark'], ['#333333', 'dark'],+ ] as const)('moves %s until it reads on the %s pane', (hex, mode) => {+ const out = readableOn(hex, PANE[mode])!+ expect(contrast(parseHex(out)!, parseHex(PANE[mode])!)).toBeGreaterThanOrEqual(MIN_CONTRAST)+ })+ it('keeps the hue: a yellow becomes a darker yellow, not grey', () => {+ const out = parseHex(readableOn('#ffff00', PANE.light))!+ expect(out.r).toBeGreaterThan(out.b + 40)+ expect(out.g).toBeGreaterThan(out.b + 40)+ })+ it('refuses what is not a colour', () => {+ expect(readableOn('red; background:url(x)', PANE.light)).toBeNull()+ expect(readableOn(null, PANE.light)).toBeNull()+ })+})++describe('lookVars', () => {+ it('emits nothing for the default look, so the chat looks as before', () => {+ const vars = lookVars(DEFAULT_LOOK, 'dark')+ expect(Object.keys(vars).filter((k) => k !== '--lu-look-leading')).toEqual([])+ })+ it('every preset reads in both modes', () => {+ for (const p of LOOK_PRESETS) {+ const look = normalizeLook({ ...DEFAULT_LOOK, ...p.look })+ for (const mode of ['light', 'dark'] as const) {+ const vars = lookVars(look, mode)+ const surfaces = [PANE[mode], vars['--lu-look-user-bubble'], vars['--lu-look-model-bubble']].filter(Boolean) as string[]+ for (const name of ['--lu-look-quote', '--lu-look-action']) {+ if (!vars[name]) continue+ for (const s of surfaces) {+ expect(contrast(parseHex(vars[name])!, parseHex(s)!), `${p.id} ${mode} ${name} on ${s}`).toBeGreaterThanOrEqual(MIN_CONTRAST)+ }+ }+ if (vars['--lu-look-model-text']) {+ expect(contrast(parseHex(vars['--lu-look-model-text'])!, parseHex(vars['--lu-look-model-bubble'] ?? PANE[mode])!)).toBeGreaterThanOrEqual(MIN_CONTRAST)+ }+ }+ }+ })+ it('quotes and actions get a colour only when switched on', () => {+ expect(lookVars({ ...DEFAULT_LOOK, quoteText: '#ff0000' }, 'light')['--lu-look-quote']).toBeUndefined()+ expect(lookVars({ ...DEFAULT_LOOK, highlightQuotes: true }, 'light')['--lu-look-quote']).toBeDefined()+ })+})++describe('fonts', () => {+ it('cuts a typed font name to what a family name can hold', () => {+ expect(cleanFontName(`Georgia'; } body { x: url(evil)`)).toBe('Georgia body x urlevil')+ expect(cleanFontName('Noto Serif JP')).toBe('Noto Serif JP')+ })+})++describe('normalizeLook', () => {+ it('drops broken and foreign fields from an imported look', () => {+ const look = normalizeLook({ modelText: 'javascript:alert(1)', font: 'comic', width: 'huge', lineHeight: 99, evil: 1, userBubble: '#ABC' })+ expect(look.modelText).toBeNull()+ expect(look.font).toBe('app')+ expect(look.width).toBe('normal')+ expect(look.lineHeight).toBe(2.2)+ expect(look.userBubble).toBe('#aabbcc')+ expect('evil' in look).toBe(false)+ })+ it('width factors', () => {+ expect(widthFactor('normal')).toBe(1)+ expect(widthFactor('wide')).toBeGreaterThan(1)+ expect(widthFactor('full')).toBeNull()+ })+})++describe('zoom (C42)', () => {+ it('one mouse notch is one step, like a browser', () => {+ expect(wheelZoom(1, -100)).toBe(1.1)+ expect(wheelZoom(1, 100)).toBe(0.9)+ expect(wheelZoom(1, -3, 1)).toBe(1.1)+ })+ it('a trackpad pinch zooms smoothly', () => {+ const z = wheelZoom(1, -4)+ expect(z).toBeGreaterThan(1)+ expect(z).toBeLessThan(1.1)+ })+ it('stays within bounds', () => {+ expect(wheelZoom(2, -100)).toBe(2)+ expect(wheelZoom(0.7, 100)).toBe(0.7)+ expect(clampZoom(Number.NaN)).toBe(1)+ })+ it('keys', () => {+ expect(keyZoom(1, '=')).toBe(1.1)+ expect(keyZoom(1, '+')).toBe(1.1)+ expect(keyZoom(1.3, '-')).toBe(1.2)+ expect(keyZoom(1.7, '0')).toBe(1)+ expect(keyZoom(1, 'a')).toBeNull()+ })+})++describe('backgrounds', () => {+ it('the chat picture wins over the persona picture', () => {+ const bgs = { 'chat:c1': { ref, scrim: 0.7, blur: 0 }, 'persona:p1': { ref, scrim: 0.6, blur: 2 } }+ expect(pickBackground(bgs, 'c1', 'p1')?.key).toBe('chat:c1')+ expect(pickBackground(bgs, 'c2', 'p1')?.key).toBe('persona:p1')+ expect(pickBackground(bgs, 'c2', undefined)).toBeNull()+ })+ it('accepts only attachment references and keeps the scrim floor', () => {+ expect(normalizeBackground({ ref: 'https://evil.example/x.png' })).toBeNull()+ expect(normalizeBackground({ ref: 'data:image/png;base64,AAAA' })).toBeNull()+ expect(normalizeBackground({ ref, scrim: 0 })!.scrim).toBeGreaterThanOrEqual(0.5)+ expect(normalizeBackground({ ref, blur: 99 })!.blur).toBe(16)+ })+ it('the scene prompt keeps narration and drops speech and markup', () => {+ const p = scenePrompt(['old', '*She leans on the rail.* "Look at that!" The harbour glows under a red sky. ((OOC: brb))'])+ expect(p).toContain('The harbour glows under a red sky.')+ expect(p).not.toContain('Look at that')+ expect(p).not.toContain('OOC')+ expect(p).not.toContain('*')+ })+})diff --git a/src/lib/chat-attachments.ts b/src/lib/chat-attachments.tsindex 38f55820..c1fb34c5 100644--- a/src/lib/chat-attachments.ts+++ b/src/lib/chat-attachments.ts@@ -55,6 +55,11 @@ async function read(data: string): Promise<string> {})}+/** The data URL behind a stored reference (chat backgrounds, 3.1.0). */+export function readAttachment(ref: string): Promise<string> {+ return read(ref)+}+/** The reference an inline image object already got. Keyed by the object, so* a state snapshot taken before the swap does not hash and write the same* megabytes a second time. */diff --git a/src/lib/chat-background.ts b/src/lib/chat-background.tsnew file mode 100644index 00000000..a16ad09f--- /dev/null+++ b/src/lib/chat-background.ts@@ -0,0 +1,93 @@+/**+ * Background pictures for a chat or a persona (3.1.0, C58).+ *+ * A picture comes from three places, all on a click of the user and never on+ * their own: a file from disk, a render from the Create gallery (local or LU+ * Cloud, fetched through the gallery's own path), or a new render of the+ * current scene through the image path the chat tools use (ComfyUI on+ * Windows and Linux, MLX on a Mac). In the cloud mode a new render goes+ * through Create, where the price is shown before anything runs; this module+ * does not spend credits.+ *+ * Every picture is scaled down to at most BG_EDGE on its long side and saved+ * as JPEG into the attachment store, so the store keeps a short reference+ * and the file is a few hundred kB, not the 10 MB a render can be.+ */+import { storeAttachment } from './chat-attachments'++export const BG_EDGE = 1920+const MAX_INPUT_BYTES = 40 * 1024 * 1024++/** Scale a picture down and encode it as a JPEG data URL. */+export async function pictureToDataUrl(blob: Blob, edge = BG_EDGE): Promise<string> {+ if (!blob.type.startsWith('image/') && blob.type !== '') throw new Error('This file is not a picture.')+ if (blob.size > MAX_INPUT_BYTES) throw new Error('This picture is larger than 40 MB.')+ const bitmap = await createImageBitmap(blob).catch(() => {+ throw new Error('This picture could not be read.')+ })+ try {+ const scale = Math.min(1, edge / Math.max(bitmap.width, bitmap.height))+ const w = Math.max(1, Math.round(bitmap.width * scale))+ const h = Math.max(1, Math.round(bitmap.height * scale))+ const canvas = document.createElement('canvas')+ canvas.width = w+ canvas.height = h+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('This picture could not be drawn.')+ ctx.drawImage(bitmap, 0, 0, w, h)+ return canvas.toDataURL('image/jpeg', 0.86)+ } finally {+ bitmap.close()+ }+}++/** Save a picture as a background and return its reference. */+export async function storeBackground(blob: Blob): Promise<string> {+ const data = await pictureToDataUrl(blob)+ const stored = await storeAttachment({ data })+ return stored.data+}++/** The address of the picture in an image_generate result+ * (`Image generated: <file> (prompt: "...")\n<url>`), or null. */+export function resultUrl(result: string): string | null {+ const lines = result.split('\n').map((l) => l.trim()).filter(Boolean)+ for (let i = lines.length - 1; i >= 0; i--) {+ const m = /^(https?:\/\/\S+|blob:\S+|data:image\/\S+)$/.exec(lines[i])+ if (m) return m[1]+ }+ return null+}++/** Whether the tool said it made a picture. Its refusals and failures are+ * sentences ("Error: ...", "Cannot generate: ...", "... cancelled."). */+export function generatedOk(result: string): boolean {+ return /^Image generated:/i.test(result.trim()) && resultUrl(result) !== null+}++/**+ * A new background from `prompt`, rendered locally through the chat's own+ * image path, owned by `conversationId` so Stop ends exactly this render.+ */+export async function renderSceneBackground(prompt: string, conversationId: string): Promise<string> {+ const { generateMediaForRemote } = await import('../api/mcp/builtin-tools')+ const result = await generateMediaForRemote('image', { prompt, aspectRatio: '16:9' }, conversationId)+ if (!generatedOk(result)) throw new Error(result.trim().split('\n')[0] || 'The picture was not made.')+ const url = resultUrl(result)!+ const { fetchComfyImageBase64 } = await import('../api/comfyui')+ const b64 = await fetchComfyImageBase64(url)+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))+ return storeBackground(new Blob([bytes], { type: 'image/png' }))+}++/** Stop a render started by renderSceneBackground. */+export async function cancelSceneBackground(conversationId: string): Promise<void> {+ const { isMlxImageHost } = await import('../api/mlx-image')+ if (isMlxImageHost()) {+ const { cancelMlxGenerate } = await import('../api/mlx-image')+ await cancelMlxGenerate().catch(() => null)+ return+ }+ const { requestGenerationCancel } = await import('../api/vram-handoff')+ requestGenerationCancel(conversationId)+}diff --git a/src/lib/chat-css-sanitize.ts b/src/lib/chat-css-sanitize.tsnew file mode 100644index 00000000..fe01a674--- /dev/null+++ b/src/lib/chat-css-sanitize.ts@@ -0,0 +1,272 @@+/**+ * Custom CSS for the chat (3.1.0, C58), made safe.+ *+ * SillyTavern pastes custom CSS into the page as typed. A shared theme can+ * therefore load fonts and pictures from any server (a tracking beacon on+ * every chat open), cover the whole window with a fake dialog, or restyle the+ * settings. LU never passes the user's text through. It is parsed here into+ * rules and declarations, every part is checked against an allow list, and a+ * NEW stylesheet is written from what passed:+ *+ * - Every selector is put under the transcript's scope (`.lu-chat-custom`),+ * so nothing outside the chat can be matched. A selector may not start+ * with a combinator (`~ div` would reach siblings of the scope) and may not+ * name :root, html, body, :host or the nesting `&`.+ * - No url(), image-set(), src(), element(), attr(), expression(), no+ * @import, @font-face, @namespace, @charset, @layer, @property, @container+ * or anything else that is not @media, @supports or @keyframes. Function+ * calls in values must be on the allow list (colours, gradients, calc,+ * transforms, filters): a function the list does not know drops the+ * declaration, it is never guessed at.+ * - No backslash anywhere (CSS escapes could spell `url(` without the+ * letters), no `<` (no way out of a <style> element), no `javascript:`.+ * - `position: fixed` and `sticky` are refused: the scope does not contain+ * them, and a fixed box could cover the rest of the app.+ * - At most MAX_CSS characters in, MAX_RULES rules out.+ *+ * The result lists what was dropped, so the editor can tell the user why a+ * line has no effect instead of failing in silence.+ */++import { MAX_CSS } from './chat-look'++export const CSS_SCOPE = '.lu-chat-custom'+const MAX_RULES = 400++/** Value functions that cannot reach the network or the page. */+const ALLOWED_FUNCTIONS = new Set([+ 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'light-dark',+ 'var', 'calc', 'min', 'max', 'clamp', 'round', 'mod', 'rem', 'abs', 'sign',+ 'linear-gradient', 'radial-gradient', 'conic-gradient',+ 'repeating-linear-gradient', 'repeating-radial-gradient', 'repeating-conic-gradient',+ 'translate', 'translatex', 'translatey', 'translate3d', 'rotate', 'rotatex', 'rotatey', 'rotatez', 'rotate3d',+ 'scale', 'scalex', 'scaley', 'scale3d', 'skew', 'skewx', 'skewy', 'matrix', 'matrix3d', 'perspective',+ 'cubic-bezier', 'steps', 'linear',+ 'blur', 'brightness', 'contrast', 'drop-shadow', 'grayscale', 'hue-rotate', 'invert', 'opacity', 'saturate', 'sepia',+ 'minmax', 'repeat', 'fit-content', 'counter', 'counters',+])++/** Pseudo-class functions a selector may use. */+const SELECTOR_FUNCTIONS = new Set(['is', 'where', 'not', 'has', 'nth-child', 'nth-last-child', 'nth-of-type', 'nth-last-of-type', 'lang', 'dir'])++const BANNED_SELECTOR = /(^|[^a-z0-9_-])(html|body)(?![a-z0-9_-])|:root|:host|&/i++const ALLOWED_AT = new Set(['media', 'supports', 'keyframes', '-webkit-keyframes'])++export interface SanitizedCss {+ css: string+ dropped: string[]+}++/** Strip /* comments *\/ (a comment can hide nothing then). */+function stripComments(s: string): string {+ return s.replace(/\/\*[\s\S]*?(\*\/|$)/g, ' ')+}++interface Block { prelude: string; body: string }++/**+ * Split text into top-level `prelude { body }` blocks, honouring strings and+ * nested braces. Text outside any block (a stray declaration, `@import x;`)+ * is reported as dropped.+ */+function blocks(text: string, dropped: string[]): Block[] {+ const out: Block[] = []+ let i = 0+ let start = 0+ while (i < text.length) {+ const ch = text[i]+ if (ch === '"' || ch === "'") { i = skipString(text, i); continue }+ if (ch === ';') {+ const stray = text.slice(start, i).trim()+ if (stray) dropped.push(short(stray))+ start = i + 1+ i+++ continue+ }+ if (ch === '{') {+ const prelude = text.slice(start, i).trim()+ let depth = 1+ let j = i + 1+ while (j < text.length && depth > 0) {+ const c = text[j]+ if (c === '"' || c === "'") { j = skipString(text, j); continue }+ if (c === '{') depth+++ else if (c === '}') depth--+ j+++ }+ out.push({ prelude, body: text.slice(i + 1, depth === 0 ? j - 1 : j) })+ i = j+ start = j+ continue+ }+ if (ch === '}') {+ // An unmatched closing brace: skip it.+ start = i + 1+ }+ i+++ }+ const rest = text.slice(start).trim()+ if (rest) dropped.push(short(rest))+ return out+}++function skipString(s: string, at: number): number {+ const q = s[at]+ let j = at + 1+ while (j < s.length && s[j] !== q && s[j] !== '\n') j+++ return j + 1+}++/** Split on `sep` at depth 0, outside strings, parentheses and brackets. */+function splitTop(s: string, sep: string): string[] {+ const parts: string[] = []+ let depth = 0+ let last = 0+ for (let i = 0; i < s.length; i++) {+ const c = s[i]+ if (c === '"' || c === "'") { i = skipString(s, i) - 1; continue }+ if (c === '(' || c === '[') depth+++ else if (c === ')' || c === ']') depth = Math.max(0, depth - 1)+ else if (c === sep && depth === 0) { parts.push(s.slice(last, i)); last = i + 1 }+ }+ parts.push(s.slice(last))+ return parts+}++function short(s: string): string {+ const one = s.replace(/\s+/g, ' ').trim()+ return one.length > 60 ? one.slice(0, 57) + '...' : one+}++/** A selector put under the scope, or null when it may not be used. */+export function scopeSelector(sel: string): string | null {+ const s = sel.trim()+ if (!s) return null+ if (/^[>+~]/.test(s)) return null+ if (BANNED_SELECTOR.test(s)) return null+ if (/[{};@]/.test(s)) return null+ for (const m of s.matchAll(/:{1,2}([a-z-]+)\(/gi)) {+ if (!SELECTOR_FUNCTIONS.has(m[1].toLowerCase())) return null+ }+ // `:scope` names the transcript itself.+ if (/^:scope\b/i.test(s)) {+ const rest = s.slice(':scope'.length)+ // The scope's own compound (`[data-mode="dark"]`, `:hover`) may follow,+ // then only a descendant or child step: `~` and `+` would match the+ // scope's siblings, which are outside the transcript.+ if (/[~+]/.test(rest.slice(compoundEnd(rest)).trimStart().charAt(0))) return null+ if (/:scope\b/i.test(rest)) return null+ return CSS_SCOPE + rest+ }+ if (/:scope\b/i.test(s)) return null+ return `${CSS_SCOPE} ${s}`+}++/** Where the first compound selector of `s` ends: the first space or+ * combinator outside brackets, parentheses and strings. */+function compoundEnd(s: string): number {+ let depth = 0+ for (let i = 0; i < s.length; i++) {+ const c = s[i]+ if (c === '"' || c === "'") { i = skipString(s, i) - 1; continue }+ if (c === '(' || c === '[') depth+++ else if (c === ')' || c === ']') depth = Math.max(0, depth - 1)+ else if (depth === 0 && /[\s>+~]/.test(c)) return i+ }+ return s.length+}++/** One declaration, cleaned, or null when it may not be used. */+export function cleanDeclaration(decl: string): string | null {+ const colon = decl.indexOf(':')+ if (colon < 0) return null+ const prop = decl.slice(0, colon).trim().toLowerCase()+ let value = decl.slice(colon + 1).trim()+ if (!/^(--[a-z0-9_-]+|-?[a-z][a-z0-9-]*)$/.test(prop)) return null+ if (!value) return null+ let important = ''+ const imp = /!\s*important\s*$/i.exec(value)+ if (imp) { important = ' !important'; value = value.slice(0, imp.index).trim() }+ if (value.includes('!')) return null+ if (/[{};<@]/.test(value)) return null+ if (/javascript:|expression|behavior|binding/i.test(value)) return null+ if (prop === 'behavior' || prop.endsWith('-binding')) return null+ if (prop === 'position' && /\b(fixed|sticky)\b/i.test(value)) return null+ for (const m of value.matchAll(/([a-z-]+)\s*\(/gi)) {+ if (!ALLOWED_FUNCTIONS.has(m[1].toLowerCase())) return null+ }+ // A bare `(` without a name before it (e.g. `( url`) is not a function we know.+ const named = [...value.matchAll(/[a-z-]+\s*\(/gi)].length+ const opens = (value.match(/\(/g) ?? []).length+ if (opens !== named) return null+ return `${prop}: ${value}${important}`+}++function declarations(body: string, dropped: string[]): string[] {+ const out: string[] = []+ for (const raw of splitTop(body, ';')) {+ const d = raw.trim()+ if (!d) continue+ const ok = cleanDeclaration(d)+ if (ok) out.push(ok)+ else dropped.push(short(d))+ }+ return out+}++function styleRules(text: string, dropped: string[], count: { n: number }, depth: number): string[] {+ const out: string[] = []+ for (const b of blocks(text, dropped)) {+ if (count.n >= MAX_RULES) { dropped.push('(too many rules)'); break }+ if (b.prelude.startsWith('@')) {+ const name = /^@([a-z-]+)/i.exec(b.prelude)?.[1].toLowerCase() ?? ''+ if (!ALLOWED_AT.has(name) || depth > 1) { dropped.push(short(b.prelude)); continue }+ const cond = b.prelude.slice(name.length + 1).trim()+ if (/[{};<\\]|url\s*\(/i.test(cond)) { dropped.push(short(b.prelude)); continue }+ if (name.endsWith('keyframes')) {+ if (!/^[a-z_][a-z0-9_-]*$/i.test(cond)) { dropped.push(short(b.prelude)); continue }+ const frames: string[] = []+ for (const f of blocks(b.body, dropped)) {+ if (!/^(from|to|\d{1,3}(\.\d+)?%)(\s*,\s*(from|to|\d{1,3}(\.\d+)?%))*$/i.test(f.prelude)) { dropped.push(short(f.prelude)); continue }+ frames.push(`${f.prelude} { ${declarations(f.body, dropped).join('; ')} }`)+ }+ count.n+++ out.push(`@${name} lu-${cond} { ${frames.join(' ')} }`)+ continue+ }+ const inner = styleRules(b.body, dropped, count, depth + 1)+ if (inner.length) out.push(`@${name} ${cond} { ${inner.join(' ')} }`)+ continue+ }+ const selectors = splitTop(b.prelude, ',').map(scopeSelector)+ if (selectors.some((s) => s === null)) { dropped.push(short(b.prelude)); continue }+ const decls = declarations(b.body, dropped)+ if (!decls.length) continue+ count.n+++ out.push(`${selectors.join(', ')} { ${decls.join('; ')} }`)+ }+ return out+}++/**+ * The user's CSS, rebuilt from what passed. Animation names get the prefix+ * `lu-` both where they are declared and where they are used, so a user+ * keyframe never replaces one of the app's.+ */+export function sanitizeChatCss(input: string): SanitizedCss {+ const dropped: string[] = []+ if (typeof input !== 'string' || !input.trim()) return { css: '', dropped }+ let text = input.slice(0, MAX_CSS)+ if (input.length > MAX_CSS) dropped.push(`(cut at ${MAX_CSS} characters)`)+ text = stripComments(text)+ // Refused outright: escapes, markup, and anything that names a URL loader.+ if (/\\/.test(text)) return { css: '', dropped: ['Backslashes are not allowed in chat CSS.'] }+ if (/</.test(text)) return { css: '', dropped: ['"<" is not allowed in chat CSS.'] }+ const rules = styleRules(text, dropped, { n: 0 }, 0)+ const css = rules.join('\n').replace(+ /(animation(?:-name)?\s*:\s*)([a-z_][a-z0-9_-]*)/gi,+ (m, head: string, name: string) => (/^(none|initial|inherit|unset|revert|lu-.*)$/i.test(name) ? m : `${head}lu-${name}`),+ )+ return { css, dropped }+}diff --git a/src/lib/chat-highlight.ts b/src/lib/chat-highlight.tsnew file mode 100644index 00000000..e36f71ee--- /dev/null+++ b/src/lib/chat-highlight.ts@@ -0,0 +1,145 @@+/**+ * "Quoted speech" in its own colour (3.1.0, C58), the way roleplay readers+ * know it from SillyTavern, done on the rendered tree instead of the raw text.+ *+ * Why on the tree: a quote often runs across markdown, `"Hello *there*"`.+ * A regex over the source either breaks the emphasis or misses the quote. The+ * plugin walks each block (paragraph, list item, heading, cell) once, carries+ * "inside a quote" across its inline children, and wraps the text runs that+ * are inside in `<span class="lu-quote">`. Code, links and math are left as+ * they are. A block with an odd number of straight double quotes (5'10",+ * a stray mark) gets no straight-quote highlighting at all, so one stray+ * mark cannot colour the rest of a paragraph; curly and guillemet pairs are+ * unambiguous and still count.+ *+ * Actions (`*waves*`) need nothing here: markdown already makes them <em>,+ * and the stylesheet colours em inside the transcript (index.css, .lu-look).+ * User messages are plain text, not markdown; `highlightPlain` below gives+ * them the same two colours without rendering their text as markdown.+ */+import type { Element, ElementContent, Root, RootContent, Text } from 'hast'++const SKIP = new Set(['code', 'pre', 'a', 'button', 'svg', 'math', 'kbd', 'script', 'style'])+const BLOCKS = new Set(['p', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'th', 'dd', 'dt', 'figcaption'])++const OPEN: Record<string, string> = { '“': '”', '„': '“', '«': '»', '»': '«', '"': '"' }++interface QuoteState { close: string | null; straight: boolean }++/** KaTeX output and anything else marked as math stays untouched. */+function skipped(el: Element): boolean {+ if (SKIP.has(el.tagName)) return true+ const cls = el.properties?.className+ const list = Array.isArray(cls) ? cls.map(String) : typeof cls === 'string' ? cls.split(/\s+/) : []+ return list.some((c) => c.startsWith('katex') || c === 'math' || c.startsWith('math-'))+}++function textOf(node: Element | Root): string {+ let s = ''+ for (const c of node.children) {+ if (c.type === 'text') s += c.value+ else if (c.type === 'element' && !skipped(c)) s += textOf(c)+ }+ return s+}++function quoteSpan(value: string): Element {+ return { type: 'element', tagName: 'span', properties: { className: ['lu-quote'] }, children: [{ type: 'text', value }] }+}++/** Split one text node by the quote state, advancing the state. */+function splitText(node: Text, state: QuoteState): ElementContent[] {+ const out: ElementContent[] = []+ const v = node.value+ let buf = ''+ let inQuote = state.close !== null+ const flush = () => {+ if (!buf) return+ out.push(inQuote ? quoteSpan(buf) : { type: 'text', value: buf })+ buf = ''+ }+ for (const ch of v) {+ if (state.close === null) {+ const close = OPEN[ch]+ if (close !== undefined && (ch !== '"' || state.straight)) {+ flush()+ state.close = close+ inQuote = true+ buf = ch+ continue+ }+ buf += ch+ } else {+ buf += ch+ if (ch === state.close) {+ flush()+ state.close = null+ inQuote = false+ }+ }+ }+ flush()+ return out+}++function walkInline(children: ElementContent[], state: QuoteState): ElementContent[] {+ const out: ElementContent[] = []+ for (const c of children) {+ if (c.type === 'text') out.push(...splitText(c, state))+ else if (c.type === 'element' && !skipped(c) && !BLOCKS.has(c.tagName)) {+ out.push({ ...c, children: walkInline(c.children, state) })+ } else if (c.type === 'element' && !skipped(c) && BLOCKS.has(c.tagName)) {+ out.push(walkBlock(c))+ } else out.push(c)+ }+ return out+}++function walkBlock(el: Element): Element {+ const straightCount = (textOf(el).match(/"/g) ?? []).length+ const state: QuoteState = { close: null, straight: straightCount % 2 === 0 }+ return { ...el, children: walkInline(el.children, state) }+}++function walk<T extends Root | Element>(node: T): T {+ const children = node.children.map((c: RootContent | ElementContent) => {+ if (c.type !== 'element' || skipped(c)) return c+ if (BLOCKS.has(c.tagName)) return walkBlock(c)+ return walk(c)+ })+ return { ...node, children } as T+}++/** rehype plugin: wraps quoted speech in `span.lu-quote`. */+export function rehypeQuoteHighlight() {+ return (tree: Root) => walk(tree)+}++export type PlainPiece = { kind: 'text' | 'quote' | 'action'; text: string }++/**+ * The same two colours for plain text (a user's message): quotes as above,+ * and `*action*` on one line. The asterisks stay visible, since the message+ * is shown exactly as typed.+ */+export function highlightPlain(text: string, quotes: boolean, actions: boolean): PlainPiece[] {+ if (!quotes && !actions) return [{ kind: 'text', text }]+ const parts: string[] = []+ if (quotes) {+ const straight = ((text.match(/"/g) ?? []).length % 2) === 0+ parts.push('“[^”\\n]*”', '„[^“”\\n]*[“”]', '«[^»\\n]*»')+ if (straight) parts.push('"[^"\\n]*"')+ }+ if (actions) parts.push('\\*[^*\\n]+\\*')+ const re = new RegExp(parts.join('|'), 'g')+ const out: PlainPiece[] = []+ let last = 0+ for (const m of text.matchAll(re)) {+ const at = m.index ?? 0+ if (at > last) out.push({ kind: 'text', text: text.slice(last, at) })+ out.push({ kind: m[0].startsWith('*') ? 'action' : 'quote', text: m[0] })+ last = at + m[0].length+ }+ if (last < text.length) out.push({ kind: 'text', text: text.slice(last) })+ return out+}diff --git a/src/lib/chat-look.ts b/src/lib/chat-look.tsnew file mode 100644index 00000000..7b52c866--- /dev/null+++ b/src/lib/chat-look.ts@@ -0,0 +1,393 @@+/**+ * Chat look (3.1.0, C58 / C42): how the transcript reads.+ *+ * Who asked: micnorian14 (GitHub Discussion #14) wants enough say over the+ * chat's look to move over from SillyTavern; boromirofgeo wants Ctrl/Cmd ++ * wheel to zoom the chat text like a browser does.+ *+ * What SillyTavern offers (docs, "UI Theme"): free colours for main, italics,+ * underlined and quoted text, user and AI message, chat width 25-100 %, a font+ * scale of 0.5-1.5, a chat style (flat, bubbles, document), a background per+ * chat and unrestricted custom CSS. Two things go wrong there all the time:+ * a colour picked in a dark theme is unreadable in a light one, and custom+ * CSS from a shared theme can load anything from anywhere.+ *+ * LU does it this way:+ * - Every colour is guarded: the colour shown is moved in lightness until it+ * reaches 4.5:1 (WCAG AA) against the surface it is read on, separately in+ * light and in dark mode. A colour can therefore never make a chat+ * unreadable, and one look works in both modes.+ * - Quoted speech and *actions* get their own colours (opt in).+ * - The background picture lies under a scrim of the pane colour, so text+ * keeps its contrast; the scrim strength is a slider with a floor.+ * - Custom CSS goes through lib/chat-css-sanitize.ts: scoped to the+ * transcript, no url(), no @import, no fonts or pictures from anywhere.+ * - The zoom lives here as a number and is applied to the transcript only.+ *+ * Everything here is pure and tested (__tests__/chat-look.test.ts); the store+ * is stores/chatLookStore.ts, the surface components/chat/ChatLookScope.tsx.+ */++export type ChatFont = 'app' | 'serif' | 'sans' | 'mono' | 'custom'+export type ChatWidth = 'normal' | 'wide' | 'full'+export type ChatLayout = 'default' | 'bubbles' | 'document'++export interface ChatLook {+ /** Text colour of the model's replies; null keeps the app's colour. */+ modelText: string | null+ /** Text colour of the user's messages. */+ userText: string | null+ /** Tint of the user's bubble (and the model's in the bubbles layout). */+ userBubble: string | null+ modelBubble: string | null+ /** Colour for "quoted speech". */+ quoteText: string | null+ /** Colour for *actions* (markdown emphasis). */+ actionText: string | null+ highlightQuotes: boolean+ highlightActions: boolean+ font: ChatFont+ /** A font installed on this computer, by name. Only used with font 'custom'. */+ customFont: string+ width: ChatWidth+ layout: ChatLayout+ /** Line height of the message text. */+ lineHeight: number+ customCss: string+ customCssOn: boolean+}++export const DEFAULT_LOOK: ChatLook = {+ modelText: null,+ userText: null,+ userBubble: null,+ modelBubble: null,+ quoteText: null,+ actionText: null,+ highlightQuotes: false,+ highlightActions: false,+ font: 'app',+ customFont: '',+ width: 'normal',+ layout: 'default',+ lineHeight: 1.625,+ customCss: '',+ customCssOn: false,+}++/** The colours the guard is computed against: the pane a message is read on+ * (index.css: #ffffff light, #1e1e1e dark). */+export const PANE = { light: '#ffffff', dark: '#1e1e1e' } as const+/** WCAG AA for body text. */+export const MIN_CONTRAST = 4.5++// ── Colour maths ─────────────────────────────────────────────────────────++export interface Rgb { r: number; g: number; b: number }++/** `#rgb` or `#rrggbb`, case-insensitive; anything else is null. */+export function parseHex(hex: string | null | undefined): Rgb | null {+ if (typeof hex !== 'string') return null+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim())+ if (!m) return null+ let h = m[1]+ if (h.length === 3) h = h.split('').map((c) => c + c).join('')+ return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16) }+}++export function toHex({ r, g, b }: Rgb): string {+ const c = (n: number) => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, '0')+ return `#${c(r)}${c(g)}${c(b)}`+}++function channel(v: number): number {+ const s = v / 255+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4+}++export function luminance(c: Rgb): number {+ return 0.2126 * channel(c.r) + 0.7152 * channel(c.g) + 0.0722 * channel(c.b)+}++export function contrast(a: Rgb, b: Rgb): number {+ const la = luminance(a)+ const lb = luminance(b)+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)+}++function rgbToHsl({ r, g, b }: Rgb): [number, number, number] {+ const rn = r / 255, gn = g / 255, bn = b / 255+ const max = Math.max(rn, gn, bn), min = Math.min(rn, gn, bn)+ const l = (max + min) / 2+ if (max === min) return [0, 0, l]+ const d = max - min+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)+ let h: number+ if (max === rn) h = (gn - bn) / d + (gn < bn ? 6 : 0)+ else if (max === gn) h = (bn - rn) / d + 2+ else h = (rn - gn) / d + 4+ return [h / 6, s, l]+}++function hslToRgb(h: number, s: number, l: number): Rgb {+ if (s === 0) return { r: l * 255, g: l * 255, b: l * 255 }+ const hue = (p: number, q: number, t: number) => {+ if (t < 0) t += 1+ if (t > 1) t -= 1+ if (t < 1 / 6) return p + (q - p) * 6 * t+ if (t < 1 / 2) return q+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6+ return p+ }+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s+ const p = 2 * l - q+ return { r: hue(p, q, h + 1 / 3) * 255, g: hue(p, q, h) * 255, b: hue(p, q, h - 1 / 3) * 255 }+}++/**+ * The colour as close to `hex` as possible that still reads at `min` against+ * `surface`: the hue and saturation stay, the lightness moves away from the+ * surface (darker on a light pane, lighter on a dark one) in small steps.+ * An unparsable colour returns null, so the caller keeps the app's own.+ */+export function readableOn(hex: string | null | undefined, surface: string, min = MIN_CONTRAST): string | null {+ const c = parseHex(hex)+ const bg = parseHex(surface)+ if (!c || !bg) return null+ if (contrast(c, bg) >= min) return toHex(c)+ const [h, s, l0] = rgbToHsl(c)+ const darker = luminance(bg) > 0.18+ for (let i = 1; i <= 100; i++) {+ const l = darker ? l0 - (l0 * i) / 100 : l0 + ((1 - l0) * i) / 100+ const next = hslToRgb(h, s, l)+ if (contrast(next, bg) >= min) return toHex(next)+ }+ return darker ? '#000000' : '#ffffff'+}++/**+ * A bubble tint as a surface: the chosen colour laid over the pane at+ * `alpha`, so a saturated pick reads as a soft tint and stays a surface text+ * can sit on. Returns the mixed opaque colour (what the eye sees).+ */+export function tintOver(hex: string | null | undefined, pane: string, alpha = 0.16): string | null {+ const c = parseHex(hex)+ const p = parseHex(pane)+ if (!c || !p) return null+ const mix = (a: number, b: number) => a * alpha + b * (1 - alpha)+ return toHex({ r: mix(c.r, p.r), g: mix(c.g, p.g), b: mix(c.b, p.b) })+}++// ── What the transcript gets ─────────────────────────────────────────────++export type Mode = 'light' | 'dark'++const FONT_STACKS: Record<Exclude<ChatFont, 'app' | 'custom'>, string> = {+ serif: `'Iowan Old Style', 'Palatino Linotype', Palatino, Georgia, 'Times New Roman', serif`,+ sans: `system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,+ mono: `ui-monospace, 'SF Mono', 'Cascadia Mono', Menlo, Consolas, monospace`,+}++/** A font name typed by the user, cut down to what a family name can hold.+ * Letters (any script), digits, space, dash, dot, underscore; at most 64.+ * Nothing else gets through, so the name can never close the declaration. */+export function cleanFontName(name: string): string {+ return name.replace(/[^\p{L}\p{N} ._-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 64)+}++export function fontStack(look: Pick<ChatLook, 'font' | 'customFont'>): string | null {+ if (look.font === 'app') return null+ if (look.font === 'custom') {+ const name = cleanFontName(look.customFont)+ return name ? `'${name}', ${FONT_STACKS.sans}` : null+ }+ return FONT_STACKS[look.font]+}++/** Width multiplier of the transcript column; null means no cap. */+export function widthFactor(width: ChatWidth): number | null {+ if (width === 'wide') return 1.35+ if (width === 'full') return null+ return 1+}++/**+ * The CSS custom properties for the transcript in `mode`. Only colours the+ * user picked are emitted; the stylesheet falls back to the app's own colour+ * for every property that is absent (index.css, `.lu-look`).+ */+export function lookVars(look: ChatLook, mode: Mode): Record<string, string> {+ const pane = PANE[mode]+ const vars: Record<string, string> = {}+ const userBubble = look.userBubble ? tintOver(look.userBubble, pane, mode === 'dark' ? 0.22 : 0.16) : null+ const modelBubble = look.modelBubble ? tintOver(look.modelBubble, pane, mode === 'dark' ? 0.18 : 0.12) : null+ const put = (name: string, value: string | null) => { if (value) vars[name] = value }+ put('--lu-look-user-bubble', userBubble)+ put('--lu-look-model-bubble', modelBubble)+ put('--lu-look-model-text', readableOn(look.modelText, modelBubble ?? pane))+ put('--lu-look-user-text', readableOn(look.userText, userBubble ?? pane))+ // Quotes and actions sit inside either bubble: guard against the harder one.+ const harder = (hex: string | null) => {+ if (!hex) return null+ const surfaces = [pane, userBubble, modelBubble].filter((s): s is string => !!s)+ let out: string | null = hex+ for (const s of surfaces) out = readableOn(out, s)+ return out+ }+ if (look.highlightQuotes) put('--lu-look-quote', harder(look.quoteText ?? (mode === 'dark' ? '#fdba74' : '#c2410c')))+ if (look.highlightActions) put('--lu-look-action', harder(look.actionText ?? (mode === 'dark' ? '#a5b4fc' : '#4f46e5')))+ put('--lu-look-font', fontStack(look))+ if (Number.isFinite(look.lineHeight)) vars['--lu-look-leading'] = String(clamp(look.lineHeight, 1.2, 2.2))+ return vars+}++function clamp(n: number, lo: number, hi: number): number {+ return Math.min(hi, Math.max(lo, n))+}++/** Bring a stored look (any shape, from disk or an imported file) back into+ * the type, field by field; unknown or broken fields fall back to defaults. */+export function normalizeLook(raw: unknown): ChatLook {+ const r = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>+ const color = (v: unknown) => (typeof v === 'string' && parseHex(v) ? toHex(parseHex(v)!) : null)+ const oneOf = <T extends string>(v: unknown, list: readonly T[], d: T): T => (list.includes(v as T) ? (v as T) : d)+ return {+ modelText: color(r.modelText),+ userText: color(r.userText),+ userBubble: color(r.userBubble),+ modelBubble: color(r.modelBubble),+ quoteText: color(r.quoteText),+ actionText: color(r.actionText),+ highlightQuotes: r.highlightQuotes === true,+ highlightActions: r.highlightActions === true,+ font: oneOf(r.font, ['app', 'serif', 'sans', 'mono', 'custom'] as const, 'app'),+ customFont: typeof r.customFont === 'string' ? cleanFontName(r.customFont) : '',+ width: oneOf(r.width, ['normal', 'wide', 'full'] as const, 'normal'),+ layout: oneOf(r.layout, ['default', 'bubbles', 'document'] as const, 'default'),+ lineHeight: typeof r.lineHeight === 'number' && Number.isFinite(r.lineHeight) ? clamp(r.lineHeight, 1.2, 2.2) : DEFAULT_LOOK.lineHeight,+ customCss: typeof r.customCss === 'string' ? r.customCss.slice(0, MAX_CSS) : '',+ customCssOn: r.customCssOn === true,+ }+}++export const MAX_CSS = 20_000++/** Ready-made looks, each tested in both modes by the guard above. */+export const LOOK_PRESETS: { id: string; label: string; look: Partial<ChatLook> }[] = [+ { id: 'lu', label: 'LU default', look: {} },+ {+ id: 'story', label: 'Story',+ look: { font: 'serif', lineHeight: 1.8, highlightQuotes: true, highlightActions: true, quoteText: '#c2410c', actionText: '#6d28d9', layout: 'document' },+ },+ {+ id: 'roleplay', label: 'Roleplay',+ look: { highlightQuotes: true, highlightActions: true, quoteText: '#ea580c', actionText: '#6366f1', userBubble: '#3b82f6', layout: 'bubbles', modelBubble: '#64748b' },+ },+ {+ id: 'calm', label: 'Calm',+ look: { modelText: '#334155', userBubble: '#14b8a6', font: 'sans', lineHeight: 1.75 },+ },+ {+ id: 'contrast', label: 'High contrast',+ look: { modelText: '#000000', userText: '#000000', highlightQuotes: true, highlightActions: true, quoteText: '#9a3412', actionText: '#1d4ed8', lineHeight: 1.7 },+ },+]++// ── Zoom (C42) ───────────────────────────────────────────────────────────++export const ZOOM_MIN = 0.7+export const ZOOM_MAX = 2+export const ZOOM_STEP = 0.1++export function clampZoom(z: number): number {+ if (!Number.isFinite(z)) return 1+ return Math.round(clamp(z, ZOOM_MIN, ZOOM_MAX) * 100) / 100+}++/**+ * The next zoom for one wheel event with Ctrl/Cmd held. A mouse wheel sends+ * notches (|deltaY| around 100, or deltaMode lines): one step per notch, as a+ * browser does. A trackpad pinch on macOS arrives as small ctrl+wheel deltas:+ * those zoom smoothly, in proportion.+ */+export function wheelZoom(current: number, deltaY: number, deltaMode = 0): number {+ if (deltaY === 0) return clampZoom(current)+ const notch = deltaMode !== 0 || Math.abs(deltaY) >= 50+ if (notch) return clampZoom(Math.round((current + (deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP)) * 10) / 10)+ return clampZoom(current * Math.exp(-deltaY * 0.01))+}++/** Ctrl/Cmd with + / = / - / 0, as in a browser. */+export function keyZoom(current: number, key: string): number | null {+ if (key === '+' || key === '=') return clampZoom(Math.round((current + ZOOM_STEP) * 10) / 10)+ if (key === '-' || key === '_') return clampZoom(Math.round((current - ZOOM_STEP) * 10) / 10)+ if (key === '0') return 1+ return null+}++// ── Background ───────────────────────────────────────────────────────────++export interface ChatBackground {+ /** `lu-attachment:v1:<sha256>` from lib/chat-attachments (never inline). */+ ref: string+ /** How much of the pane colour lies over the picture, 0.5 to 0.95. */+ scrim: number+ /** Blur in px, 0 to 16. */+ blur: number+}++export const SCRIM_MIN = 0.5+export const SCRIM_DEFAULT = 0.72++export function bgKeyForChat(conversationId: string): string { return `chat:${conversationId}` }+export function bgKeyForPersona(personaId: string): string { return `persona:${personaId}` }++/** The chat's own picture wins over the persona's. */+export function pickBackground(+ backgrounds: Record<string, ChatBackground>,+ conversationId: string | null | undefined,+ personaId: string | null | undefined,+): { key: string; bg: ChatBackground } | null {+ if (conversationId) {+ const k = bgKeyForChat(conversationId)+ if (backgrounds[k]) return { key: k, bg: backgrounds[k] }+ }+ if (personaId) {+ const k = bgKeyForPersona(personaId)+ if (backgrounds[k]) return { key: k, bg: backgrounds[k] }+ }+ return null+}++export function normalizeBackground(b: Partial<ChatBackground>): ChatBackground | null {+ if (typeof b.ref !== 'string' || !/^lu-attachment:v1:[a-f0-9]{64}$/.test(b.ref)) return null+ return {+ ref: b.ref,+ scrim: typeof b.scrim === 'number' && Number.isFinite(b.scrim) ? clamp(b.scrim, SCRIM_MIN, 0.95) : SCRIM_DEFAULT,+ blur: typeof b.blur === 'number' && Number.isFinite(b.blur) ? clamp(Math.round(b.blur), 0, 16) : 0,+ }+}++/**+ * A prompt for a background of the current scene, made from the latest+ * reply (or the latest message): narration only. Quoted speech, markdown and+ * out-of-character notes are dropped, the rest is cut at a sentence near 400+ * characters. The user sees and edits it before anything is generated.+ */+export function scenePrompt(texts: string[]): string {+ const source = [...texts].reverse().find((t) => t && t.trim()) ?? ''+ const narration = source+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/\(\((?:.|\n)*?\)\)|\[OOC[^\]]*\]/gi, ' ')+ .replace(/"[^"\n]*"|“[^”\n]*”|„[^“”\n]*[“”]|«[^»\n]*»/g, ' ')+ .replace(/[*_#>`~|]/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ let cut = narration.slice(0, 420)+ if (narration.length > 420) {+ const end = cut.lastIndexOf('. ')+ if (end > 120) cut = cut.slice(0, end + 1)+ }+ const scene = cut || 'a calm, atmospheric place'+ return `Wide background scenery, empty of people, no text, soft focus, cinematic light. Scene: ${scene}`+}diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex aac15859..8a366b3b 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -41,6 +41,10 @@ export const STORE_KEYS = ['lu-cloud-outage',// Neuron tweaker slider values per model and persona (3.0.9, P11).'lu-neuron-tweaker',+ // Chat look, reading zoom and the background references per chat and+ // persona (3.1.0, C58/C42). Also what keeps those background files alive:+ // the attachment collector keeps every reference it finds in the backup.+ 'lu-chat-look','locally-uncensored-agent-goal',// Computer control: the switch and the always allowed apps.'locally-uncensored-computer',diff --git a/src/mobile/boot/__tests__/settings-durable.test.ts b/src/mobile/boot/__tests__/settings-durable.test.tsindex 993644d2..764f7b18 100644--- a/src/mobile/boot/__tests__/settings-durable.test.ts+++ b/src/mobile/boot/__tests__/settings-durable.test.ts@@ -110,6 +110,7 @@ describe('which keys are kept', () => {'lu-local-api': 'desktop only','locally-uncensored-computer': 'desktop only: the settings of computer use, which the phone does not have','lu-neuron-tweaker': 'desktop only (3.0.9, P11): the Neuron tweaker steers LU Engine, which the phone does not have',+ 'lu-chat-look': 'desktop only (3.1.0, C58): the chat look of the desktop transcript; the phone has its own chat screen','LU-create-orders': 'the orders of Create in chat, which is locked on the phone until it has the order card','lu-mobile-switched-under-answer': 'a note per answer; lost, the chat says "interrupted" instead of "you switched models"','lu-mobile-settings-stamp': 'the stamp of this copy itself; in the native backup it dates the settings there (L5)',diff --git a/src/stores/chatLookStore.ts b/src/stores/chatLookStore.tsnew file mode 100644index 00000000..c89d60b8--- /dev/null+++ b/src/stores/chatLookStore.ts@@ -0,0 +1,84 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'+import {+ DEFAULT_LOOK, clampZoom, normalizeBackground, normalizeLook,+ type ChatBackground, type ChatLook,+} from '../lib/chat-look'++/**+ * The chat look (lib/chat-look.ts), the reading zoom and the background+ * pictures per chat and per persona. Persisted as `lu-chat-look` and carried+ * by the store backup (lib/store-backup.ts STORE_KEYS).+ *+ * The pictures themselves are NOT in here: a background is a reference+ * (`lu-attachment:v1:<sha256>`) into the attachment store (native files on+ * the desktop, IndexedDB in a browser), so a 400 kB JPEG never lands in+ * localStorage. Because the backup holds this store, the attachment garbage+ * collector (chat_attachments.rs) sees the reference and keeps the file.+ */+interface ChatLookState {+ look: ChatLook+ /** Reading zoom of the transcript (C42), 0.7 to 2. */+ zoom: number+ /** Key `chat:<id>` or `persona:<id>` (lib/chat-look bgKeyFor*). */+ backgrounds: Record<string, ChatBackground>+ setLook: (patch: Partial<ChatLook>) => void+ replaceLook: (look: unknown) => void+ resetLook: () => void+ setZoom: (zoom: number) => void+ setBackground: (key: string, bg: Partial<ChatBackground> & { ref: string }) => void+ patchBackground: (key: string, patch: Partial<Omit<ChatBackground, 'ref'>>) => void+ removeBackground: (key: string) => void+}++export const useChatLookStore = create<ChatLookState>()(+ persist(+ (set, get) => ({+ look: DEFAULT_LOOK,+ zoom: 1,+ backgrounds: {},+ setLook: (patch) => set({ look: normalizeLook({ ...get().look, ...patch }) }),+ replaceLook: (look) => set({ look: normalizeLook(look) }),+ resetLook: () => set({ look: DEFAULT_LOOK }),+ setZoom: (zoom) => set({ zoom: clampZoom(zoom) }),+ setBackground: (key, bg) => {+ const clean = normalizeBackground(bg)+ if (!clean) return+ set({ backgrounds: { ...get().backgrounds, [key]: clean } })+ },+ patchBackground: (key, patch) => {+ const now = get().backgrounds[key]+ if (!now) return+ const clean = normalizeBackground({ ...now, ...patch })+ if (clean) set({ backgrounds: { ...get().backgrounds, [key]: clean } })+ },+ removeBackground: (key) => {+ const next = { ...get().backgrounds }+ delete next[key]+ set({ backgrounds: next })+ },+ }),+ {+ name: 'lu-chat-look',+ storage: safeJSONStorage(),+ partialize: (s) => ({ look: s.look, zoom: s.zoom, backgrounds: s.backgrounds }) as ChatLookState,+ merge: (persisted, current) => {+ const p = (persisted && typeof persisted === 'object' ? persisted : {}) as Partial<ChatLookState>+ const backgrounds: Record<string, ChatBackground> = {}+ if (p.backgrounds && typeof p.backgrounds === 'object') {+ for (const [k, v] of Object.entries(p.backgrounds)) {+ const clean = v && typeof v === 'object' ? normalizeBackground(v) : null+ if (clean && /^(chat|persona):.+/.test(k)) backgrounds[k] = clean+ }+ }+ return {+ ...current,+ look: normalizeLook(p.look),+ zoom: clampZoom(typeof p.zoom === 'number' ? p.zoom : 1),+ backgrounds,+ }+ },+ },+ ),+)