Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add customizable chat background images and effects (#15973)
Wasim Yousef Said694cac1bea1a
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex bbc20a350d0..4fd1b151816 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -443,8 +443,10 @@ export const BUDGET = {// 1,849,311 -> 1,849,948 B transfer against b80df648bf, one machine and build, Node 22, 85 chunks both): the app// provider reports a ready renderer through the setting's API module at startup, plus the setting's strings in// the eager English catalog and its search rows. Raised by that.- transferBytes: 1_850_410,- rawBytes: 5_991_390,+ // Chat wallpaper prefs, reset and English strings: +6,365 B raw / +3,589 B transfer (Node 24,+ // 85 -> 89 eager chunks). Renderer, contrast and pixel worker stay lazy.+ transferBytes: 1_853_999,+ rawBytes: 5_997_755,};// Chunk count is not budgeted: splitting a page out raises it while lowering bytes.diff --git a/studio/frontend/smoke-chat-background-main.tsx b/studio/frontend/smoke-chat-background-main.tsxnew file mode 100644index 00000000000..11484f28ba8--- /dev/null+++ b/studio/frontend/smoke-chat-background-main.tsx@@ -0,0 +1,125 @@+import { WindowTitlebar } from "./src/components/tauri/window-titlebar";+// Backend-free wallpaper integration fixture: production settings and renderer.+import { StrictMode, useState } from "react";+import { createRoot } from "react-dom/client";+import { ChatBackground } from "./src/features/chat-background/background";+import { BACKGROUND_ON_ALL_PAGES } from "./src/features/chat-background/model";+import { ChatBackgroundControls } from "./src/features/chat-background/controls";+import {+ resetChatBackground,+ patchBackground,+ useBackgroundStore,+} from "./src/features/chat-background/storage";+import { TooltipProvider } from "./src/components/ui/tooltip";+import "./src/index.css";+declare global {+ interface Window {+ __wallpaperSmoke: {+ patch: typeof patchBackground;+ state: typeof useBackgroundStore.getState;+ };+ }+}+window.__wallpaperSmoke = {+ patch: patchBackground,+ state: useBackgroundStore.getState,+};+function App() {+ const [conversation, setConversation] = useState(false),+ [active, setActive] = useState(true),+ [sidebar, setSidebar] = useState(false),+ [otherPage, setOtherPage] = useState(false),+ [dark, setDark] = useState(false);+ return (+ <TooltipProvider>+ <div className="p-4 text-foreground">+ <div className="mb-4 flex flex-wrap gap-4">+ <button onClick={() => setConversation((v) => !v)}>+ Toggle conversation+ </button>+ <button+ onClick={() => {+ setDark(!dark);+ document.documentElement.classList.toggle("dark", !dark);+ }}+ >+ Toggle theme+ </button>+ <button onClick={() => setActive((v) => !v)}>Toggle route</button>+ <button onClick={() => setSidebar(v => !v)}>Toggle sidebar</button>+ <button onClick={() => setOtherPage(v => !v)}>Toggle page</button>+ <button onClick={() => void resetChatBackground()}>Reset all</button>+ </div>+ <div className="grid gap-8 lg:grid-cols-2">+ <div className="settings-page">+ <ChatBackgroundControls />+ </div>+ <div+ data-chat-content-root=""+ data-wallpaper-workspace=""+ data-wallpaper-route={otherPage ? "page" : "chat"}+ className="relative h-[700px] overflow-hidden rounded-xl border bg-background"+ >+ <ChatBackground active={active && (!otherPage || BACKGROUND_ON_ALL_PAGES)} />+ <WindowTitlebar showSidebarSurface />+ {sidebar && <aside data-slot="sidebar" className="absolute inset-y-0 left-0 z-50 w-40 bg-sidebar p-4">Unsloth<br />New chat<br />Model hub</aside>}+ <main data-slot="sidebar-inset" className="relative h-full" style={{marginLeft: sidebar ? 160 : 0}}>+ {otherPage && <div className="absolute inset-0 z-40 p-16"><h1>Model hub</h1><div className="mt-4 rounded-xl bg-card p-6">Models and downloads</div></div>}+ <div style={{visibility: otherPage ? "hidden" : "visible"}} className="h-full">+ <div data-side-panel-inset="" className="absolute inset-x-0 top-[var(--studio-content-top-inset,0px)] z-40 flex h-12 items-center justify-between bg-background px-3">+ <div data-wallpaper-chrome-controls="" className="p-2 text-xs">Select model</div>+ <div data-wallpaper-chrome-controls="" className="p-2 text-xs">Search · Browser</div>+ </div>+ <div data-side-panel-inset="" className="chat-header-fade pointer-events-none absolute inset-x-0 top-[calc(var(--studio-content-top-inset,0px)+48px)] z-20 h-6 bg-gradient-to-b from-background to-transparent" />+ <div className="aui-thread-root relative h-full">+ <div className="aui-thread-viewport h-full p-8">+ <div+ className={+ conversation+ ? "space-y-8 pt-12"+ : "aui-thread-welcome-center pt-48"+ }+ >+ {conversation ? (+ <>+ <p className="text-muted-foreground">+ Tell me about this scene.+ </p>+ <p>+ A clear conversation, with the artwork quietly in the+ background.+ </p>+ <pre className="rounded-xl bg-card p-4">+ const greeting = "Hello";+ </pre>+ </>+ ) : (+ <h1 className="unsloth-welcome-greeting mb-6 text-center text-2xl">+ What would you like to explore?+ </h1>+ )}+ <div className="unsloth-composer-surface mt-8 p-6">+ <textarea+ aria-label="Message"+ placeholder="Ask anything…"+ className="w-full bg-transparent outline-none"+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>+ </div>+ </div>+ </div>+ </TooltipProvider>+ );+}+const root = createRoot(document.getElementById("root")!);+if (import.meta.hot) import.meta.hot.dispose(() => root.unmount());+root.render(+ <StrictMode>+ <App />+ </StrictMode>,+);diff --git a/studio/frontend/smoke-chat-background.html b/studio/frontend/smoke-chat-background.htmlnew file mode 100644index 00000000000..0316feb178b--- /dev/null+++ b/studio/frontend/smoke-chat-background.html@@ -0,0 +1 @@+<!doctype html><html><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Chat background verification</title></head><body><div id="root"></div><script type="module" src="/smoke-chat-background-main.tsx"></script></body></html>diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 1c18b3844db..a7fa996a55a 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { BACKGROUND_ON_ALL_PAGES, ChatBackground } from "@/features/chat-background";import { ImageViewer } from "@/components/image-viewer";import { useAppShellReadySignal } from "@/components/app-readiness";import { LazyImportFailure } from "@/components/lazy-import-boundary";@@ -721,8 +722,11 @@ function RootLayout() {pinned={pinned}setPinned={setPinned}togglePinned={togglePinned}- className="!min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden"+ data-wallpaper-workspace=""+ data-wallpaper-route={isChatRoute ? "chat" : "page"}+ className="relative !min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden">+ <ChatBackground active={isChatRoute || BACKGROUND_ON_ALL_PAGES} /><AppSidebar /><SidebarEdgeTrigger /><SidebarInsetdiff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsxindex e8fec1b9857..c1c2f740fa3 100644--- a/studio/frontend/src/components/tauri/window-titlebar.tsx+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx@@ -504,12 +504,14 @@ export function WindowTitlebar({)}data-titlebar-live-width-scope=""data-slot="window-titlebar"+ data-wallpaper-sidebar-pinned={showSidebarSurface && pinned || undefined}data-viewport-backdrop-open={backdropOpen ? "" : undefined}data-viewport-backdrop-tone={backdropTone ?? undefined}aria-label={t("desktopShell.titlebar")}>{showSidebarSurface && (<div+ data-wallpaper-chrome-controls=""// Glyph in the sidebar's icon column, over New chat's pencil: 19px in, less 6px padding.className="pointer-events-auto absolute left-0 top-0 flex h-full min-w-0 items-center pl-[calc(4.75*var(--spacing)-6px)]"style={{ width: titlebarNavigationWidth }}@@ -539,6 +541,7 @@ export function WindowTitlebar({"pointer-events-auto absolute right-0 top-0 z-[100] flex h-full",focused ? "text-foreground" : "text-muted-foreground",)}+ data-wallpaper-chrome-controls=""role="toolbar"aria-label={t("desktopShell.windowControls")}>diff --git a/studio/frontend/src/features/chat-background/background.tsx b/studio/frontend/src/features/chat-background/background.tsxnew file mode 100644index 00000000000..7e8381c0ede--- /dev/null+++ b/studio/frontend/src/features/chat-background/background.tsx@@ -0,0 +1,218 @@+// SPDX-License-Identifier: AGPL-3.0-only+import {+ useEffect,+ useEffectEvent,+ useRef,+ useState,+ type CSSProperties,+} from "react";+import { useChatBackground, setBackgroundError } from "./storage";+import { acquireRender } from "./render";+import { safeArtworkOpacity, type RGB } from "./contrast";+import type { ChatBackgroundValue } from "./model";++type Frame = { url: string; value: ChatBackgroundValue };+export function ChatBackground({ active = true }: { active?: boolean }) {+ const { value } = useChatBackground();+ const enabled = Boolean(value);+ const blob = value?.blob;+ const effect = value?.effect;+ const themeDependent = effect !== "None" && effect !== "Dither";+ const host = useRef<HTMLDivElement>(null);+ const urls = useRef(new Set<string>());+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const latest = useRef<Frame | null>(null);+ const [frames, setFrames] = useState<{+ current: Frame | null;+ previous: Frame | null;+ }>({ current: null, previous: null });+ const [skin, setSkin] = useState({ light: false, reduced: true, safe: 0 });+ useEffect(() => {+ if (!enabled || !active) return;+ const html = document.documentElement,+ media = window.matchMedia("(prefers-reduced-motion: reduce)");+ let frame = 0;+ const update = () => {+ const el = host.current;+ if (!el) return;+ const probe = document.createElement("span");+ probe.style.position = "absolute";+ probe.style.visibility = "hidden";+ el.append(probe);+ const ctx = document+ .createElement("canvas")+ .getContext("2d", { willReadFrequently: true })!;+ const rgb = (token: string): RGB => {+ probe.style.color = `var(${token})`;+ ctx.clearRect(0, 0, 1, 1);+ ctx.fillStyle = getComputedStyle(probe).color;+ ctx.fillRect(0, 0, 1, 1);+ const p = ctx.getImageData(0, 0, 1, 1).data;+ return [p[0], p[1], p[2]];+ };+ const safe = safeArtworkOpacity(rgb("--background"), [+ rgb("--foreground"),+ rgb("--muted-foreground"),+ ]);+ probe.remove();+ setSkin({+ light: !html.classList.contains("dark"),+ reduced:+ html.classList.contains("force-reduced-motion") ||+ (!html.classList.contains("force-motion") && media.matches),+ safe,+ });+ };+ const schedule = () => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(update);+ };+ const observer = new MutationObserver(schedule);+ observer.observe(html, {+ attributes: true,+ attributeFilter: ["style", "class", "data-palette"],+ });+ media.addEventListener("change", schedule);+ update();+ return () => {+ observer.disconnect();+ media.removeEventListener("change", schedule);+ cancelAnimationFrame(frame);+ };+ }, [enabled, active]);+ useEffect(() => {+ const parent = host.current?.parentElement;+ if (!parent || !enabled || !active) return;+ parent.style.setProperty("--wallpaper-safe", String(skin.safe));+ return () => {+ parent.style.removeProperty("--wallpaper-safe");+ };+ }, [skin.safe, enabled, active]);+ const adoptFrame = useEffectEvent((url: string) => {+ urls.current.add(url);+ clearTimeout(timer.current);+ const previous = skin.reduced ? null : latest.current;+ const current = { url, value: value! };+ latest.current = current;+ setFrames({ current, previous });+ timer.current = setTimeout(+ () =>+ setFrames((s) =>+ s.current === current ? { current, previous: null } : s,+ ),+ skin.reduced ? 0 : 180,+ );+ });+ const renderLight = themeDependent && skin.light;+ useEffect(() => {+ if (!active || !blob || !effect) {+ latest.current = null;+ let cancelled = false;+ queueMicrotask(() => {+ if (!cancelled) setFrames({ current: null, previous: null });+ });+ return () => {+ cancelled = true;+ };+ }+ let cancelled = false;+ const job = acquireRender(blob, effect, renderLight);+ void job.promise+ .then(async (blob) => {+ if (cancelled) return;+ const url = URL.createObjectURL(blob);+ const image = new Image();+ image.src = url;+ try {+ await image.decode();+ } catch {+ urls.current.delete(url);+ URL.revokeObjectURL(url);+ throw new Error("decode");+ }+ if (cancelled) {+ urls.current.delete(url);+ URL.revokeObjectURL(url);+ return;+ }+ adoptFrame(url);+ })+ .catch(() => {+ if (!cancelled) setBackgroundError("effect");+ });+ return () => {+ cancelled = true;+ job.release();+ };+ // Visual controls are CSS only, never inputs to image processing.+ }, [active, blob, effect, renderLight]);+ useEffect(() => {+ const alive = new Set([frames.current?.url, frames.previous?.url]);+ for (const url of urls.current)+ if (!alive.has(url)) {+ URL.revokeObjectURL(url);+ urls.current.delete(url);+ }+ }, [frames]);+ useEffect(+ () => () => {+ clearTimeout(timer.current);+ for (const url of urls.current) URL.revokeObjectURL(url);+ urls.current.clear();+ },+ [],+ );+ if (!value || !active) return null;+ return (+ <div+ ref={host}+ aria-hidden="true"+ className="chat-wallpaper"+ data-ready={Boolean(frames.current) || undefined}+ data-reduced={skin.reduced || undefined}+ data-outline={value.outline}+ style={{ "--wallpaper-safe": skin.safe } as CSSProperties}+ >+ {[frames.previous, frames.current].map((frame, i) => {+ if (!frame) return null;+ const adjustment =+ frame.value.blob === value.blob ? value : frame.value;+ return (+ <div+ key={frame.url}+ className="chat-wallpaper-frame"+ data-effect={frame.value.effect}+ data-departing={i === 0 || undefined}+ data-entering={(i === 1 && Boolean(frames.previous)) || undefined}+ style={+ {+ "--wallpaper-visibility": adjustment.visibility / 100,+ } as CSSProperties+ }+ >+ <div className="chat-wallpaper-image" data-fade={adjustment.fade}>+ <div+ className="chat-wallpaper-artwork"+ style={{+ backgroundImage: `url("${frame.url}")`,+ backgroundPosition: adjustment.position,+ backgroundSize:+ adjustment.sizing === "original"+ ? "auto"+ : adjustment.sizing === "stretch"+ ? "100% 100%"+ : adjustment.sizing,+ transform: `scale(${adjustment.zoom / 100})`,+ transformOrigin: adjustment.position,+ filter: adjustment.blur+ ? `blur(${adjustment.blur}px)`+ : undefined,+ }}+ />+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/studio/frontend/src/features/chat-background/contrast.ts b/studio/frontend/src/features/chat-background/contrast.tsnew file mode 100644index 00000000000..d18e1004028--- /dev/null+++ b/studio/frontend/src/features/chat-background/contrast.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+export type RGB = readonly [number, number, number];+export function luminance(rgb: RGB): number {+ const linear = rgb.map((v) => {+ const c = v / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+ return linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;+}+export function contrast(a: RGB, b: RGB): number {+ const x = luminance(a),+ y = luminance(b);+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);+}+/** Largest artwork alpha safe for any image; keeps a deliberately chosen theme contrast below 4.5. */+export function safeArtworkOpacity(+ background: RGB,+ foregrounds: RGB[],+): number {+ const targets = foregrounds.map((f) =>+ Math.min(4.5, contrast(background, f)),+ );+ const passes = (alpha: number) => {+ const low = luminance(+ background.map((c) => c * (1 - alpha)) as unknown as RGB,+ );+ const high = luminance(+ background.map((c) => c * (1 - alpha) + 255 * alpha) as unknown as RGB,+ );+ return foregrounds.every((f, i) => {+ const l = luminance(f);+ const nearest = Math.max(low, Math.min(high, l));+ return (+ (Math.max(l, nearest) + 0.05) / (Math.min(l, nearest) + 0.05) >=+ targets[i] - 1e-7+ );+ });+ };+ let lo = 0,+ hi = 1;+ for (let i = 0; i < 24; i++) {+ const mid = (lo + hi) / 2;+ if (passes(mid)) lo = mid;+ else hi = mid;+ }+ return lo;+}diff --git a/studio/frontend/src/features/chat-background/controls.tsx b/studio/frontend/src/features/chat-background/controls.tsxnew file mode 100644index 00000000000..549ede03785--- /dev/null+++ b/studio/frontend/src/features/chat-background/controls.tsx@@ -0,0 +1,337 @@+// SPDX-License-Identifier: AGPL-3.0-only+import { useRef } from "react";+import { Cancel01Icon, Upload01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Slider } from "@/components/ui/slider";+import { useT, type TranslationKey } from "@/i18n";+// Shared settings primitives: avoid importing the settings barrel into this feature.+// eslint-disable-next-line no-restricted-imports+import { SettingsSection } from "@/features/settings/components/settings-section";+// eslint-disable-next-line no-restricted-imports+import { SettingsRow } from "@/features/settings/components/settings-row";+import { ChatBackground } from "./index";+import {+ DEFAULT_ADJUSTMENTS,+ EFFECTS,+ IMAGE_SIZING,+ type ImageSizing,+ POSITIONS,+ normalizedSize,+ validUpload,+ type BackgroundEffect,+} from "./model";+import {+ beginBackgroundUpload,+ failBackgroundUpload,+ finishBackgroundUpload,+ patchBackground,+ resetChatBackground,+ useChatBackground,+} from "./storage";+import { canvasBlob, decodeImage } from "./image";++const labels: Record<BackgroundEffect, TranslationKey> = {+ None: "chatBackground.none",+ Dither: "chatBackground.dither",+ ASCII: "chatBackground.ascii",+ Halftone: "chatBackground.halftone",+ Scanlines: "chatBackground.scanlines",+};+const sizingLabels: Record<ImageSizing, TranslationKey> = {+ cover: "chatBackground.fill",+ contain: "chatBackground.fit",+ stretch: "chatBackground.stretch",+ original: "chatBackground.original",+};+const errors = {+ storage: "chatBackground.storageError",+ file: "chatBackground.fileError",+ dimensions: "chatBackground.dimensionsError",+ decode: "chatBackground.decodeError",+ effect: "chatBackground.effectError",+} as const;+export function ChatBackgroundControls() {+ const t = useT();+ const { value, error, ready, busy } = useChatBackground();+ const input = useRef<HTMLInputElement>(null);+ const adjustments = value ?? DEFAULT_ADJUSTMENTS;+ return (+ <SettingsSection+ title={t("chatBackground.title")}+ action={+ <div className="flex max-w-full flex-wrap items-center justify-end gap-1">+ {value && (+ <Button+ // Same hover wash as the outline (btn-fill) Replace button beside it.+ className="text-foreground hover:bg-[color-mix(in_srgb,var(--foreground)_calc(8%*var(--contrast-wash-gain,1)),transparent)] dark:hover:bg-[color-mix(in_srgb,var(--foreground)_calc(10%*var(--contrast-wash-gain,1)),transparent)]"+ type="button"+ variant="ghost"+ size="sm"+ disabled={busy}+ onClick={() => void resetChatBackground()}+ >+ <HugeiconsIcon+ icon={Cancel01Icon}+ strokeWidth={1.75}+ className="size-4"+ aria-hidden="true"+ />+ {t("chatBackground.remove")}+ </Button>+ )}++ <Button+ className="text-foreground"+ type="button"+ variant="outline"+ size="sm"+ disabled={!ready || busy}+ onClick={() => input.current?.click()}+ >+ <HugeiconsIcon+ icon={Upload01Icon}+ strokeWidth={1.75}+ className="size-4"+ aria-hidden="true"+ />+ {busy+ ? t("common.loading")+ : t(value ? "chatBackground.replace" : "chatBackground.upload")}+ </Button>+ </div>+ }+ >+ <input+ ref={input}+ className="sr-only"+ tabIndex={-1}+ aria-label={t("chatBackground.upload")}+ type="file"+ accept="image/jpeg,image/png,image/webp"+ disabled={!ready || busy}+ onChange={async (event) => {+ const file = event.target.files?.[0];+ event.target.value = "";+ if (!file) return;+ const ticket = beginBackgroundUpload();+ if (!validUpload(file)) {+ failBackgroundUpload(ticket, "file");+ return;+ }+ try {+ const decoded = await decodeImage(file);+ try {+ const [width, height] = normalizedSize(+ decoded.width,+ decoded.height,+ );+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("decode");+ ctx.drawImage(decoded.source, 0, 0, width, height);+ await finishBackgroundUpload(ticket, {+ ...DEFAULT_ADJUSTMENTS,+ blob: await canvasBlob(canvas),+ });+ } finally {+ decoded.close();+ }+ } catch (error) {+ failBackgroundUpload(+ ticket,+ error instanceof Error && error.message === "dimensions"+ ? "dimensions"+ : "decode",+ );+ }+ }}+ />+ {error && (+ <p role="alert" className="mt-3 mb-3 text-sm text-destructive">+ {t(errors[error])}+ </p>+ )}+ <div+ className={`${error ? "" : "mt-3 "}grid grid-cols-1 gap-3 sm:grid-cols-2`}+ data-wallpaper-previews=""+ >+ {[false, true].map((conversation) => (+ <div key={String(conversation)} className="min-w-0">+ <p className="mb-2 text-xs text-muted-foreground">+ {t(+ conversation+ ? "chatBackground.conversation"+ : "chatBackground.newChat",+ )}+ </p>+ <div+ className="wallpaper-preview relative h-48 overflow-hidden rounded-xl border border-border bg-background"+ data-wallpaper-conversation={conversation || undefined}+ >+ <ChatBackground />+ {!value && (+ <p className="absolute inset-x-4 top-4 text-center text-xs text-muted-foreground">+ {t("chatBackground.noBackground")}+ </p>+ )}+ <div className="wallpaper-preview-content absolute inset-x-4 bottom-4 space-y-3 text-xs">+ {conversation && (+ <p className="wallpaper-preview-prose rounded-lg p-3">+ {t("chatBackground.response")}+ </p>+ )}+ <div className="wallpaper-preview-composer rounded-xl p-3">+ {t("chatBackground.prompt")}+ </div>+ </div>+ </div>+ </div>+ ))}+ </div>+ {value && (+ <>+ <SettingsRow label={t("chatBackground.effect")} className="mt-3 items-start">+ <Select+ disabled={!value || busy}+ value={adjustments.effect}+ onValueChange={(effect) =>+ patchBackground({ effect: effect as BackgroundEffect })+ }+ >+ <SelectTrigger+ aria-label={t("chatBackground.effect")}+ className="w-52"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EFFECTS.map((effect) => (+ <SelectItem key={effect} value={effect}>+ {t(labels[effect])}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ <SettingsRow label={t("chatBackground.sizing")} className="items-start">+ <Select+ disabled={!value || busy}+ value={adjustments.sizing}+ onValueChange={(sizing) =>+ patchBackground({ sizing: sizing as ImageSizing })+ }+ >+ <SelectTrigger+ aria-label={t("chatBackground.sizing")}+ className="w-52"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {IMAGE_SIZING.map((sizing) => (+ <SelectItem key={sizing} value={sizing}>+ {t(sizingLabels[sizing])}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ {(["visibility", "blur", "zoom"] as const).map((key) => (+ <SettingsRow+ key={key}+ className="items-start"+ label={t(+ key === "zoom"+ ? "chatBackground.zoom"+ : key === "blur"+ ? "chatBackground.blur"+ : "chatBackground.visibility",+ )}+ >+ <div className="flex w-52 items-center gap-3">+ <Slider+ disabled={!value || busy}+ aria-label={t(+ key === "zoom"+ ? "chatBackground.zoom"+ : key === "blur"+ ? "chatBackground.blur"+ : "chatBackground.visibility",+ )}+ min={key === "zoom" ? 100 : 0}+ max={key === "zoom" ? 300 : key === "blur" ? 20 : 100}+ step={1}+ value={[adjustments[key]]}+ onValueChange={([v]) => patchBackground({ [key]: v })}+ />+ <span className="w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground">+ {adjustments[key]}+ {key === "blur" ? "px" : "%"}+ </span>+ </div>+ </SettingsRow>+ ))}+ <SettingsRow label={t("chatBackground.outline")} className="items-start">+ <Switch+ aria-label={t("chatBackground.outline")}+ checked={adjustments.outline}+ disabled={!value || busy}+ onCheckedChange={(outline) => patchBackground({ outline })}+ />+ </SettingsRow>+ <SettingsRow label={t("chatBackground.fade")} className="items-start">+ <Switch+ aria-label={t("chatBackground.fade")}+ checked={adjustments.fade}+ disabled={!value || busy}+ onCheckedChange={(fade) => patchBackground({ fade })}+ />+ </SettingsRow>+ <SettingsRow+ label={t("chatBackground.position")}+ className="items-start"+ >+ <div className="flex w-52 justify-end">+ <div+ className="grid w-fit grid-cols-3 gap-1"+ role="group"+ aria-label={t("chatBackground.position")}+ >+ {POSITIONS.map((position) => {+ const [x, y] = position+ .split(" ")+ .map((v) => Number.parseInt(v));+ return (+ <button+ key={position}+ type="button"+ disabled={!value || busy}+ aria-pressed={adjustments.position === position}+ aria-label={t("chatBackground.positionValue", { x, y })}+ title={t("chatBackground.positionValue", { x, y })}+ className="flex size-6 items-center justify-center rounded-full border border-border text-muted-foreground hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring aria-pressed:border-primary aria-pressed:bg-primary/10 aria-pressed:text-primary disabled:opacity-40"+ onClick={() => patchBackground({ position })}+ >+ <span className="size-1 rounded-full bg-current" />+ </button>+ );+ })}+ </div>+ </div>+ </SettingsRow>+ </>+ )}+ </SettingsSection>+ );+}diff --git a/studio/frontend/src/features/chat-background/effects.ts b/studio/frontend/src/features/chat-background/effects.tsnew file mode 100644index 00000000000..0bc70677450--- /dev/null+++ b/studio/frontend/src/features/chat-background/effects.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { BackgroundEffect } from "./model.ts";++// Recursive ordered dither: low coordinate bits give the most significant rank bits.+function orderedRank(column: number, row: number): number {+ let rank = 0;+ for (let bit = 0; bit < 2; bit++) {+ const horizontal = (column >> bit) & 1;+ const vertical = (row >> bit) & 1;+ rank = rank * 4 + 2 * (horizontal ^ vertical) + vertical;+ }+ return rank;+}++// 5x7 stroked glyphs with 1px right/bottom spacing: no platform font rasterization.+function punctuationInk(level: number, x: number, y: number): boolean {+ if (x === 5 || y === 7) return false;+ switch (level) {+ case 1:+ return x === 2 && y === 5; // .+ case 2:+ return x === 2 && (y === 1 || y === 4); // :+ case 3:+ return y === 3 && x >= 1 && x <= 3; // -+ case 4:+ return (y === 2 || y === 4) && x >= 1 && x <= 3; // =+ case 5:+ return y === 3 || (x === 2 && y >= 1 && y <= 5); // ++ case 6: // *+ return (+ y === 3 ||+ ((y === 1 || y === 5) && x % 2 === 0) ||+ ((y === 2 || y === 4) && x >= 1 && x <= 3)+ );+ case 7:+ return y === 2 || y === 4 || x === 1 || x === 3; // #+ case 8: // %+ return (+ ((y === 0 || y === 6) && (x === 0 || x === 4)) ||+ (y >= 1 && y <= 5 && x === 4 - Math.round(y * 0.8))+ );+ case 9: // @+ if (y === 0 || y === 6) return x >= 1 && x <= 3;+ if (y === 1) return x === 0 || x === 4;+ if (y === 5) return x === 0;+ return x === 0 || x === 4 || x === 2 || (x === 3 && y !== 3);+ default:+ return false;+ }+}++export function renderEffect(+ source: Uint8ClampedArray,+ width: number,+ height: number,+ effect: BackgroundEffect,+ light: boolean,+): Uint8ClampedArray {+ if (+ ![width, height].every((n) => Number.isSafeInteger(n) && n > 0) ||+ source.length / 4 !== width * height+ ) {+ throw new Error("Invalid image dimensions");+ }+ const pixels = source.slice();+ if (effect === "None") return pixels;++ if (effect === "Scanlines") {+ for (let row = 0; row < height; row += 3) {+ const end = (row + 1) * width * 4;+ for (let offset = row * width * 4; offset < end; offset += 4) {+ for (let channel = 0; channel < 3; channel++) {+ const value = source[offset + channel];+ pixels[offset + channel] = Math.floor(+ light ? value + (255 - value) * 0.48 : value * 0.52,+ );+ }+ }+ }+ return pixels;+ }++ const tileWidth = effect === "ASCII" ? 6 : effect === "Dither" ? 2 : 4;+ const tileHeight = effect === "ASCII" ? 8 : tileWidth;+ const paper = light ? 255 : 0;+ const index = (x: number, y: number) =>+ 4 * (Math.min(y, height - 1) * width + Math.min(x, width - 1));+ const brightness = (offset: number) =>+ (0.2126 * source[offset] ++ 0.7152 * source[offset + 1] ++ 0.0722 * source[offset + 2]) /+ 255;++ // Clip the last cell so odd-sized uploads keep the pattern.+ for (let top = 0; top < height; top += tileHeight) {+ for (let left = 0; left < width; left += tileWidth) {+ const center = index(left + tileWidth / 2, top + tileHeight / 2);+ const color = source.subarray(center, center + 3);+ const level = brightness(+ effect === "Halftone" ? index(left, top) : center,+ );+ const density = Math.sqrt(light ? 1 - level : level);+ const glyph = Math.min(9, Math.floor(density * 9));+ const radius = 2 * (0.3 + 0.7 * density);+ const maximum = Math.max(...color);+ const lit = maximum / 255 > (orderedRank(left / 2, top / 2) + 0.5) / 16;+ const amplification = lit ? 255 / Math.max(1, maximum) : 0.08;+ const dot = Array.from(color, (value) =>+ Math.round(value * amplification),+ );++ for (let dy = 0; dy < Math.min(tileHeight, height - top); dy++) {+ for (let dx = 0; dx < Math.min(tileWidth, width - left); dx++) {+ const offset = ((top + dy) * width + left + dx) * 4;+ const coverage =+ effect === "ASCII"+ ? Number(punctuationInk(glyph, dx, dy))+ : Math.max(+ 0,+ Math.min(1, radius + 0.5 - Math.hypot(dx - 1.5, dy - 1.5)),+ );+ for (let channel = 0; channel < 3; channel++) {+ if (effect === "Dither") {+ pixels[offset + channel] = dot[channel];+ } else {+ const texture =+ color[channel] * coverage + paper * (1 - coverage);+ pixels[offset + channel] = Math.floor(+ source[offset + channel] * 0.6 + texture * 0.4,+ );+ }+ }+ }+ }+ }+ }+ return pixels;+}diff --git a/studio/frontend/src/features/chat-background/image.ts b/studio/frontend/src/features/chat-background/image.tsnew file mode 100644index 00000000000..9030713f086--- /dev/null+++ b/studio/frontend/src/features/chat-background/image.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: AGPL-3.0-only+export function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob> {+ return new Promise((resolve, reject) =>+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error("decode"))),+ "image/png",+ ),+ );+}+export async function decodeImage(blob: Blob): Promise<{+ source: CanvasImageSource;+ width: number;+ height: number;+ close: () => void;+}> {+ if (typeof createImageBitmap === "function") {+ const image = await createImageBitmap(blob);+ return {+ source: image,+ width: image.width,+ height: image.height,+ close: () => image.close(),+ };+ }+ const url = URL.createObjectURL(blob),+ image = new Image();+ image.src = url;+ try {+ await image.decode();+ return {+ source: image,+ width: image.naturalWidth,+ height: image.naturalHeight,+ close: () => URL.revokeObjectURL(url),+ };+ } catch (error) {+ URL.revokeObjectURL(url);+ throw error;+ }+}diff --git a/studio/frontend/src/features/chat-background/index.ts b/studio/frontend/src/features/chat-background/index.tsnew file mode 100644index 00000000000..74a8f04cf3b--- /dev/null+++ b/studio/frontend/src/features/chat-background/index.ts@@ -0,0 +1,4 @@+// SPDX-License-Identifier: AGPL-3.0-only+export { ChatBackground } from "./mount";+export { BACKGROUND_ON_ALL_PAGES } from "./model";+export { resetChatBackground, useBackgroundStore } from "./storage";diff --git a/studio/frontend/src/features/chat-background/model.ts b/studio/frontend/src/features/chat-background/model.tsnew file mode 100644index 00000000000..e6d2207cb1b--- /dev/null+++ b/studio/frontend/src/features/chat-background/model.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++// Enable to restore wallpaper on every main workspace page. The sidebar stays solid.+export const BACKGROUND_ON_ALL_PAGES = false;++export const EFFECTS = [+ "None",+ "Dither",+ "ASCII",+ "Halftone",+ "Scanlines",+] as const;+export type BackgroundEffect = (typeof EFFECTS)[number];+export const IMAGE_SIZING = [+ "cover",+ "contain",+ "stretch",+ "original",+] as const;+export type ImageSizing = (typeof IMAGE_SIZING)[number];+export const POSITIONS = [+ "0% 0%",+ "50% 0%",+ "100% 0%",+ "0% 50%",+ "50% 50%",+ "100% 50%",+ "0% 100%",+ "50% 100%",+ "100% 100%",+] as const;+export const DEFAULT_ADJUSTMENTS = {+ effect: "None" as BackgroundEffect,+ visibility: 70,+ blur: 0,+ fade: true,+ outline: true,+ sizing: "cover" as ImageSizing,+ zoom: 100,+ position: "50% 50%",+};+export type BackgroundAdjustments = typeof DEFAULT_ADJUSTMENTS;+export type ChatBackgroundValue = BackgroundAdjustments & { blob: Blob };+export type BackgroundError =+ | "storage"+ | "file"+ | "dimensions"+ | "decode"+ | "effect";+export const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;+export const MAX_PIXELS = 40_000_000;+export const MAX_EDGE = 2048;+export function sanitizeAdjustments(+ input: Partial<BackgroundAdjustments>,+): BackgroundAdjustments {+ const bounded = (v: unknown, max: number, fallback: number) =>+ typeof v === "number" && Number.isFinite(v)+ ? Math.max(0, Math.min(max, Math.round(v)))+ : fallback;+ return {+ effect: EFFECTS.includes(input.effect as BackgroundEffect)+ ? input.effect!+ : "None",+ visibility: bounded(input.visibility, 100, 70),+ blur: bounded(input.blur, 20, 0),+ fade: typeof input.fade === "boolean" ? input.fade : true,+ outline: typeof input.outline === "boolean" ? input.outline : true,+ sizing: IMAGE_SIZING.includes(input.sizing as ImageSizing)+ ? input.sizing!+ : "cover",+ zoom: Math.max(100, bounded(input.zoom, 300, 100)),+ position: POSITIONS.includes(input.position as (typeof POSITIONS)[number])+ ? input.position!+ : "50% 50%",+ };+}+export function validUpload(file: Pick<File, "type" | "size">): boolean {+ return (+ file.size > 0 &&+ file.size <= MAX_UPLOAD_BYTES &&+ ["image/jpeg", "image/png", "image/webp"].includes(file.type)+ );+}+export function normalizedSize(+ width: number,+ height: number,+): [number, number] {+ if (+ width < 1 ||+ height < 1 ||+ !Number.isFinite(width * height) ||+ width * height > MAX_PIXELS+ )+ throw new Error("dimensions");+ const scale = Math.min(1, MAX_EDGE / Math.max(width, height));+ return [+ Math.max(1, Math.round(width * scale)),+ Math.max(1, Math.round(height * scale)),+ ];+}diff --git a/studio/frontend/src/features/chat-background/mount.tsx b/studio/frontend/src/features/chat-background/mount.tsxnew file mode 100644index 00000000000..3e007ebf00d--- /dev/null+++ b/studio/frontend/src/features/chat-background/mount.tsx@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-only+import { lazy, Suspense } from "react";+import { useChatBackground } from "./storage";+const Renderer = lazy(() =>+ import("./background").then((module) => ({ default: module.ChatBackground })),+);+export function ChatBackground({+ active = true,+}: { active?: boolean }) {+ const { value } = useChatBackground();+ if (!active || !value) return null;+ return (+ <Suspense fallback={null}>+ <Renderer active={active} />+ </Suspense>+ );+}diff --git a/studio/frontend/src/features/chat-background/render.ts b/studio/frontend/src/features/chat-background/render.tsnew file mode 100644index 00000000000..0fef4fe84f9--- /dev/null+++ b/studio/frontend/src/features/chat-background/render.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: AGPL-3.0-only+import { canvasBlob, decodeImage } from "./image";+import type { BackgroundEffect } from "./model";++type Job = { promise: Promise<Blob>; release: () => void };+const cache = new WeakMap<Blob, Map<string, Blob>>();+const jobs = new WeakMap<+ Blob,+ Map<string, { promise: Promise<Blob>; users: number; cancel: () => void }>+>();+/** Shared by chat and previews: the last release cancels pixel work; blobs are cached, never URLs. */+export function acquireRender(+ blob: Blob,+ effect: BackgroundEffect,+ light: boolean,+): Job {+ if (effect === "None")+ return { promise: Promise.resolve(blob), release: () => {} };+ const key = `${effect}:${effect === "Dither" ? false : light}`;+ const cached = cache.get(blob)?.get(key);+ if (cached) return { promise: Promise.resolve(cached), release: () => {} };+ const pending = jobs.get(blob) ?? new Map();+ jobs.set(blob, pending);+ let entry = pending.get(key);+ if (!entry) {+ let cancelled = false,+ worker: Worker | undefined,+ rejectJob: (reason: Error) => void = () => {};+ const promise = new Promise<Blob>((resolve, reject) => {+ rejectJob = reject;+ void (async () => {+ const decoded = await decodeImage(blob);+ const canvas = document.createElement("canvas");+ canvas.width = decoded.width;+ canvas.height = decoded.height;+ const ctx = canvas.getContext("2d", { willReadFrequently: true });+ try {+ if (cancelled) return;+ if (!ctx) throw new Error("effect");+ ctx.drawImage(decoded.source, 0, 0);+ } finally {+ decoded.close();+ }+ if (cancelled) return;+ const pixels = ctx!.getImageData(+ 0,+ 0,+ canvas.width,+ canvas.height,+ ).data;+ worker = new Worker(new URL("./worker.ts", import.meta.url), {+ type: "module",+ });+ worker.onerror = () => reject(new Error("effect"));+ worker.onmessage = ({+ data,+ }: MessageEvent<{ pixels?: Uint8ClampedArray; error?: boolean }>) => {+ worker?.terminate();+ if (cancelled) return;+ if (!data.pixels) {+ reject(new Error("effect"));+ return;+ }+ ctx!.putImageData(+ new ImageData(+ new Uint8ClampedArray(data.pixels),+ canvas.width,+ canvas.height,+ ),+ 0,+ 0,+ );+ void canvasBlob(canvas).then(resolve, reject);+ };+ worker.postMessage(+ { pixels, width: canvas.width, height: canvas.height, effect, light },+ [pixels.buffer],+ );+ })().catch(reject);+ })+ .then((result) => {+ if (!cancelled) {+ const images = cache.get(blob) ?? new Map();+ images.set(key, result);+ if (images.size > 4) images.delete(images.keys().next().value!);+ cache.set(blob, images);+ }+ return result;+ })+ .finally(() => {+ worker?.terminate();+ if (pending.get(key)?.promise === promise) pending.delete(key);+ });+ entry = {+ promise,+ users: 0,+ cancel: () => {+ cancelled = true;+ worker?.terminate();+ rejectJob(new Error("cancelled"));+ },+ };+ pending.set(key, entry);+ }+ entry.users++;+ let released = false;+ return {+ promise: entry.promise,+ release: () => {+ if (released) return;+ released = true;+ if (--entry!.users === 0 && pending.get(key) === entry) {+ pending.delete(key);+ entry!.cancel();+ }+ },+ };+}diff --git a/studio/frontend/src/features/chat-background/storage.ts b/studio/frontend/src/features/chat-background/storage.tsnew file mode 100644index 00000000000..e9b5ee74f3f--- /dev/null+++ b/studio/frontend/src/features/chat-background/storage.ts@@ -0,0 +1,133 @@+// SPDX-License-Identifier: AGPL-3.0-only+import Dexie from "dexie";+import { useEffect } from "react";+import { create } from "zustand";+import { accountDatabaseName } from "@/lib/account-transition";+import {+ sanitizeAdjustments,+ type ChatBackgroundValue,+ type BackgroundAdjustments,+ type BackgroundError,+} from "./model";++export const useBackgroundStore = create<{+ value: ChatBackgroundValue | null;+ error: BackgroundError | null;+ ready: boolean;+ busy: boolean;+}>(() => ({ value: null, error: null, ready: false, busy: false }));+let database: Dexie | undefined;+let account = "";+let revision = 0;+let committed: ChatBackgroundValue | null = null;+let writes: Promise<unknown> = Promise.resolve();+let hydration: Promise<void> | undefined;+function currentDatabase() {+ const name = accountDatabaseName("unsloth-chat-background");+ if (!database || account !== name) {+ database?.close();+ account = name;+ revision++;+ database = new Dexie(name);+ database.version(1).stores({ backgrounds: "id" });+ hydration = undefined;+ committed = null;+ writes = Promise.resolve();+ useBackgroundStore.setState({+ value: null,+ error: null,+ ready: false,+ busy: false,+ });+ }+ return database;+}+export function hydrateBackground(): Promise<void> {+ const db = currentDatabase();+ if (!hydration) {+ const ticket = revision;+ hydration = db+ .table("backgrounds")+ .get("current")+ .then((row) => {+ if (ticket !== revision) return;+ committed =+ row?.value?.blob instanceof Blob+ ? { ...sanitizeAdjustments(row.value), blob: row.value.blob }+ : null;+ useBackgroundStore.setState({ value: committed, ready: true });+ })+ .catch(() => {+ if (ticket === revision)+ useBackgroundStore.setState({ error: "storage", ready: true });+ });+ }+ return hydration;+}+export function useChatBackground() {+ useEffect(() => {+ void hydrateBackground();+ }, []);+ return useBackgroundStore();+}+export function setBackgroundError(error: BackgroundError) {+ useBackgroundStore.setState({ error });+}+async function persist(+ value: ChatBackgroundValue | null,+ optimistic: boolean,+): Promise<boolean> {+ const db = currentDatabase();+ const ticket = ++revision;+ if (optimistic) useBackgroundStore.setState({ value, error: null });+ const write = writes.then(async () => {+ if (value) await db.table("backgrounds").put({ id: "current", value });+ else await db.table("backgrounds").delete("current");+ if (db === database) committed = value;+ });+ writes = write.catch(() => undefined);+ try {+ await write;+ if (ticket === revision)+ useBackgroundStore.setState({ value, error: null, ready: true });+ return true;+ } catch {+ if (ticket === revision)+ useBackgroundStore.setState({+ value: committed,+ error: "storage",+ ready: true,+ });+ return false;+ }+}+export function patchBackground(patch: Partial<BackgroundAdjustments>) {+ const value = useBackgroundStore.getState().value;+ if (value)+ void persist(+ { ...value, ...sanitizeAdjustments({ ...value, ...patch }) },+ true,+ );+}+let uploadTicket = 0;+export function beginBackgroundUpload() {+ useBackgroundStore.setState({ busy: true, error: null });+ return ++uploadTicket;+}+export async function finishBackgroundUpload(+ ticket: number,+ value: ChatBackgroundValue,+) {+ if (ticket !== uploadTicket) return;+ await persist(value, false);+ if (ticket === uploadTicket) useBackgroundStore.setState({ busy: false });+}+export function failBackgroundUpload(ticket: number, error: BackgroundError) {+ if (ticket === uploadTicket)+ useBackgroundStore.setState({ busy: false, error });+}+export async function resetChatBackground(): Promise<boolean> {+ uploadTicket++;+ useBackgroundStore.setState({ busy: false });+ return persist(null, false);+}diff --git a/studio/frontend/src/features/chat-background/worker.ts b/studio/frontend/src/features/chat-background/worker.tsnew file mode 100644index 00000000000..799f9598f32--- /dev/null+++ b/studio/frontend/src/features/chat-background/worker.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: AGPL-3.0-only+import { renderEffect } from "./effects";+import type { BackgroundEffect } from "./model";+// Main thread decodes; only the pixel transform runs here (no OffscreenCanvas needed).+self.onmessage = ({+ data,+}: MessageEvent<{+ pixels: Uint8ClampedArray;+ width: number;+ height: number;+ effect: BackgroundEffect;+ light: boolean;+}>) => {+ try {+ const pixels = renderEffect(+ data.pixels,+ data.width,+ data.height,+ data.effect,+ data.light,+ );+ self.postMessage({ pixels }, { transfer: [pixels.buffer] });+ } catch {+ self.postMessage({ error: true });+ }+};diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 4421c909259..8e87bb81b35 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2193,7 +2193,8 @@ function ProjectLanding({</div>) : (<div- className="flex min-h-0 min-w-0 flex-1 basis-0 overflow-y-auto px-5"+ data-wallpaper-reading-surface=""+ className="relative flex min-h-0 min-w-0 flex-1 basis-0 overflow-y-auto px-5"style={{["--thread-max-width" as string]: "48rem",@@ -4573,7 +4574,7 @@ export function ChatPage({<ChatComposerFocusableContext.Providervalue={modelConfigRequest === null && !handoffOwnsPicker}>- <div className="flex min-h-0 min-w-0 flex-1 basis-0 overflow-hidden bg-background">+ <div data-chat-page-root="" className="flex min-h-0 min-w-0 flex-1 basis-0 overflow-hidden bg-background">{/* Portaled surfaces escape the hidden wrapper, so gate them on `active`. */}{active && <GuidedTour {...tour.tourProps} />}{/* One app-level mount driven by global state, or Compare's composers each render a copy. */}@@ -4608,7 +4609,7 @@ export function ChatPage({"right-[var(--thread-scrollbar-gutter,10px)] left-auto w-auto bg-transparent pl-0 pr-[calc(0.5rem*var(--ui-space-scale,1)+var(--studio-chat-header-right-inset,var(--studio-window-control-inset,0px)))]",)}>- <div className="group/chat-model-controls pointer-events-auto flex min-w-0 items-center gap-1">+ <div data-wallpaper-chrome-controls="" className="group/chat-model-controls pointer-events-auto flex min-w-0 items-center gap-1">{isTauri && !isMobile && !pinned && view.mode !== "compare" && (<Buttontype="button"@@ -4743,7 +4744,7 @@ export function ChatPage({</div>) : null}</div>- <div className="pointer-events-auto ml-auto flex min-w-min max-w-max grow basis-0 items-center gap-1 *:shrink-0">+ <div data-wallpaper-chrome-controls="" className="pointer-events-auto ml-auto flex min-w-min max-w-max grow basis-0 items-center gap-1 *:shrink-0">{showContextWindowUsage &&(view.mode === "single" ||(view.mode === "project" && activeThreadId != null)) &&diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsxindex 3580518d4dc..a4a03fb93b2 100644--- a/studio/frontend/src/features/export/export-page.tsx+++ b/studio/frontend/src/features/export/export-page.tsx@@ -1175,7 +1175,7 @@ export function ExportPage() {}, [showPanel]);return (- <div className="flex min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] flex-col bg-background">+ <div data-wallpaper-page-canvas="" className="flex min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] flex-col bg-background"><main className="mx-auto flex w-full max-w-[calc(1180px*var(--ui-space-scale,1))] 3xl:max-w-[calc(1440px*var(--ui-space-scale,1))] 4xl:max-w-[calc(1760px*var(--ui-space-scale,1))] flex-col gap-7 px-5 pb-20 pt-8 max-sm:px-4 sm:px-9"><GuidedTour {...tour.tourProps} />diff --git a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsxindex 94fea7a8243..c5cb782447b 100644--- a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx+++ b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { resetChatBackground, useBackgroundStore } from "@/features/chat-background";import { Button } from "@/components/ui/button";import {Command,@@ -1026,7 +1027,9 @@ export function ResetCustomizationButton() {const resetAll = useAppearanceCustomStore((s) => s.resetAll);const interfaceScale = useInterfaceScaleStore((s) => s.scale);const resetInterfaceScale = useInterfaceScaleStore((s) => s.reset);+ const background = useBackgroundStore((s) => s.value);const pristine =+ background === null &&isDefaultCustomization(customization) &&interfaceScale === INTERFACE_SCALE_RANGE.default;return (@@ -1036,6 +1039,7 @@ export function ResetCustomizationButton() {size="sm"disabled={pristine}onClick={() => {+ void resetChatBackground();resetAll();resetInterfaceScale();}}diff --git a/studio/frontend/src/features/settings/components/settings-section.tsx b/studio/frontend/src/features/settings/components/settings-section.tsxindex 6f17b8af138..d8cd257e51b 100644--- a/studio/frontend/src/features/settings/components/settings-section.tsx+++ b/studio/frontend/src/features/settings/components/settings-section.tsx@@ -12,11 +12,14 @@ export function SettingsSection({ref,hideHeading = false,action,+ actionAlign,danger = false,}: {title: string;/** Control shown beside the heading, e.g. Refresh. */action?: ReactNode;+ /** Align an action’s top edge with the heading’s visible text. */+ actionAlign?: "text";hideHeading?: boolean;/** Danger zone: a divider above the heading sets it apart from the sections before it. */danger?: boolean;@@ -39,15 +42,20 @@ export function SettingsSection({<divclassName={cn("flex justify-between gap-3",- description ? "items-start" : "items-center",+ description || actionAlign === "text" ? "items-start" : "items-center",)}><h2 className="settings-heading text-base font-semibold font-heading">{title}</h2>- {description ? (+ {description || actionAlign === "text" ? (// Top edge on the h2's cap top (text-base at leading 1.5; Hellix: 0.372em).- <div className="mt-[calc(var(--text-base)*0.372)] shrink-0">+ <div+ className={cn(+ "mt-[calc(var(--text-base)*0.372)]",+ actionAlign === "text" ? "min-w-0 flex-1" : "shrink-0",+ )}+ >{action}</div>) : (diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 5b2c4b7ec54..f97724c72d6 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -58,6 +58,15 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.profile.stats.longestStreak",],appearance: [+ "chatBackground.title",+ "chatBackground.fade",+ "chatBackground.sizing",+ "chatBackground.zoom",+ "chatBackground.outline",+ "chatBackground.effect",+ "chatBackground.visibility",+ "chatBackground.blur",+ "chatBackground.position","settings.appearance.theme.label","settings.appearance.palette.label","settings.appearance.trickOrTreat.label",diff --git a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx b/studio/frontend/src/features/settings/tabs/appearance-tab.tsxindex b827fe0794d..8e37e81d453 100644--- a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx@@ -1,6 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+// Keep the background settings UI in this lazy tab, outside the chat startup barrel.+// eslint-disable-next-line no-restricted-imports+import { ChatBackgroundControls } from "@/features/chat-background/controls";import { useEffect, useRef } from "react";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";@@ -206,6 +209,7 @@ export function AppearanceTab() {</SettingsRow></SettingsSection>+ <ChatBackgroundControls /><SettingsSection title={t("settings.appearance.custom.preferencesTitle")}><SettingsRow label={t("settings.appearance.custom.uiFont.label")}><div className={FONT_CONTROL_CLASS}>diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 4b09873f2e3..a56b151b55c 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { resetChatBackground } from "@/features/chat-background";import { Button } from "@/components/ui/button";import {Dialog,@@ -34,7 +35,7 @@ import {type NotificationChannel,} from "@/hooks/use-notification-frequency";import { useHfTokenValidation } from "@/hooks";-import { LOCALE_STORAGE_KEY, type TranslationKey, useT } from "@/i18n";+import { LOCALE_STORAGE_KEY, getLocale, translate, type TranslationKey, useT } from "@/i18n";import { isTauri } from "@/lib/api-base";import {SPELLCHECK_STORAGE_KEY,@@ -199,7 +200,11 @@ const PREFS_KEYS: string[] = [// Set by resetAllPrefs so the unmount commit skips writing back the in-memory draft.let resetInProgress = false;-function resetAllPrefs() {+async function resetAllPrefs() {+ if (!(await resetChatBackground())) {+ toast.error(translate("chatBackground.storageError", {}, getLocale()));+ return;+ }resetInProgress = true;for (const key of PREFS_KEYS) {try {diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsxindex 5d892308359..aa561664471 100644--- a/studio/frontend/src/features/studio/studio-page.tsx+++ b/studio/frontend/src/features/studio/studio-page.tsx@@ -177,7 +177,7 @@ export function StudioPage(): ReactElement {const showHistoryBack = activeTab === "history" && !!selectedHistoryRunId;return (- <div className="flex h-full min-h-0 flex-col bg-background">+ <div data-wallpaper-page-canvas="" className="flex h-full min-h-0 flex-col bg-background"><Tabsvalue={activeTab}onValueChange={(value) => handleTabChange(value as TrainSubTab)}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 227b0d682c4..770b5c01cff 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const ar = {+ chatBackground: {+ noBackground: "بدون خلفية",+ sizing: "تحجيم الصورة",+ fill: "ملء",+ fit: "احتواء",+ stretch: "تمديد",+ original: "الحجم الأصلي",+ zoom: "تكبير",+ outline: "إطار حقل الرسالة",+ fade: "تلاشي إلى الخلفية",+ title: "صورة الخلفية",+ description: "صورة محلية لمساحة عملك. JPEG أو PNG أو WebP، حتى 20 MiB. يبقى النص مقروءًا تلقائيًا.",+ upload: "رفع صورة",+ replace: "استبدال الصورة",+ remove: "إزالة الخلفية",+ reset: "إعادة ضبط التعديلات",+ effect: "التأثير",+ none: "بلا",+ dither: "تنقيط",+ ascii: "ASCII",+ halftone: "نصف نغمة",+ scanlines: "خطوط المسح",+ visibility: "الظهور",+ blur: "تمويه الصورة",+ position: "الموضع",+ positionValue: "أفقي {x}%، عمودي {y}%",+ newChat: "دردشة جديدة",+ conversation: "محادثة",+ prompt: "ماذا تود استكشافه؟",+ response: "تبقى محادثتك واضحة فوق الخلفية.",+ storageError: "تعذر حفظ الخلفية. تحقق من مساحة تخزين المتصفح.",+ fileError: "اختر صورة JPEG أو PNG أو WebP أصغر من 20 MiB.",+ dimensionsError: "اختر صورة أصغر من 40 ميغابكسل.",+ decodeError: "تعذرت قراءة الصورة. جرّب ملفًا آخر.",+ effectError: "تعذر إنشاء التأثير. اختر بلا أو صورة أخرى.",+ },+linkMenu: {openInBrowser: "فتح في متصفح Unsloth",openExternal: "فتح في متصفح خارجي",diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.tsindex 18381538526..1e83b2ab605 100644--- a/studio/frontend/src/i18n/locales/cs.ts+++ b/studio/frontend/src/i18n/locales/cs.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const cs = {+ chatBackground: {+ noBackground: "Bez pozadí",+ sizing: "Velikost obrázku",+ fill: "Vyplnit",+ fit: "Přizpůsobit",+ stretch: "Roztáhnout",+ original: "Původní velikost",+ zoom: "Přiblížení",+ outline: "Obrys pole zprávy",+ fade: "Prolnout do pozadí",+ title: "Obrázek na pozadí",+ description: "Místní obrázek pro pracovní prostor. JPEG, PNG nebo WebP, až 20 MiB. Text automaticky zůstává čitelný.",+ upload: "Nahrát obrázek",+ replace: "Nahradit obrázek",+ remove: "Odebrat pozadí",+ reset: "Obnovit úpravy",+ effect: "Efekt",+ none: "Žádný",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Polotón",+ scanlines: "Skenovací řádky",+ visibility: "Viditelnost",+ blur: "Rozmazání obrázku",+ position: "Pozice",+ positionValue: "Vodorovně {x} %, svisle {y} %",+ newChat: "Nový chat",+ conversation: "Konverzace",+ prompt: "Co chcete prozkoumat?",+ response: "Konverzace zůstává na pozadí čitelná.",+ storageError: "Pozadí se nepodařilo uložit. Zkontrolujte dostupné úložiště prohlížeče.",+ fileError: "Vyberte obrázek JPEG, PNG nebo WebP menší než 20 MiB.",+ dimensionsError: "Vyberte obrázek menší než 40 megapixelů.",+ decodeError: "Obrázek se nepodařilo dekódovat. Zkuste jiný soubor.",+ effectError: "Efekt se nepodařilo vykreslit. Zvolte Žádný nebo jiný obrázek.",+ },linkMenu: {openInBrowser: "Otevřít v prohlížeči Unsloth",openExternal: "Otevřít v externím prohlížeči",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex eb7a48e9176..e1ebbc46201 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const de = {+ chatBackground: {+ noBackground: "Kein Hintergrund",+ sizing: "Bildskalierung",+ fill: "Ausfüllen",+ fit: "Einpassen",+ stretch: "Strecken",+ original: "Originalgröße",+ zoom: "Zoom",+ outline: "Umrandung des Eingabefelds",+ fade: "Zum Hintergrund ausblenden",+ title: "Hintergrundbild",+ description: "Ein lokales Bild für deinen Arbeitsbereich. JPEG, PNG oder WebP, bis zu 20 MiB. Text bleibt automatisch lesbar.",+ upload: "Bild hochladen",+ replace: "Bild ersetzen",+ remove: "Hintergrund entfernen",+ reset: "Anpassungen zurücksetzen",+ effect: "Effekt",+ none: "Keiner",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Halbton",+ scanlines: "Scanlinien",+ visibility: "Sichtbarkeit",+ blur: "Bildunschärfe",+ position: "Position",+ positionValue: "Horizontal {x} %, vertikal {y} %",+ newChat: "Neuer Chat",+ conversation: "Unterhaltung",+ prompt: "Was möchtest du erkunden?",+ response: "Deine Unterhaltung bleibt vor dem Hintergrund gut lesbar.",+ storageError: "Der Hintergrund konnte nicht gespeichert werden. Prüfe den Browserspeicher.",+ fileError: "Wähle ein JPEG-, PNG- oder WebP-Bild unter 20 MiB.",+ dimensionsError: "Wähle ein Bild mit weniger als 40 Megapixeln.",+ decodeError: "Das Bild konnte nicht gelesen werden. Versuche eine andere Datei.",+ effectError: "Der Effekt konnte nicht erstellt werden. Wähle Keiner oder ein anderes Bild.",+ },+linkMenu: {openInBrowser: "Im Unsloth-Browser öffnen",openExternal: "Im externen Browser öffnen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 59b3c355c99..87958cda7c5 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2,6 +2,43 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export const en = {+ chatBackground: {+ noBackground: "No background",+ sizing: "Image sizing",+ fill: "Fill",+ fit: "Fit",+ stretch: "Stretch",+ original: "Original size",+ zoom: "Zoom",+ outline: "Composer outline",+ fade: "Fade to background",+ title: "Background image",+ description: "A local image for your workspace. JPEG, PNG or WebP, up to 20 MiB. Text stays readable automatically.",+ upload: "Upload image",+ replace: "Replace image",+ remove: "Remove background",+ reset: "Reset adjustments",+ effect: "Effect",+ none: "None",+ dither: "Dither",+ ascii: "ASCII",+ halftone: "Halftone",+ scanlines: "Scanlines",+ visibility: "Visibility",+ blur: "Image blur",+ position: "Position",+ positionValue: "Horizontal {x}%, vertical {y}%",+ newChat: "New chat",+ conversation: "Conversation",+ prompt: "What would you like to explore?",+ response: "Your conversation stays clear over the background.",+ storageError: "Could not save the background. Check available browser storage.",+ fileError: "Choose a JPEG, PNG or WebP image under 20 MiB.",+ dimensionsError: "Choose an image smaller than 40 megapixels.",+ decodeError: "Could not decode this image. Try another file.",+ effectError: "Could not render the effect. Try None or choose another image.",+ },+linkMenu: {openInBrowser: "Open in Unsloth browser",openExternal: "Open in external browser",diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.tsindex 9986efacc10..9b4108e4ad1 100644--- a/studio/frontend/src/i18n/locales/es-419.ts+++ b/studio/frontend/src/i18n/locales/es-419.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const es419 = {+ chatBackground: {+ noBackground: "Sin fondo",+ sizing: "Tamaño de imagen",+ fill: "Rellenar",+ fit: "Ajustar",+ stretch: "Estirar",+ original: "Tamaño original",+ zoom: "Zoom",+ outline: "Contorno del campo de mensaje",+ fade: "Desvanecer hacia el fondo",+ title: "Imagen de fondo",+ description: "Una imagen local para tu espacio de trabajo. JPEG, PNG o WebP, hasta 20 MiB. El texto permanece legible automáticamente.",+ upload: "Subir imagen",+ replace: "Reemplazar imagen",+ remove: "Quitar fondo",+ reset: "Restablecer ajustes",+ effect: "Efecto",+ none: "Ninguno",+ dither: "Tramado",+ ascii: "ASCII",+ halftone: "Semitono",+ scanlines: "Líneas de barrido",+ visibility: "Visibilidad",+ blur: "Desenfoque de imagen",+ position: "Posición",+ positionValue: "Horizontal {x} %, vertical {y} %",+ newChat: "Nuevo chat",+ conversation: "Conversación",+ prompt: "¿Qué te gustaría explorar?",+ response: "Tu conversación sigue siendo legible sobre el fondo.",+ storageError: "No se pudo guardar el fondo. Comprueba el almacenamiento del navegador.",+ fileError: "Elige una imagen JPEG, PNG o WebP de menos de 20 MiB.",+ dimensionsError: "Elige una imagen de menos de 40 megapíxeles.",+ decodeError: "No se pudo leer esta imagen. Prueba otro archivo.",+ effectError: "No se pudo generar el efecto. Elige Ninguno u otra imagen.",+ },+linkMenu: {openInBrowser: "Abrir en el navegador de Unsloth",openExternal: "Abrir en el navegador externo",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 11285d9f3e3..3f60e94be5d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const es = {+ chatBackground: {+ noBackground: "Sin fondo",+ sizing: "Tamaño de imagen",+ fill: "Rellenar",+ fit: "Ajustar",+ stretch: "Estirar",+ original: "Tamaño original",+ zoom: "Zoom",+ outline: "Contorno del campo de mensaje",+ fade: "Desvanecer hacia el fondo",+ title: "Imagen de fondo",+ description: "Una imagen local para tu espacio de trabajo. JPEG, PNG o WebP, hasta 20 MiB. El texto permanece legible automáticamente.",+ upload: "Subir imagen",+ replace: "Reemplazar imagen",+ remove: "Quitar fondo",+ reset: "Restablecer ajustes",+ effect: "Efecto",+ none: "Ninguno",+ dither: "Tramado",+ ascii: "ASCII",+ halftone: "Semitono",+ scanlines: "Líneas de barrido",+ visibility: "Visibilidad",+ blur: "Desenfoque de imagen",+ position: "Posición",+ positionValue: "Horizontal {x} %, vertical {y} %",+ newChat: "Nuevo chat",+ conversation: "Conversación",+ prompt: "¿Qué te gustaría explorar?",+ response: "Tu conversación sigue siendo legible sobre el fondo.",+ storageError: "No se pudo guardar el fondo. Comprueba el almacenamiento del navegador.",+ fileError: "Elige una imagen JPEG, PNG o WebP de menos de 20 MiB.",+ dimensionsError: "Elige una imagen de menos de 40 megapíxeles.",+ decodeError: "No se pudo leer esta imagen. Prueba otro archivo.",+ effectError: "No se pudo generar el efecto. Elige Ninguno u otra imagen.",+ },+linkMenu: {openInBrowser: "Abrir en el navegador de Unsloth",openExternal: "Abrir en el navegador externo",diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.tsindex 44efa6f1f42..e634985c58a 100644--- a/studio/frontend/src/i18n/locales/fa.ts+++ b/studio/frontend/src/i18n/locales/fa.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const fa = {+ chatBackground: {+ noBackground: "بدون پسزمینه",+ sizing: "اندازهبندی تصویر",+ fill: "پر کردن",+ fit: "جا دادن",+ stretch: "کشیدن",+ original: "اندازهٔ اصلی",+ zoom: "بزرگنمایی",+ outline: "کادر بخش نوشتن پیام",+ fade: "محو شدن در پسزمینه",+ title: "تصویر پسزمینه",+ description: "یک تصویر محلی برای فضای کاری شما. JPEG، PNG یا WebP، حداکثر 20 MiB. متن بهطور خودکار خوانا میماند.",+ upload: "بارگذاری تصویر",+ replace: "جایگزینی تصویر",+ remove: "حذف پسزمینه",+ reset: "بازنشانی تنظیمات",+ effect: "جلوه",+ none: "هیچکدام",+ dither: "دیتر",+ ascii: "ASCII",+ halftone: "نیمسایه",+ scanlines: "خطوط اسکن",+ visibility: "میزان نمایش",+ blur: "تاری تصویر",+ position: "موقعیت",+ positionValue: "افقی {x}٪، عمودی {y}٪",+ newChat: "گفتگوی جدید",+ conversation: "گفتگو",+ prompt: "میخواهید چه چیزی را بررسی کنید؟",+ response: "متن گفتگو روی پسزمینه خوانا میماند.",+ storageError: "ذخیرهٔ پسزمینه ممکن نشد. فضای ذخیرهسازی مرورگر را بررسی کنید.",+ fileError: "یک تصویر JPEG، PNG یا WebP کوچکتر از 20 MiB انتخاب کنید.",+ dimensionsError: "تصویری کوچکتر از 40 مگاپیکسل انتخاب کنید.",+ decodeError: "رمزگشایی تصویر ممکن نشد. فایل دیگری را امتحان کنید.",+ effectError: "رندر جلوه ممکن نشد. هیچکدام یا تصویر دیگری را انتخاب کنید.",+ },linkMenu: {openInBrowser: "باز کردن در مرورگر Unsloth",openExternal: "باز کردن در مرورگر خارجی",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex af1034e1bb1..f233cb2c9fe 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const fr = {+ chatBackground: {+ noBackground: "Aucun arrière-plan",+ sizing: "Dimensionnement de l’image",+ fill: "Remplir",+ fit: "Ajuster",+ stretch: "Étirer",+ original: "Taille d’origine",+ zoom: "Zoom",+ outline: "Contour du champ de message",+ fade: "Fondu vers l’arrière-plan",+ title: "Image d’arrière-plan",+ description: "Une image locale pour votre espace de travail. JPEG, PNG ou WebP, jusqu’à 20 Mio. Le texte reste automatiquement lisible.",+ upload: "Importer une image",+ replace: "Remplacer l’image",+ remove: "Supprimer l’arrière-plan",+ reset: "Réinitialiser les réglages",+ effect: "Effet",+ none: "Aucun",+ dither: "Tramage",+ ascii: "ASCII",+ halftone: "Demi-teinte",+ scanlines: "Lignes de balayage",+ visibility: "Visibilité",+ blur: "Flou de l’image",+ position: "Position",+ positionValue: "Horizontal {x} %, vertical {y} %",+ newChat: "Nouveau chat",+ conversation: "Conversation",+ prompt: "Que souhaitez-vous explorer ?",+ response: "Votre conversation reste lisible sur l’arrière-plan.",+ storageError: "Impossible d’enregistrer l’arrière-plan. Vérifiez le stockage du navigateur.",+ fileError: "Choisissez une image JPEG, PNG ou WebP de moins de 20 Mio.",+ dimensionsError: "Choisissez une image de moins de 40 mégapixels.",+ decodeError: "Impossible de lire cette image. Essayez un autre fichier.",+ effectError: "Impossible de générer l’effet. Choisissez Aucun ou une autre image.",+ },+linkMenu: {openInBrowser: "Ouvrir dans le navigateur Unsloth",openExternal: "Ouvrir dans le navigateur externe",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 56e1a86fb73..9afbc418cbb 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en";export const he = {+ chatBackground: {+ noBackground: "ללא רקע",+ sizing: "התאמת גודל תמונה",+ fill: "מילוי",+ fit: "התאמה",+ stretch: "מתיחה",+ original: "גודל מקורי",+ zoom: "זום",+ outline: "מסגרת שדה ההודעה",+ fade: "דעיכה אל הרקע",+ title: "תמונת רקע",+ description: "תמונה מקומית לסביבת העבודה שלך. JPEG, PNG או WebP, עד 20 MiB. הטקסט נשאר קריא אוטומטית.",+ upload: "העלאת תמונה",+ replace: "החלפת תמונה",+ remove: "הסרת הרקע",+ reset: "איפוס התאמות",+ effect: "אפקט",+ none: "ללא",+ dither: "דיתור",+ ascii: "ASCII",+ halftone: "חצי גוון",+ scanlines: "קווי סריקה",+ visibility: "נראות",+ blur: "טשטוש תמונה",+ position: "מיקום",+ positionValue: "אופקי {x}%, אנכי {y}%",+ newChat: "צ׳אט חדש",+ conversation: "שיחה",+ prompt: "מה תרצו לחקור?",+ response: "השיחה נשארת ברורה על גבי הרקע.",+ storageError: "לא ניתן לשמור את הרקע. בדקו את שטח האחסון בדפדפן.",+ fileError: "בחרו תמונת JPEG, PNG או WebP קטנה מ־20 MiB.",+ dimensionsError: "בחרו תמונה קטנה מ־40 מגה־פיקסל.",+ decodeError: "לא ניתן לקרוא את התמונה. נסו קובץ אחר.",+ effectError: "לא ניתן ליצור את האפקט. בחרו ללא או תמונה אחרת.",+ },+linkMenu: {openInBrowser: "פתח בדפדפן של Unsloth",openExternal: "פתח בדפדפן חיצוני",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex f15548fa377..c741b55b49d 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const hi = {+ chatBackground: {+ noBackground: "कोई पृष्ठभूमि नहीं",+ sizing: "छवि का आकार",+ fill: "भरें",+ fit: "फ़िट करें",+ stretch: "खींचें",+ original: "मूल आकार",+ zoom: "ज़ूम",+ outline: "संदेश बॉक्स की रूपरेखा",+ fade: "पृष्ठभूमि में फ़ेड करें",+ title: "पृष्ठभूमि छवि",+ description: "आपके कार्यक्षेत्र के लिए एक स्थानीय छवि। JPEG, PNG या WebP, अधिकतम 20 MiB। पाठ अपने आप पढ़ने योग्य रहता है।",+ upload: "छवि अपलोड करें",+ replace: "छवि बदलें",+ remove: "पृष्ठभूमि हटाएँ",+ reset: "समायोजन रीसेट करें",+ effect: "प्रभाव",+ none: "कोई नहीं",+ dither: "डिथर",+ ascii: "ASCII",+ halftone: "हाफ़टोन",+ scanlines: "स्कैनलाइन",+ visibility: "दृश्यता",+ blur: "छवि का धुंधलापन",+ position: "स्थिति",+ positionValue: "क्षैतिज {x}%, लंबवत {y}%",+ newChat: "नई चैट",+ conversation: "बातचीत",+ prompt: "आप क्या जानना चाहेंगे?",+ response: "पृष्ठभूमि पर भी आपकी बातचीत स्पष्ट रहती है।",+ storageError: "पृष्ठभूमि सहेजी नहीं जा सकी। ब्राउज़र का संग्रहण जाँचें।",+ fileError: "20 MiB से छोटी JPEG, PNG या WebP छवि चुनें।",+ dimensionsError: "40 मेगापिक्सेल से छोटी छवि चुनें।",+ decodeError: "छवि पढ़ी नहीं जा सकी। दूसरी फ़ाइल आज़माएँ।",+ effectError: "प्रभाव बनाया नहीं जा सका। कोई नहीं या दूसरी छवि चुनें।",+ },+linkMenu: {openInBrowser: "Unsloth ब्राउज़र में खोलें",openExternal: "बाहरी ब्राउज़र में खोलें",diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.tsindex d029bf2a014..e4469fef521 100644--- a/studio/frontend/src/i18n/locales/id.ts+++ b/studio/frontend/src/i18n/locales/id.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const id = {+ chatBackground: {+ noBackground: "Tanpa latar belakang",+ sizing: "Ukuran gambar",+ fill: "Isi",+ fit: "Sesuaikan",+ stretch: "Regangkan",+ original: "Ukuran asli",+ zoom: "Zoom",+ outline: "Garis tepi kolom pesan",+ fade: "Pudarkan ke latar belakang",+ title: "Gambar latar belakang",+ description: "Gambar lokal untuk ruang kerja Anda. JPEG, PNG, atau WebP, hingga 20 MiB. Teks tetap mudah dibaca secara otomatis.",+ upload: "Unggah gambar",+ replace: "Ganti gambar",+ remove: "Hapus latar belakang",+ reset: "Reset penyesuaian",+ effect: "Efek",+ none: "Tidak ada",+ dither: "Dither",+ ascii: "ASCII",+ halftone: "Halftone",+ scanlines: "Garis pindai",+ visibility: "Visibilitas",+ blur: "Keburaman gambar",+ position: "Posisi",+ positionValue: "Horizontal {x}%, vertikal {y}%",+ newChat: "Chat baru",+ conversation: "Percakapan",+ prompt: "Apa yang ingin Anda jelajahi?",+ response: "Percakapan Anda tetap jelas di atas latar belakang.",+ storageError: "Tidak dapat menyimpan latar belakang. Periksa ruang penyimpanan browser.",+ fileError: "Pilih gambar JPEG, PNG, atau WebP di bawah 20 MiB.",+ dimensionsError: "Pilih gambar di bawah 40 megapiksel.",+ decodeError: "Tidak dapat mendekode gambar ini. Coba file lain.",+ effectError: "Tidak dapat merender efek. Pilih Tidak ada atau gambar lain.",+ },linkMenu: {openInBrowser: "Buka di browser Unsloth",openExternal: "Buka di browser eksternal",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex e74b69863aa..3e625184596 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2,6 +2,43 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export const it = {+ chatBackground: {+ noBackground: "Nessuno sfondo",+ sizing: "Dimensionamento immagine",+ fill: "Riempi",+ fit: "Adatta",+ stretch: "Allunga",+ original: "Dimensioni originali",+ zoom: "Zoom",+ outline: "Bordo del campo messaggio",+ fade: "Sfuma verso lo sfondo",+ title: "Immagine di sfondo",+ description: "Un’immagine locale per il tuo spazio di lavoro. JPEG, PNG o WebP, fino a 20 MiB. Il testo rimane automaticamente leggibile.",+ upload: "Carica immagine",+ replace: "Sostituisci immagine",+ remove: "Rimuovi sfondo",+ reset: "Ripristina regolazioni",+ effect: "Effetto",+ none: "Nessuno",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Mezzitoni",+ scanlines: "Linee di scansione",+ visibility: "Visibilità",+ blur: "Sfocatura immagine",+ position: "Posizione",+ positionValue: "Orizzontale {x}%, verticale {y}%",+ newChat: "Nuova chat",+ conversation: "Conversazione",+ prompt: "Cosa vorresti esplorare?",+ response: "La conversazione rimane leggibile sullo sfondo.",+ storageError: "Impossibile salvare lo sfondo. Controlla lo spazio del browser.",+ fileError: "Scegli un’immagine JPEG, PNG o WebP inferiore a 20 MiB.",+ dimensionsError: "Scegli un’immagine inferiore a 40 megapixel.",+ decodeError: "Impossibile leggere l’immagine. Prova un altro file.",+ effectError: "Impossibile creare l’effetto. Scegli Nessuno o un’altra immagine.",+ },+linkMenu: {openInBrowser: "Apri nel browser di Unsloth",openExternal: "Apri nel browser esterno",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 190ba31d2fd..5339b0663bb 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -6,6 +6,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const ja = {+ chatBackground: {+ noBackground: "背景なし",+ sizing: "画像のサイズ調整",+ fill: "埋める",+ fit: "全体を表示",+ stretch: "引き伸ばす",+ original: "元のサイズ",+ zoom: "ズーム",+ outline: "入力欄の枠線",+ fade: "背景にフェード",+ title: "背景画像",+ description: "ワークスペース用のローカル画像。JPEG、PNG、WebP、最大20 MiB。文字の読みやすさは自動調整されます。",+ upload: "画像をアップロード",+ replace: "画像を置き換え",+ remove: "背景を削除",+ reset: "調整をリセット",+ effect: "エフェクト",+ none: "なし",+ dither: "ディザ",+ ascii: "ASCII",+ halftone: "ハーフトーン",+ scanlines: "走査線",+ visibility: "表示強度",+ blur: "画像のぼかし",+ position: "位置",+ positionValue: "横 {x}%、縦 {y}%",+ newChat: "新しいチャット",+ conversation: "会話",+ prompt: "何を調べたいですか?",+ response: "背景があっても会話は読みやすく表示されます。",+ storageError: "背景を保存できませんでした。ブラウザーの空き容量を確認してください。",+ fileError: "20 MiB未満のJPEG、PNG、WebP画像を選択してください。",+ dimensionsError: "4000万画素未満の画像を選択してください。",+ decodeError: "画像を読み込めませんでした。別のファイルを試してください。",+ effectError: "エフェクトを生成できませんでした。「なし」または別の画像を選択してください。",+ },+linkMenu: {openInBrowser: "Unsloth ブラウザで開く",openExternal: "外部ブラウザで開く",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex de072676285..a15354a772c 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const ko = {+ chatBackground: {+ noBackground: "배경 없음",+ sizing: "이미지 크기 조정",+ fill: "채우기",+ fit: "맞추기",+ stretch: "늘이기",+ original: "원본 크기",+ zoom: "확대",+ outline: "메시지 입력창 테두리",+ fade: "배경으로 페이드",+ title: "배경 이미지",+ description: "작업 공간에 사용할 로컬 이미지입니다. JPEG, PNG 또는 WebP, 최대 20 MiB. 텍스트 가독성은 자동으로 유지됩니다.",+ upload: "이미지 업로드",+ replace: "이미지 교체",+ remove: "배경 제거",+ reset: "조정 초기화",+ effect: "효과",+ none: "없음",+ dither: "디더링",+ ascii: "ASCII",+ halftone: "하프톤",+ scanlines: "주사선",+ visibility: "표시 강도",+ blur: "이미지 흐림",+ position: "위치",+ positionValue: "가로 {x}%, 세로 {y}%",+ newChat: "새 채팅",+ conversation: "대화",+ prompt: "무엇을 알아보고 싶으신가요?",+ response: "배경 위에서도 대화가 선명하게 표시됩니다.",+ storageError: "배경을 저장할 수 없습니다. 브라우저 저장 공간을 확인하세요.",+ fileError: "20 MiB 미만의 JPEG, PNG 또는 WebP 이미지를 선택하세요.",+ dimensionsError: "4천만 화소 미만의 이미지를 선택하세요.",+ decodeError: "이미지를 읽을 수 없습니다. 다른 파일을 시도하세요.",+ effectError: "효과를 생성할 수 없습니다. 없음 또는 다른 이미지를 선택하세요.",+ },+linkMenu: {openInBrowser: "Unsloth 브라우저에서 열기",openExternal: "외부 브라우저에서 열기",diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.tsindex b526ceb8cec..ce3f4b3d660 100644--- a/studio/frontend/src/i18n/locales/nl.ts+++ b/studio/frontend/src/i18n/locales/nl.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const nl = {+ chatBackground: {+ noBackground: "Geen achtergrond",+ sizing: "Afbeeldingsgrootte",+ fill: "Vullen",+ fit: "Passend maken",+ stretch: "Uitrekken",+ original: "Oorspronkelijke grootte",+ zoom: "Zoom",+ outline: "Rand om berichtveld",+ fade: "Vervagen naar achtergrond",+ title: "Achtergrondafbeelding",+ description: "Een lokale afbeelding voor je werkruimte. JPEG, PNG of WebP, tot 20 MiB. Tekst blijft automatisch leesbaar.",+ upload: "Afbeelding uploaden",+ replace: "Afbeelding vervangen",+ remove: "Achtergrond verwijderen",+ reset: "Aanpassingen herstellen",+ effect: "Effect",+ none: "Geen",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Halftoon",+ scanlines: "Scanlijnen",+ visibility: "Zichtbaarheid",+ blur: "Afbeelding vervagen",+ position: "Positie",+ positionValue: "Horizontaal {x}%, verticaal {y}%",+ newChat: "Nieuwe chat",+ conversation: "Gesprek",+ prompt: "Wat wil je ontdekken?",+ response: "Je gesprek blijft goed leesbaar op de achtergrond.",+ storageError: "Kan de achtergrond niet opslaan. Controleer de beschikbare browseropslag.",+ fileError: "Kies een JPEG-, PNG- of WebP-afbeelding kleiner dan 20 MiB.",+ dimensionsError: "Kies een afbeelding kleiner dan 40 megapixels.",+ decodeError: "Kan deze afbeelding niet decoderen. Probeer een ander bestand.",+ effectError: "Kan het effect niet weergeven. Kies Geen of een andere afbeelding.",+ },linkMenu: {openInBrowser: "Openen in Unsloth-browser",openExternal: "Openen in externe browser",diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.tsindex c4c57145b48..aea28aaef2d 100644--- a/studio/frontend/src/i18n/locales/pl.ts+++ b/studio/frontend/src/i18n/locales/pl.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const pl = {+ chatBackground: {+ noBackground: "Brak tła",+ sizing: "Skalowanie obrazu",+ fill: "Wypełnij",+ fit: "Dopasuj",+ stretch: "Rozciągnij",+ original: "Oryginalny rozmiar",+ zoom: "Powiększenie",+ outline: "Obramowanie pola wiadomości",+ fade: "Przenikanie do tła",+ title: "Obraz tła",+ description: "Lokalny obraz dla przestrzeni roboczej. JPEG, PNG lub WebP, do 20 MiB. Tekst automatycznie pozostaje czytelny.",+ upload: "Prześlij obraz",+ replace: "Zastąp obraz",+ remove: "Usuń tło",+ reset: "Resetuj ustawienia",+ effect: "Efekt",+ none: "Brak",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Raster",+ scanlines: "Linie skanowania",+ visibility: "Widoczność",+ blur: "Rozmycie obrazu",+ position: "Pozycja",+ positionValue: "Poziomo {x}%, pionowo {y}%",+ newChat: "Nowy czat",+ conversation: "Rozmowa",+ prompt: "Co chcesz odkryć?",+ response: "Rozmowa pozostaje czytelna na tle.",+ storageError: "Nie udało się zapisać tła. Sprawdź dostępne miejsce w pamięci przeglądarki.",+ fileError: "Wybierz obraz JPEG, PNG lub WebP mniejszy niż 20 MiB.",+ dimensionsError: "Wybierz obraz mniejszy niż 40 megapikseli.",+ decodeError: "Nie udało się zdekodować obrazu. Spróbuj innego pliku.",+ effectError: "Nie udało się wyrenderować efektu. Wybierz Brak lub inny obraz.",+ },linkMenu: {openInBrowser: "Otwórz w przeglądarce Unsloth",openExternal: "Otwórz w zewnętrznej przeglądarce",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex b476a822742..dc45b073128 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const ptBR = {+ chatBackground: {+ noBackground: "Sem fundo",+ sizing: "Dimensionamento da imagem",+ fill: "Preencher",+ fit: "Ajustar",+ stretch: "Esticar",+ original: "Tamanho original",+ zoom: "Zoom",+ outline: "Contorno do campo de mensagem",+ fade: "Esmaecer para o fundo",+ title: "Imagem de fundo",+ description: "Uma imagem local para seu espaço de trabalho. JPEG, PNG ou WebP, até 20 MiB. O texto permanece legível automaticamente.",+ upload: "Enviar imagem",+ replace: "Substituir imagem",+ remove: "Remover fundo",+ reset: "Redefinir ajustes",+ effect: "Efeito",+ none: "Nenhum",+ dither: "Pontilhamento",+ ascii: "ASCII",+ halftone: "Meio-tom",+ scanlines: "Linhas de varredura",+ visibility: "Visibilidade",+ blur: "Desfoque da imagem",+ position: "Posição",+ positionValue: "Horizontal {x}%, vertical {y}%",+ newChat: "Novo chat",+ conversation: "Conversa",+ prompt: "O que você gostaria de explorar?",+ response: "Sua conversa continua legível sobre o fundo.",+ storageError: "Não foi possível salvar o fundo. Verifique o armazenamento do navegador.",+ fileError: "Escolha uma imagem JPEG, PNG ou WebP menor que 20 MiB.",+ dimensionsError: "Escolha uma imagem menor que 40 megapixels.",+ decodeError: "Não foi possível ler a imagem. Tente outro arquivo.",+ effectError: "Não foi possível criar o efeito. Escolha Nenhum ou outra imagem.",+ },+linkMenu: {openInBrowser: "Abrir no navegador do Unsloth",openExternal: "Abrir no navegador externo",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex b4c775c0f8a..a6e3110cc2f 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const ru = {+ chatBackground: {+ noBackground: "Без фона",+ sizing: "Масштабирование изображения",+ fill: "Заполнить",+ fit: "Вписать",+ stretch: "Растянуть",+ original: "Исходный размер",+ zoom: "Масштаб",+ outline: "Контур поля сообщения",+ fade: "Плавный переход к фону",+ title: "Фоновое изображение",+ description: "Локальное изображение для рабочего пространства. JPEG, PNG или WebP, до 20 МиБ. Текст автоматически остаётся читаемым.",+ upload: "Загрузить изображение",+ replace: "Заменить изображение",+ remove: "Удалить фон",+ reset: "Сбросить настройки",+ effect: "Эффект",+ none: "Нет",+ dither: "Дизеринг",+ ascii: "ASCII",+ halftone: "Полутон",+ scanlines: "Строки развёртки",+ visibility: "Видимость",+ blur: "Размытие изображения",+ position: "Положение",+ positionValue: "По горизонтали {x}%, по вертикали {y}%",+ newChat: "Новый чат",+ conversation: "Переписка",+ prompt: "Что вы хотите изучить?",+ response: "Переписка остаётся хорошо видимой на фоне.",+ storageError: "Не удалось сохранить фон. Проверьте хранилище браузера.",+ fileError: "Выберите изображение JPEG, PNG или WebP меньше 20 МиБ.",+ dimensionsError: "Выберите изображение меньше 40 мегапикселей.",+ decodeError: "Не удалось прочитать изображение. Попробуйте другой файл.",+ effectError: "Не удалось применить эффект. Выберите Нет или другое изображение.",+ },+linkMenu: {openInBrowser: "Открыть в браузере Unsloth",openExternal: "Открыть во внешнем браузере",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 24ee0f184ed..97e60af2ab9 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -2,6 +2,43 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export const sv = {+ chatBackground: {+ noBackground: "Ingen bakgrund",+ sizing: "Bildstorlek",+ fill: "Fyll",+ fit: "Anpassa",+ stretch: "Sträck ut",+ original: "Originalstorlek",+ zoom: "Zoom",+ outline: "Kontur runt meddelandefältet",+ fade: "Tona ut mot bakgrunden",+ title: "Bakgrundsbild",+ description: "En lokal bild för din arbetsyta. JPEG, PNG eller WebP, högst 20 MiB. Texten förblir automatiskt läsbar.",+ upload: "Ladda upp bild",+ replace: "Byt bild",+ remove: "Ta bort bakgrund",+ reset: "Återställ justeringar",+ effect: "Effekt",+ none: "Ingen",+ dither: "Dithering",+ ascii: "ASCII",+ halftone: "Raster",+ scanlines: "Skanningslinjer",+ visibility: "Synlighet",+ blur: "Bildoskärpa",+ position: "Position",+ positionValue: "Horisontellt {x} %, vertikalt {y} %",+ newChat: "Ny chatt",+ conversation: "Konversation",+ prompt: "Vad vill du utforska?",+ response: "Konversationen förblir tydlig mot bakgrunden.",+ storageError: "Det gick inte att spara bakgrunden. Kontrollera webbläsarens lagringsutrymme.",+ fileError: "Välj en JPEG-, PNG- eller WebP-bild under 20 MiB.",+ dimensionsError: "Välj en bild mindre än 40 megapixlar.",+ decodeError: "Det gick inte att läsa bilden. Prova en annan fil.",+ effectError: "Det gick inte att skapa effekten. Välj Ingen eller en annan bild.",+ },+linkMenu: {openInBrowser: "Öppna i Unsloth-webbläsaren",openExternal: "Öppna i extern webbläsare",diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.tsindex 0c5f7489391..e2b32b412ad 100644--- a/studio/frontend/src/i18n/locales/th.ts+++ b/studio/frontend/src/i18n/locales/th.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const th = {+ chatBackground: {+ noBackground: "ไม่มีพื้นหลัง",+ sizing: "การปรับขนาดภาพ",+ fill: "เติมเต็ม",+ fit: "พอดี",+ stretch: "ยืด",+ original: "ขนาดต้นฉบับ",+ zoom: "ซูม",+ outline: "เส้นขอบช่องข้อความ",+ fade: "จางเข้าสู่พื้นหลัง",+ title: "ภาพพื้นหลัง",+ description: "ภาพในเครื่องสำหรับพื้นที่ทำงานของคุณ รองรับ JPEG, PNG หรือ WebP สูงสุด 20 MiB ข้อความจะอ่านง่ายโดยอัตโนมัติ",+ upload: "อัปโหลดภาพ",+ replace: "เปลี่ยนภาพ",+ remove: "ลบพื้นหลัง",+ reset: "รีเซ็ตการปรับแต่ง",+ effect: "เอฟเฟกต์",+ none: "ไม่มี",+ dither: "ดิเทอร์",+ ascii: "ASCII",+ halftone: "ฮาล์ฟโทน",+ scanlines: "เส้นสแกน",+ visibility: "การมองเห็น",+ blur: "ความเบลอของภาพ",+ position: "ตำแหน่ง",+ positionValue: "แนวนอน {x}% แนวตั้ง {y}%",+ newChat: "แชทใหม่",+ conversation: "การสนทนา",+ prompt: "คุณอยากสำรวจอะไร?",+ response: "ข้อความสนทนายังคงอ่านได้ชัดเจนบนพื้นหลัง",+ storageError: "บันทึกพื้นหลังไม่ได้ ตรวจสอบพื้นที่จัดเก็บของเบราว์เซอร์",+ fileError: "เลือกภาพ JPEG, PNG หรือ WebP ที่เล็กกว่า 20 MiB",+ dimensionsError: "เลือกภาพที่เล็กกว่า 40 ล้านพิกเซล",+ decodeError: "ถอดรหัสภาพนี้ไม่ได้ ลองใช้ไฟล์อื่น",+ effectError: "แสดงเอฟเฟกต์ไม่ได้ เลือกไม่มีหรือเลือกภาพอื่น",+ },linkMenu: {openInBrowser: "เปิดในเบราว์เซอร์ Unsloth",openExternal: "เปิดในเบราว์เซอร์ภายนอก",diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.tsindex ea678b81d26..67dd59b959b 100644--- a/studio/frontend/src/i18n/locales/tr.ts+++ b/studio/frontend/src/i18n/locales/tr.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const tr = {+ chatBackground: {+ noBackground: "Arka plan yok",+ sizing: "Görüntü boyutlandırma",+ fill: "Doldur",+ fit: "Sığdır",+ stretch: "Uzat",+ original: "Özgün boyut",+ zoom: "Yakınlaştırma",+ outline: "Mesaj kutusu kenarlığı",+ fade: "Arka plana doğru soldur",+ title: "Arka plan görüntüsü",+ description: "Çalışma alanınız için yerel bir görüntü. JPEG, PNG veya WebP, en fazla 20 MiB. Metin otomatik olarak okunaklı kalır.",+ upload: "Görüntü yükle",+ replace: "Görüntüyü değiştir",+ remove: "Arka planı kaldır",+ reset: "Ayarları sıfırla",+ effect: "Efekt",+ none: "Yok",+ dither: "Dither",+ ascii: "ASCII",+ halftone: "Yarım ton",+ scanlines: "Tarama çizgileri",+ visibility: "Görünürlük",+ blur: "Görüntü bulanıklığı",+ position: "Konum",+ positionValue: "Yatay %{x}, dikey %{y}",+ newChat: "Yeni sohbet",+ conversation: "Sohbet",+ prompt: "Ne keşfetmek istersiniz?",+ response: "Sohbetiniz arka plan üzerinde okunaklı kalır.",+ storageError: "Arka plan kaydedilemedi. Tarayıcının kullanılabilir depolama alanını kontrol edin.",+ fileError: "20 MiB'den küçük bir JPEG, PNG veya WebP görüntüsü seçin.",+ dimensionsError: "40 megapikselden küçük bir görüntü seçin.",+ decodeError: "Görüntünün kodu çözülemedi. Başka bir dosya deneyin.",+ effectError: "Efekt oluşturulamadı. Yok seçeneğini veya başka bir görüntü seçin.",+ },linkMenu: {openInBrowser: "Unsloth tarayıcısında aç",openExternal: "Harici tarayıcıda aç",diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.tsindex 06fe5d41a6c..5ad5e9f9bc1 100644--- a/studio/frontend/src/i18n/locales/uk.ts+++ b/studio/frontend/src/i18n/locales/uk.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const uk = {+ chatBackground: {+ noBackground: "Без тла",+ sizing: "Масштабування зображення",+ fill: "Заповнити",+ fit: "Вписати",+ stretch: "Розтягнути",+ original: "Початковий розмір",+ zoom: "Масштаб",+ outline: "Контур поля повідомлення",+ fade: "Плавний перехід до тла",+ title: "Зображення тла",+ description: "Локальне зображення для робочого простору. JPEG, PNG або WebP, до 20 MiB. Текст автоматично залишається читабельним.",+ upload: "Завантажити зображення",+ replace: "Замінити зображення",+ remove: "Видалити тло",+ reset: "Скинути налаштування",+ effect: "Ефект",+ none: "Немає",+ dither: "Дизеринг",+ ascii: "ASCII",+ halftone: "Напівтони",+ scanlines: "Рядки сканування",+ visibility: "Видимість",+ blur: "Розмиття зображення",+ position: "Позиція",+ positionValue: "По горизонталі {x}%, по вертикалі {y}%",+ newChat: "Новий чат",+ conversation: "Розмова",+ prompt: "Що хочете дослідити?",+ response: "Розмова залишається чіткою на тлі.",+ storageError: "Не вдалося зберегти тло. Перевірте доступне сховище браузера.",+ fileError: "Виберіть зображення JPEG, PNG або WebP розміром до 20 MiB.",+ dimensionsError: "Виберіть зображення менше ніж 40 мегапікселів.",+ decodeError: "Не вдалося декодувати зображення. Спробуйте інший файл.",+ effectError: "Не вдалося відтворити ефект. Виберіть «Немає» або інше зображення.",+ },linkMenu: {openInBrowser: "Відкрити в браузері Unsloth",openExternal: "Відкрити в зовнішньому браузері",diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.tsindex ca7366c6187..ac4d85edc34 100644--- a/studio/frontend/src/i18n/locales/vi.ts+++ b/studio/frontend/src/i18n/locales/vi.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const vi = {+ chatBackground: {+ noBackground: "Không có nền",+ sizing: "Kích thước ảnh",+ fill: "Lấp đầy",+ fit: "Vừa khung",+ stretch: "Kéo giãn",+ original: "Kích thước gốc",+ zoom: "Thu phóng",+ outline: "Viền ô soạn tin",+ fade: "Mờ dần vào nền",+ title: "Ảnh nền",+ description: "Ảnh cục bộ cho không gian làm việc. JPEG, PNG hoặc WebP, tối đa 20 MiB. Văn bản tự động được giữ rõ ràng.",+ upload: "Tải ảnh lên",+ replace: "Thay ảnh",+ remove: "Xóa nền",+ reset: "Đặt lại điều chỉnh",+ effect: "Hiệu ứng",+ none: "Không",+ dither: "Dither",+ ascii: "ASCII",+ halftone: "Bán sắc",+ scanlines: "Đường quét",+ visibility: "Độ hiển thị",+ blur: "Độ mờ ảnh",+ position: "Vị trí",+ positionValue: "Ngang {x}%, dọc {y}%",+ newChat: "Cuộc trò chuyện mới",+ conversation: "Cuộc trò chuyện",+ prompt: "Bạn muốn khám phá điều gì?",+ response: "Nội dung trò chuyện vẫn rõ ràng trên nền.",+ storageError: "Không thể lưu nền. Kiểm tra dung lượng lưu trữ của trình duyệt.",+ fileError: "Chọn ảnh JPEG, PNG hoặc WebP dưới 20 MiB.",+ dimensionsError: "Chọn ảnh nhỏ hơn 40 megapixel.",+ decodeError: "Không thể giải mã ảnh này. Hãy thử tệp khác.",+ effectError: "Không thể hiển thị hiệu ứng. Chọn Không hoặc chọn ảnh khác.",+ },linkMenu: {openInBrowser: "Mở trong trình duyệt Unsloth",openExternal: "Mở trong trình duyệt bên ngoài",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 2947957a751..188a6333f08 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -5,6 +5,43 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const zhCN = {+ chatBackground: {+ noBackground: "无背景",+ sizing: "图片缩放方式",+ fill: "填充",+ fit: "适应",+ stretch: "拉伸",+ original: "原始尺寸",+ zoom: "缩放",+ outline: "消息输入框边框",+ fade: "渐隐至背景",+ title: "背景图片",+ description: "用于工作区的本地图片。支持 JPEG、PNG 或 WebP,最大 20 MiB。自动保持文字清晰可读。",+ upload: "上传图片",+ replace: "替换图片",+ remove: "移除背景",+ reset: "重置调整",+ effect: "效果",+ none: "无",+ dither: "抖动",+ ascii: "ASCII",+ halftone: "半色调",+ scanlines: "扫描线",+ visibility: "可见度",+ blur: "图片模糊",+ position: "位置",+ positionValue: "水平 {x}%,垂直 {y}%",+ newChat: "新聊天",+ conversation: "对话",+ prompt: "你想探索什么?",+ response: "背景上的对话依然清晰可读。",+ storageError: "无法保存背景。请检查浏览器存储空间。",+ fileError: "请选择小于 20 MiB 的 JPEG、PNG 或 WebP 图片。",+ dimensionsError: "请选择小于 4000 万像素的图片。",+ decodeError: "无法读取图片。请尝试其他文件。",+ effectError: "无法生成效果。请选择“无”或其他图片。",+ },+linkMenu: {openInBrowser: "在 Unsloth 浏览器中打开",openExternal: "在外部浏览器中打开",diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.tsindex 6435ca2c154..c52d2e3ffb0 100644--- a/studio/frontend/src/i18n/locales/zh-TW.ts+++ b/studio/frontend/src/i18n/locales/zh-TW.ts@@ -5,6 +5,42 @@ import type { DeepPartialMessageTree } from "../types";import type { en } from "./en.ts";export const zhTW = {+ chatBackground: {+ noBackground: "無背景",+ sizing: "圖片縮放方式",+ fill: "填滿",+ fit: "符合",+ stretch: "延展",+ original: "原始大小",+ zoom: "縮放",+ outline: "訊息輸入框外框",+ fade: "漸隱至背景",+ title: "背景圖片",+ description: "工作區的本機圖片。支援 JPEG、PNG 或 WebP,上限 20 MiB。自動保持文字清晰可讀。",+ upload: "上傳圖片",+ replace: "替換圖片",+ remove: "移除背景",+ reset: "重設調整",+ effect: "效果",+ none: "無",+ dither: "抖色",+ ascii: "ASCII",+ halftone: "半色調",+ scanlines: "掃描線",+ visibility: "可見度",+ blur: "圖片模糊",+ position: "位置",+ positionValue: "水平 {x}%,垂直 {y}%",+ newChat: "新對話",+ conversation: "對話",+ prompt: "你想探索什麼?",+ response: "對話內容在背景上保持清晰。",+ storageError: "無法儲存背景。請檢查瀏覽器可用儲存空間。",+ fileError: "請選擇小於 20 MiB 的 JPEG、PNG 或 WebP 圖片。",+ dimensionsError: "請選擇小於 4,000 萬像素的圖片。",+ decodeError: "無法解碼此圖片。請嘗試其他檔案。",+ effectError: "無法繪製效果。請選擇「無」或其他圖片。",+ },linkMenu: {openInBrowser: "在 Unsloth 瀏覽器中開啟",openExternal: "在外部瀏覽器中開啟",diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 0c182158585..ca9af76eaf6 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -6705,3 +6705,94 @@ html.force-reduced-motion .spooky-still :is(.spooky-spider, .spooky-bat) {to { opacity: 0.85; }}++.chat-wallpaper { position: absolute; inset: 0; overflow: hidden; pointer-events: none; --wallpaper-safe: 0; }+.chat-wallpaper-frame { position: absolute; inset: 0; opacity: var(--wallpaper-visibility); }+.chat-wallpaper-image {+ position: absolute; inset: 0 0 auto; height: min(72%, 760px);+ overflow: hidden;+ mask-image: linear-gradient(#000, transparent);+}+.chat-wallpaper-artwork { position: absolute; inset: 0; background-repeat: no-repeat; }+.chat-wallpaper-image[data-fade="false"] { height: 100%; mask-image: none; }+.chat-wallpaper-frame[data-entering] { animation: wallpaper-enter 180ms ease-out both; }+.chat-wallpaper-frame[data-departing] { animation: wallpaper-leave 180ms ease-out both; }+@keyframes wallpaper-enter { from { opacity: 0; } to { opacity: var(--wallpaper-visibility); } }+@keyframes wallpaper-leave { from { opacity: var(--wallpaper-visibility); } to { opacity: 0; } }+.chat-wallpaper[data-reduced] .chat-wallpaper-frame { animation: none; }+.chat-wallpaper[data-reduced] .chat-wallpaper-frame[data-departing] { display: none; }+/* Conversations dim the crop; compare dims even an empty pane so both match. */+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]):not([data-wallpaper-route="page"]):not(:has(.aui-thread-welcome-center)) > .chat-wallpaper,+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]):not([data-wallpaper-route="page"]):has([data-tour="chat-compare-view"]) > .chat-wallpaper,+.wallpaper-preview[data-wallpaper-conversation] > .chat-wallpaper { opacity: .4; }+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) :is(.aui-thread-viewport, [data-wallpaper-reading-surface]) {+ background: color-mix(in srgb, var(--background) calc((1 - var(--wallpaper-safe, 0)) * 100%), transparent);+}+/* No second wash on the welcome view: it crushes mid-tones into a dark horizon. */+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .aui-thread-viewport:has(.aui-thread-welcome-center) {+ background: transparent;+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .unsloth-welcome-greeting {+ position: relative;+ isolation: isolate;+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .unsloth-welcome-greeting::before {+ content: "";+ position: absolute;+ inset: -48px -40px;+ z-index: -1;+ pointer-events: none;+ background: radial-gradient(ellipse, color-mix(in srgb, var(--background) calc((1 - var(--wallpaper-safe, 0)) * 70%), transparent) 0%, transparent 72%);+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .unsloth-composer-surface,+.wallpaper-preview-composer {+ background: color-mix(in srgb, var(--background) max(92%, calc((1 - var(--wallpaper-safe, 0)) * 100%)), transparent);+ backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);+ box-shadow: inset 0 0 0 1px var(--border);+}+.wallpaper-preview-prose { background: var(--background); }++.chat-wallpaper::after {+ content: "";+ position: absolute;+ inset: 0 0 auto;+ height: 150px;+ background: linear-gradient(color-mix(in srgb, var(--background) 48%, transparent), transparent);+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) [data-side-panel-inset]:not(.chat-header-fade),+html:has(:is([data-wallpaper-workspace], [data-chat-content-root]) > .chat-wallpaper[data-ready]) [data-slot="window-titlebar"] {+ background: transparent;+ backdrop-filter: none;+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .chat-header-fade,+html:has(:is([data-wallpaper-workspace], [data-chat-content-root]) > .chat-wallpaper[data-ready]) [data-slot="window-titlebar-decoration"] {+ visibility: hidden;+}+:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) [data-wallpaper-chrome-controls],+html:has(:is([data-wallpaper-workspace], [data-chat-content-root]) > .chat-wallpaper[data-ready]) [data-slot="window-titlebar"] [data-wallpaper-chrome-controls] {+ background: transparent;+ backdrop-filter: none;+ text-shadow: 0 1px 8px var(--background);+}+/* The pinned sidebar stays solid, including its segment of the native titlebar. */+html:has([data-wallpaper-workspace] > .chat-wallpaper[data-ready]) [data-slot="window-titlebar"][data-wallpaper-sidebar-pinned] > [data-wallpaper-chrome-controls]:first-child {+ background: var(--sidebar);+}+/* One viewport-sized crop, so opening the sidebar does not reframe the image. */+[data-wallpaper-workspace]:has(> .chat-wallpaper[data-ready]) > [data-slot="sidebar-inset"],+[data-wallpaper-workspace]:has(> .chat-wallpaper[data-ready]) [data-chat-page-root] {+ background: transparent;+}+[data-wallpaper-workspace][data-wallpaper-route="page"]:has(> .chat-wallpaper[data-ready]) > [data-slot="sidebar-inset"] {+ background: color-mix(in srgb, var(--background) calc((1 - var(--wallpaper-safe, 0)) * 100%), transparent);+}+@supports not (backdrop-filter: blur(1px)) {+ :is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready]) .unsloth-composer-surface,+ .wallpaper-preview-composer { background: var(--background); }+}++/* Clear only route canvases; cards, menus and reading surfaces retain their fills. */+[data-wallpaper-workspace]:has(> .chat-wallpaper[data-ready]) :is(.hub-page, .hub-page .hub-canvas, [data-wallpaper-page-canvas]) { background: transparent; }++:is([data-wallpaper-workspace], [data-chat-content-root]):has(> .chat-wallpaper[data-ready][data-outline="false"]) .unsloth-composer-surface,+.wallpaper-preview:has(> .chat-wallpaper[data-outline="false"]) .wallpaper-preview-composer { box-shadow: none; }diff --git a/studio/frontend/tests/chat-background.test.ts b/studio/frontend/tests/chat-background.test.tsnew file mode 100644index 00000000000..e592dd70807--- /dev/null+++ b/studio/frontend/tests/chat-background.test.ts@@ -0,0 +1,194 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import test from "node:test";+import { renderEffect } from "../src/features/chat-background/effects.ts";+import {+ DEFAULT_ADJUSTMENTS,+ EFFECTS,+ sanitizeAdjustments,+ normalizedSize,+ validUpload,+} from "../src/features/chat-background/model.ts";+import {+ contrast,+ safeArtworkOpacity,+ type RGB,+} from "../src/features/chat-background/contrast.ts";+test("background preferences repair malformed persisted data", () => {+ assert.deepEqual(sanitizeAdjustments({}), DEFAULT_ADJUSTMENTS);+ assert.deepEqual(+ sanitizeAdjustments({+ effect: "invalid" as never,+ visibility: 200,+ blur: -12,+ position: "url(evil)",+ }),+ { ...DEFAULT_ADJUSTMENTS, visibility: 100, blur: 0 },+ );+ assert.equal(sanitizeAdjustments({ visibility: NaN }).visibility, 70);+ assert.equal(sanitizeAdjustments({ fade: false }).fade, false);+ assert.equal(sanitizeAdjustments({ outline: false }).outline, false);+ assert.equal(sanitizeAdjustments({ outline: "false" as never }).outline, true);+ assert.equal(sanitizeAdjustments({ sizing: "contain" }).sizing, "contain");+ assert.equal(sanitizeAdjustments({ sizing: "invalid" as never }).sizing, "cover");+ assert.equal(sanitizeAdjustments({ zoom: 500 }).zoom, 300);+ assert.equal(sanitizeAdjustments({ zoom: 0 }).zoom, 100);+ assert.equal(sanitizeAdjustments({ zoom: NaN }).zoom, 100);+ assert.equal(sanitizeAdjustments({ fade: "false" as never }).fade, true);+});+test("uploads bound processing dimensions", () => {+ assert.deepEqual(normalizedSize(6000, 4000), [2048, 1365]);+ assert.deepEqual(normalizedSize(3, 7), [3, 7]);+ assert.throws(() => normalizedSize(10000, 10000));+ assert.throws(() => normalizedSize(0, 1));+ assert.equal(validUpload({ type: "image/svg+xml", size: 40 }), false);+ assert.equal(+ validUpload({ type: "image/png", size: 21 * 1024 * 1024 }),+ false,+ );+ assert.equal(validUpload({ type: "image/png", size: 1024 }), true);+});+test("effects preserve alpha, bounds, input and deterministic output at cell edges", () => {+ const source = Uint8ClampedArray.from(+ { length: 13 * 11 * 4 },+ (_, i) => (i * 37) % 256,+ ),+ copy = new Uint8ClampedArray(source);+ for (const effect of EFFECTS)+ for (const light of [false, true]) {+ const result = renderEffect(source, 13, 11, effect, light);+ assert.equal(result.length, source.length);+ assert.deepEqual(result, renderEffect(source, 13, 11, effect, light));+ for (let i = 3; i < source.length; i += 4)+ assert.equal(result[i], source[i]);+ if (effect !== "None") assert.notDeepEqual(result, source);+ else assert.deepEqual(result, source);+ assert.deepEqual(source, copy);+ }+});+test("theme-dependent effects adapt to light mode", () => {+ const source = new Uint8ClampedArray(8 * 8 * 4).fill(100);+ for (const effect of EFFECTS) {+ const a = renderEffect(source, 8, 8, effect, false),+ b = renderEffect(source, 8, 8, effect, true);+ if (effect === "None" || effect === "Dither") assert.deepEqual(a, b);+ else assert.notDeepEqual(a, b);+ }+ assert.throws(() => renderEffect(source, 0, 8, "None", false));+});+test("contrast protection holds for arbitrary imagery and custom palettes", () => {+ const themes: [RGB, RGB[]][] = [+ [+ [255, 255, 255],+ [+ [20, 20, 20],+ [110, 110, 110],+ ],+ ],+ [+ [16, 14, 24],+ [+ [245, 245, 245],+ [160, 156, 170],+ ],+ ],+ [+ [60, 85, 70],+ [+ [220, 240, 225],+ [190, 200, 195],+ ],+ ],+ [[128, 128, 128], [[130, 130, 130]]],+ ];+ for (const [bg, foregrounds] of themes) {+ const alpha = safeArtworkOpacity(bg, foregrounds);+ assert.ok(alpha >= 0 && alpha <= 1);+ for (let r = 0; r <= 255; r += 51)+ for (let g = 0; g <= 255; g += 51)+ for (let b = 0; b <= 255; b += 51) {+ const composite = bg.map(+ (v, i) => v * (1 - alpha) + [r, g, b][i] * alpha,+ ) as unknown as RGB;+ for (const fg of foregrounds)+ assert.ok(+ contrast(composite, fg) >= Math.min(4.5, contrast(bg, fg)) - 1e-6,+ );+ }+ }+});++test("dither preserves hue across the ordered threshold pattern", () => {+ // RGB(128,64,32) lights thresholds 0-7; other dots use an 8% gain; each dot is 2x2 px.+ const source = Uint8ClampedArray.from(+ { length: 8 * 8 * 4 },+ (_, i) => [128, 64, 32, 255][i % 4],+ );+ const result = renderEffect(source, 8, 8, "Dither", false);+ for (let y = 0; y < 8; y++) {+ for (let x = 0; x < 8; x++) {+ const bright = (Math.floor(x / 2) + Math.floor(y / 2)) % 2 === 0;+ const offset = (y * 8 + x) * 4;+ assert.deepEqual(+ [...result.slice(offset, offset + 4)],+ bright ? [255, 128, 64, 255] : [10, 5, 3, 255],+ );+ }+ }+ assert.deepEqual(renderEffect(source, 8, 8, "Dither", true), result);+});++// Digests captured before the renderer rewrite; cover odd sizes, alpha, color and density.+const appearanceDigests: Record<string, string> = {+ "None:false":+ "7ee58829538bc7f04cd4e5ba7cc284309f7a8c9322b353ffcd728cdac36bd691",+ "None:true":+ "7ee58829538bc7f04cd4e5ba7cc284309f7a8c9322b353ffcd728cdac36bd691",+ "Dither:false":+ "d489c8d42fab551fb0eb18f2de57295c069b0b13b7b265a38a4a19a8c116952b",+ "Dither:true":+ "d489c8d42fab551fb0eb18f2de57295c069b0b13b7b265a38a4a19a8c116952b",+ "ASCII:false":+ "8f42a61785faaa10a0f21a07e5c9a9feb0667f1603d89c13aed50d4d2409dec5",+ "ASCII:true":+ "d6e415288dc7da96d7eb1fe696dce2f9df6f4dc0ccd26e8f03a6ef0a57f916ee",+ "Halftone:false":+ "7f4bda226cb36549fa8a21912645b258eb6db4bf8134a61ccb014fca4293681f",+ "Halftone:true":+ "c91bb71945d000777670219d46a3bbddbfaef7b7d22a646632cab2b32e14d39e",+ "Scanlines:false":+ "e308c1f64f34f3adf98838c554e9bf60a8d6a5f812255184ecc7272f178f7b77",+ "Scanlines:true":+ "b4b309f732feb40d141d535a71c64313db602b32cc494190c166853bbc06d341",+};++test("effect textures retain their established appearance", () => {+ for (const effect of EFFECTS) {+ for (const light of [false, true]) {+ const digest = createHash("sha256");+ for (const [width, height] of [+ [1, 1],+ [2, 3],+ [7, 9],+ [17, 19],+ [64, 48],+ ]) {+ for (let seed = 0; seed < 32; seed++) {+ const image = Uint8ClampedArray.from(+ { length: width * height * 4 },+ (_, i) =>+ seed < 16+ ? (i * 37 + seed * 17) % 256+ : [seed * 8 - 128, seed * 8 - 128, seed * 8 - 128, 255][i % 4],+ );+ digest.update(renderEffect(image, width, height, effect, light));+ }+ }+ assert.equal(+ digest.digest("hex"),+ appearanceDigests[`${effect}:${light}`],+ `${effect}, light=${light}`,+ );+ }+ }+});diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex de5b9ca4a4d..7a2848f9826 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -42,6 +42,7 @@"smoke-heavy-thread-main.tsx","smoke-thread-weight-main.tsx","smoke-settings-main.tsx",+ "smoke-chat-background-main.tsx","smoke-shortcuts-main.tsx","smoke-stream-pacing-main.tsx","smoke-code-block-flicker-main.tsx",diff --git a/tests/studio/playwright_chat_background.js b/tests/studio/playwright_chat_background.jsnew file mode 100644index 00000000000..bd0e52864a2--- /dev/null+++ b/tests/studio/playwright_chat_background.js@@ -0,0 +1,137 @@+// After opening /smoke-chat-background.html on the Vite server:+// playwright-cli -s=wallpaper run-code --filename=tests/studio/playwright_chat_background.js+async (page) => {+ const check=(ok,message)=>{if(!ok)throw new Error(message);};+ await page.emulateMedia({reducedMotion:'no-preference'});+ await page.addInitScript(()=>{+ window.__wallpaperWorkers=0;+ const Original=window.Worker;+ window.Worker=class extends Original{constructor(...args){super(...args);window.__wallpaperWorkers++;}};+ });+ await page.route('**/smoke-chat-background.html', async route => {+ const response = await route.fetch();+ // Vite's dev preamble needs inline scripts; workers still require self.+ await route.fulfill({response, headers:{...response.headers(), 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; worker-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' ws:"}});+ });+ await page.reload();+ await page.getByRole('button',{name:'Reset all',exact:true}).click();+ await page.waitForFunction(()=>document.querySelector('input[type=file]')?.disabled===false);+ check(await page.getByRole('button',{name:'Remove background',exact:true}).count()===0,'no remove action without an image');+ check(await page.locator('section[data-settings-label="Background image"] [role=combobox], section[data-settings-label="Background image"] [role=slider], section[data-settings-label="Background image"] [role=switch]').count()===0,'no adjustments before upload');+ check(await page.locator('[data-wallpaper-previews] .wallpaper-preview').count()===2,'both previews visible without an image');+ check(await page.getByText('No background',{exact:true}).count()===2,'empty previews are labelled');+ check(await page.getByRole('button',{name:'Reset adjustments',exact:true}).count()===0,'no reset action without an image');+ const upload = async (invalid=false) => page.evaluate(invalid=>{+ const c=document.createElement('canvas');c.width=900;c.height=600;+ const ctx=c.getContext('2d');const g=ctx.createLinearGradient(0,0,900,600);+ g.addColorStop(0,'#e78c9c');g.addColorStop(.5,'#65d6c0');g.addColorStop(1,'#29388d');ctx.fillStyle=g;ctx.fillRect(0,0,900,600);+ for(let n=0;n<16;n++){ctx.fillStyle=n%2?'#ffffff88':'#11111188';ctx.fillRect(n*60,60,30,400);}+ const bytes=invalid?new Uint8Array([1,2,3]):Uint8Array.from(atob(c.toDataURL('image/png').split(',')[1]),v=>v.charCodeAt(0));+ const dt=new DataTransfer();dt.items.add(new File([bytes],'background.png',{type:'image/png'}));+ const input=document.querySelector('input[type=file]');input.files=dt.files;input.dispatchEvent(new Event('change',{bubbles:true}));+ },invalid);+ const settled=async(effect)=>page.waitForFunction(effect=>{+ window.__wallpaperStep=effect;const frames=document.querySelectorAll('[data-chat-content-root] .chat-wallpaper-frame');+ return frames.length===1&&frames[0].getAttribute('data-effect')===effect;+ },effect);+ await upload();await settled('None');+ check(await page.getByText('No background',{exact:true}).count()===0,'empty labels disappear after upload');+ check(await page.getByRole('button',{name:'Remove background',exact:true}).count()===1,'uploaded image can be removed');+ check(await page.getByRole('button',{name:'Reset adjustments',exact:true}).count()===0,'default adjustments need no reset');+ const canvas=page.locator('[data-wallpaper-workspace] > .chat-wallpaper');+ const crop=await canvas.boundingBox();+ await page.getByRole('button',{name:'Toggle sidebar',exact:true}).click();+ await page.locator('[data-slot=sidebar]').waitFor();+ check(JSON.stringify(crop)===JSON.stringify(await canvas.boundingBox()),'sidebar must not reframe image');+ check(await page.locator('[data-slot=sidebar]').evaluate(e=>getComputedStyle(e).backgroundColor!=='rgba(0, 0, 0, 0)'),'sidebar stays solid');+ await page.getByRole('button',{name:'Toggle page',exact:true}).click();+ await page.waitForSelector('[data-wallpaper-route="page"]');+ await canvas.waitFor({state:'detached'});+ check(await canvas.count()===0,'non-chat page has no wallpaper');+ await page.getByRole('button',{name:'Toggle page',exact:true}).click();+ await page.waitForSelector('[data-wallpaper-route="chat"]');+ await settled('None');+ await page.getByRole('button',{name:'Toggle sidebar',exact:true}).click();+ for(const effect of ['Dither','ASCII','Halftone','Scanlines','None']){+ await page.getByRole('combobox',{name:'Effect',exact:true}).click();+ await page.getByRole('option',{name:effect,exact:true}).click();+ await settled(effect);+ }+ await page.getByRole('combobox',{name:'Effect',exact:true}).click();await page.getByRole('option',{name:'ASCII',exact:true}).click();await settled('ASCII');+ const workers=await page.evaluate(()=>window.__wallpaperWorkers);+ for(const [label,size] of [['Fill','cover'],['Stretch','100% 100%'],['Original size','auto'],['Fit','contain']]) {+ await page.getByRole('combobox',{name:'Image sizing',exact:true}).click();+ await page.getByRole('option',{name:label,exact:true}).click();+ await page.waitForFunction(size=>[...document.querySelectorAll('.chat-wallpaper-artwork')].every(e=>getComputedStyle(e).backgroundSize===size),size);+ }+ await page.getByRole('slider',{name:'Zoom',exact:true}).focus();await page.keyboard.press('End');+ await page.waitForFunction(()=>getComputedStyle(document.querySelector('.chat-wallpaper-artwork')).transform==='matrix(3, 0, 0, 3, 0, 0)');+ const outline=page.getByRole('switch',{name:'Composer outline',exact:true});+ await outline.click();+ await page.waitForFunction(()=>[...document.querySelectorAll('.wallpaper-preview-composer, .unsloth-composer-surface')].every(e=>getComputedStyle(e).boxShadow==='none'));++ const fade=page.getByRole('switch',{name:'Fade to background',exact:true});+ check(await fade.getAttribute('aria-checked')==='true','fade defaults on');+ await fade.click();+ await page.waitForFunction(()=>[...document.querySelectorAll('.chat-wallpaper-image')].every(e=>getComputedStyle(e).maskImage==='none'));+ check(await page.locator('[data-chat-content-root] .chat-wallpaper-image').evaluate(e=>e.getBoundingClientRect().height===e.parentElement.getBoundingClientRect().height),'no fade fills the canvas');+ await page.getByRole('slider',{name:'Visibility',exact:true}).focus();await page.keyboard.press('End');+ await page.getByRole('slider',{name:'Image blur',exact:true}).focus();await page.keyboard.press('ArrowRight');+ await page.getByRole('button',{name:'Horizontal 100%, vertical 0%',exact:true}).click();+ await page.setViewportSize({width:1100,height:800});+ await page.getByRole('textbox',{name:'Message',exact:true}).fill('Streaming and editing do not redraw the background.');+ check(await page.evaluate(()=>window.__wallpaperWorkers)===workers,'CSS controls must not rerun effects');+ await page.reload();await settled('ASCII');+ check(await fade.getAttribute('aria-checked')==='false','fade preference persisted');+ check(await outline.getAttribute('aria-checked')==='false','outline preference persisted');+ check(await page.getByRole('slider',{name:'Zoom',exact:true}).getAttribute('aria-valuenow')==='300','zoom persisted');+ check(await page.locator('[data-chat-content-root] .chat-wallpaper-artwork').evaluate(e=>getComputedStyle(e).backgroundSize)==='contain','sizing persisted');+ check(await page.getByRole('slider',{name:'Visibility',exact:true}).getAttribute('aria-valuenow')==='100','visibility persisted');+ check(await page.getByRole('slider',{name:'Image blur',exact:true}).getAttribute('aria-valuenow')==='1','blur persisted');+ check(await page.getByRole('button',{name:'Horizontal 100%, vertical 0%',exact:true}).getAttribute('aria-pressed')==='true','position persisted');+ await upload(true);await page.getByRole('alert').waitFor();await settled('ASCII');+ await page.evaluate(async()=>{const s=window.__wallpaperSmoke;for(let i=0;i<30;i++)s.patch({visibility:i,effect:i===29?'Halftone':'Scanlines'});});+ await settled('Halftone');+ await page.waitForFunction(async()=>{const s=window.__wallpaperSmoke;return s.state().value.visibility===29;});+ await page.evaluate(()=>{window.__put=IDBObjectStore.prototype.put;IDBObjectStore.prototype.put=function(...args){if(this.name==='backgrounds')throw new DOMException('quota','QuotaExceededError');return window.__put.apply(this,args);};});+ await upload();await page.getByRole('alert').waitFor();await settled('Halftone');+ await page.evaluate(()=>{IDBObjectStore.prototype.put=window.__put;delete window.__put;});+ await upload();await settled('None');+ check(await page.getByRole('button',{name:'Reset adjustments',exact:true}).count()===0,'reset action is absent');+ check(await fade.getAttribute('aria-checked')==='true','upload starts with fade enabled');+ check(await outline.getAttribute('aria-checked')==='true','upload starts with outline enabled');+ check(await page.getByRole('slider',{name:'Zoom',exact:true}).getAttribute('aria-valuenow')==='100','upload starts at default zoom');+ await page.getByRole('combobox',{name:'Effect',exact:true}).click();await page.getByRole('option',{name:'Halftone',exact:true}).click();await settled('Halftone');+ await page.getByRole('button',{name:'Toggle theme',exact:true}).click();await settled('Halftone');+ await page.getByRole('button',{name:'Toggle conversation',exact:true}).click();+ await page.waitForFunction(()=>getComputedStyle(document.querySelector('[data-chat-content-root] > .chat-wallpaper')).opacity==='0.4');+ await page.emulateMedia({reducedMotion:'reduce'});+ await page.waitForFunction(()=>document.querySelector('[data-chat-content-root] > .chat-wallpaper')?.getAttribute('data-reduced')==='true');+ await page.getByRole('button',{name:'Toggle route',exact:true}).click();+ check(await page.locator('[data-chat-content-root] > .chat-wallpaper').count()===0,'other route has no wallpaper');+ await page.getByRole('button',{name:'Toggle route',exact:true}).click();await settled('Halftone');+ await page.setViewportSize({width:390,height:844});+ check(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'mobile must not overflow horizontally');+ await page.screenshot({path:'.playwright-cli/wallpaper-mobile.png',fullPage:true});+ await page.setViewportSize({width:1440,height:1000});+ await page.screenshot({path:'.playwright-cli/wallpaper-conversation.png',fullPage:true});+ await page.evaluate(()=>localStorage.setItem('unsloth.browser-account.v1','account:wallpaper-test:other'));+ await page.reload();await page.waitForFunction(()=>document.querySelector('input[type=file]')?.disabled===false);+ check(await page.locator('.chat-wallpaper').count()===0,'account isolation');+ await page.evaluate(()=>localStorage.removeItem('unsloth.browser-account.v1'));+ await page.reload();await settled('Halftone');+ await page.getByRole('button',{name:'Remove background',exact:true}).click();+ await page.waitForFunction(()=>!document.querySelector('.chat-wallpaper'));+ check(await page.getByRole('combobox',{name:'Effect',exact:true}).count()===0,'removal hides adjustments');+ await page.reload();await page.waitForFunction(()=>document.querySelector('input[type=file]')?.disabled===false);+ check(await page.locator('.chat-wallpaper').count()===0,'removal persists');+ await upload();await settled('None');+ await page.evaluate(()=>{window.__workingWorker=window.Worker;window.Worker=function(){throw new Error('worker unavailable');};});+ await page.getByRole('combobox',{name:'Effect',exact:true}).click();await page.getByRole('option',{name:'Dither',exact:true}).click();+ await page.getByRole('alert').waitFor();await settled('None');+ await page.evaluate(()=>{window.Worker=window.__workingWorker;delete window.__workingWorker;});+ await page.getByRole('combobox',{name:'Effect',exact:true}).click();await page.getByRole('option',{name:'ASCII',exact:true}).click();await settled('ASCII');+ await page.getByRole('button',{name:'Reset all',exact:true}).click();+ await page.waitForFunction(()=>!document.querySelector('.chat-wallpaper'));+ return 'PASS: effects, CSS-only controls, persistence, invalid upload, quota recovery, latest-wins changes, theme, conversation, reduced motion, route lifecycle, mobile, account isolation and reset';+}