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
Prevent Studio reloads from flashing blank (#9251)
oobaboogae32ed98bda21
diff --git a/studio/frontend/index.html b/studio/frontend/index.htmlindex f1d9269392b..3d6fb70de9b 100644--- a/studio/frontend/index.html+++ b/studio/frontend/index.html@@ -11,6 +11,9 @@<!-- Classic boot scripts satisfy script-src 'self' and run before modules. --><script src="/crypto-boot.js"></script><script src="/theme-boot.js"></script>+ <!-- Restores the last rendered shell before the replacement document's+ first paint, then removes it when React commits the new shell. -->+ <script src="/reload-snapshot.js"></script></head><body><div id="root"></div>diff --git a/studio/frontend/public/reload-snapshot.js b/studio/frontend/public/reload-snapshot.jsnew file mode 100644index 00000000000..cd5bec3d58c--- /dev/null+++ b/studio/frontend/public/reload-snapshot.js@@ -0,0 +1,872 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++(function () {+ var storageKey = "unsloth.reload-snapshot.v1";+ var maxSnapshotLength = 3 * 1024 * 1024;+ var maxInlineStylesLength = 2 * 1024 * 1024;+ var maxSnapshotAgeMs = 10 * 1000;+ var retainedStyleWaitMs = 500;+ var maxMaterializedMediaPixels = 1500 * 1000;+ var appearanceStorageKey = "unsloth_appearance_customization";+ var maxImportedFonts = 3;+ var maxImportedFontLength = 2200000;+ var maxImportedFontsLength = 4400000;+ var importedFontWaitMs = 250;+ var fontDataUrlPattern =+ /^data:(?:font\/(?:woff2?|ttf|otf|sfnt)|application\/(?:octet-stream|x-font-\w+|font-\w+));base64,[A-Za-z0-9+/=]+$/;+ var overlay = null;+ var retainedSnapshot = null;+ var removalTimer = null;+ // Appearance is inline custom properties on <html> plus these gate+ // attributes, written by theme-boot.js (mode and palette) and+ // applyCustomizationToDocument in+ // src/features/settings/stores/appearance-custom-store.ts (the rest).+ // Uncarried, the copy paints in stock colors until React restyles it.+ var appearanceAttributes = [+ "data-chat-font",+ "data-code-font-size",+ "data-contrast-adjust",+ "data-palette",+ "data-ui-font",+ "data-ui-font-size",+ ];+ // Keep this in sync with applyCustomizationToDocument. Other inline root+ // variables are transient runtime state (for example an in-progress panel+ // resize) and must not be replayed into the replacement document.+ var appearanceVariables = [+ "--background",+ "--chart-1",+ "--contrast-mix",+ "--contrast-target",+ "--control-accent",+ "--control-accent-foreground",+ "--custom-chat-font",+ "--custom-code-font",+ "--custom-code-font-size",+ "--custom-heading-font",+ "--font-heading",+ "--font-mono",+ "--font-sans",+ "--foreground",+ "--primary",+ "--primary-foreground",+ "--ui-font-scale",+ ];++ function clearStoredSnapshot() {+ try {+ sessionStorage.removeItem(storageKey);+ } catch (error) {}+ }++ function readStoredSnapshot() {+ try {+ var value = sessionStorage.getItem(storageKey);+ sessionStorage.removeItem(storageKey);+ return value ? JSON.parse(value) : null;+ } catch (error) {+ clearStoredSnapshot();+ return null;+ }+ }++ function navigationType() {+ try {+ var entries = performance.getEntriesByType("navigation");+ return entries.length ? entries[0].type : null;+ } catch (error) {+ return null;+ }+ }++ function readStyleSheets() {+ var hrefs = [];+ document+ .querySelectorAll('link[rel="stylesheet"]')+ .forEach(function (link) {+ if (link.href) hrefs.push(link.href);+ });+ return hrefs;+ }++ function readInlineStyleSheets() {+ var styles = [];+ var total = 0;+ document+ .querySelectorAll("style[data-vite-dev-id]")+ .forEach(function (style) {+ var text = style.textContent;+ if (+ typeof text !== "string" ||+ !text ||+ total + text.length > maxInlineStylesLength+ ) {+ return;+ }+ total += text.length;+ styles.push(text);+ });+ return styles;+ }++ // Design tokens the app defines through `:root` do not reach a shadow tree:+ // `:root` matches only a document's root element, and Tailwind's `:host`+ // block redeclares some of them on the host. Freeze the computed set and put+ // it on the copy's own root instead.+ function readTokens() {+ var style = getComputedStyle(document.documentElement);+ var tokens = {};+ for (var index = 0; index < style.length; index += 1) {+ var name = style[index];+ if (name.slice(0, 2) === "--") {+ tokens[name] = style.getPropertyValue(name);+ }+ }+ return tokens;+ }++ function readAppearance() {+ var root = document.documentElement;+ var variables = {};+ appearanceVariables.forEach(function (name) {+ var value = root.style.getPropertyValue(name);+ if (value) variables[name] = value;+ });+ var attributes = {};+ appearanceAttributes.forEach(function (name) {+ var value = root.getAttribute(name);+ if (value !== null) attributes[name] = value;+ });+ return { variables: variables, attributes: attributes };+ }++ function applyAppearanceAttributes(element, appearance) {+ var attributes = (appearance && appearance.attributes) || {};+ appearanceAttributes.forEach(function (name) {+ if (typeof attributes[name] === "string") {+ element.setAttribute(name, attributes[name]);+ }+ });+ }++ // React re-applies all of these on mount, so this only brings that forward.+ // Nothing here needs undoing when the overlay goes.+ function applyAppearance(appearance) {+ if (!appearance) return;+ var root = document.documentElement;+ var variables = appearance.variables || {};+ appearanceVariables.forEach(function (name) {+ if (typeof variables[name] === "string") {+ root.style.setProperty(name, variables[name]);+ }+ });+ applyAppearanceAttributes(root, appearance);+ }++ function registerImportedFonts() {+ var loads = [];+ if (+ typeof FontFace !== "function" ||+ !document.fonts ||+ typeof document.fonts.add !== "function"+ ) {+ return loads;+ }+ try {+ var raw = localStorage.getItem(appearanceStorageKey);+ if (!raw || raw.length > maxImportedFontsLength + 100000) return loads;+ var persisted = JSON.parse(raw);+ var customization =+ persisted && persisted.state && persisted.state.customization;+ if (!customization || !Array.isArray(customization.importedFonts)) {+ return loads;+ }+ var selected = {};+ ["uiFont", "headingFont", "chatFont", "codeFont"].forEach(+ function (key) {+ var name = customization[key];+ if (typeof name === "string") selected[name] = true;+ },+ );+ var total = 0;+ var seen = {};+ customization.importedFonts+ .slice(0, maxImportedFonts)+ .forEach(function (font) {+ var name = font && font.name;+ var dataUrl = font && font.dataUrl;+ if (+ typeof name !== "string" ||+ !selected[name] ||+ seen[name] ||+ !name ||+ name.length > 100 ||+ /[;{}()<>"'\\/,\x60\x00-\x1f\x7f]/.test(name) ||+ typeof dataUrl !== "string" ||+ dataUrl.length > maxImportedFontLength ||+ total + dataUrl.length > maxImportedFontsLength ||+ !fontDataUrlPattern.test(dataUrl)+ ) {+ return;+ }+ total += dataUrl.length;+ seen[name] = true;+ try {+ var face = new FontFace(name, "url(" + dataUrl + ")");+ document.fonts.add(face);+ loads.push(face.load());+ } catch (error) {}+ });+ } catch (error) {}+ return loads;+ }++ function restoreScrollState(root) {+ root+ .querySelectorAll(+ "[data-reload-scroll-top], [data-reload-scroll-left]",+ )+ .forEach(function (element) {+ var top = Number(element.getAttribute("data-reload-scroll-top"));+ var left = Number(element.getAttribute("data-reload-scroll-left"));+ if (isFinite(top)) element.scrollTop = top;+ if (isFinite(left)) element.scrollLeft = left;+ });+ }++ function restoreSnapshot() {+ var snapshot = readStoredSnapshot();+ var linkedStyles =+ snapshot && Array.isArray(snapshot.styles) ? snapshot.styles : [];+ var inlineStyles =+ snapshot && Array.isArray(snapshot.inlineStyles)+ ? snapshot.inlineStyles+ : [];+ if (+ navigationType() !== "reload" ||+ !snapshot ||+ typeof snapshot.createdAt !== "number" ||+ Date.now() - snapshot.createdAt > maxSnapshotAgeMs ||+ snapshot.path !== location.pathname + location.search ||+ typeof snapshot.html !== "string" ||+ !snapshot.html ||+ !linkedStyles.length &&+ !inlineStyles.length+ ) {+ return;+ }++ var fontLoads = registerImportedFonts();+ applyAppearance(snapshot.appearance);+ retainedSnapshot = snapshot;+ overlay = document.createElement("div");+ overlay.className = "reload-snapshot";+ // Vite injects index.css only after main.tsx runs, and styles inside the+ // closed shadow tree cannot match its host. Keep the host full-viewport+ // during that development-only gap; index.css repeats this for production.+ overlay.style.position = "fixed";+ overlay.style.inset = "0";+ overlay.style.zIndex = "2147483647";+ overlay.style.pointerEvents = "none";+ overlay.style.background = "var(--background)";+ overlay.setAttribute("aria-hidden", "true");+ // pointer-events: none on the host is not enough, since the copy carries+ // the app's own pointer-events-auto classes. inert is. The property is a+ // silent expando where unsupported, so set the attribute too.+ overlay.inert = true;+ overlay.setAttribute("inert", "");+ // A closed shadow tree keeps the copy out of every document query. The+ // markup is a duplicate of the live shell, so leaving it in the page tree+ // makes `#root textarea` (and the UI tests that wait on one) ambiguous.+ var shell = overlay.attachShadow({ mode: "closed" });+ var pendingLinkedStyles = 0;+ var linkedStylesRestored = false;+ var shellBody;+ var restoreAfterLinkedStyles = function () {+ if (linkedStylesRestored) return;+ linkedStylesRestored = true;+ if (overlay && shellBody) restoreScrollState(shellBody);+ };+ linkedStyles.forEach(function (href) {+ if (typeof href !== "string" || !href) return;+ var link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = href;+ pendingLinkedStyles += 1;+ link.onload = function () {+ pendingLinkedStyles -= 1;+ if (pendingLinkedStyles === 0) restoreAfterLinkedStyles();+ };+ // A rebuilt bundle renames its hashed CSS, so the shell would come back+ // unstyled. Drop it and let the real document through instead.+ link.onerror = removeOverlay;+ shell.appendChild(link);+ });+ inlineStyles.forEach(function (text) {+ if (typeof text !== "string" || !text) return;+ var style = document.createElement("style");+ style.textContent = text;+ shell.appendChild(style);+ });+ // Selectors do not cross the shadow boundary, and 80-odd rules are anchored+ // on `html` (light/dark theming above all), so the copy is rooted in an+ // <html> element carrying the classes and gate attributes it was styled by,+ // plus the marker index.css hangs the shell's own rules off.+ var shellRoot = document.createElement("html");+ if (fontLoads.length) shellRoot.style.visibility = "hidden";+ shellRoot.className =+ "reload-snapshot-shell " ++ (typeof snapshot.rootClass === "string" ? snapshot.rootClass : "");+ applyAppearanceAttributes(shellRoot, snapshot.appearance);+ var tokens = snapshot.tokens || {};+ Object.keys(tokens).forEach(function (name) {+ if (name.slice(0, 2) === "--" && typeof tokens[name] === "string") {+ shellRoot.style.setProperty(name, tokens[name]);+ }+ });+ // Global typography and foreground styles hang off body, not html, so the+ // copy needs that inheritance boundary rather than a bare html root.+ shellBody = document.createElement("body");+ shellBody.innerHTML = snapshot.html;+ shellRoot.appendChild(shellBody);+ shell.appendChild(shellRoot);+ document.documentElement.appendChild(overlay);+ // Arm the fail-open timeout before anything else can throw. Once the host+ // is in the document, a throw below would otherwise strand it.+ removalTimer = setTimeout(removeOverlay, 5000);+ if (fontLoads.length) {+ var revealShell = function () {+ shellRoot.style.visibility = "visible";+ };+ Promise.race([+ Promise.all(+ fontLoads.map(function (load) {+ return load.catch(function () {});+ }),+ ),+ new Promise(function (resolve) {+ setTimeout(resolve, importedFontWaitMs);+ }),+ ]).then(revealShell, revealShell);+ }+ // Apply immediately and on the next frame for inline styles, then once+ // linked styles settle (or after a bounded wait) for their final geometry.+ restoreScrollState(shellBody);+ requestAnimationFrame(function () {+ if (overlay) restoreScrollState(shellBody);+ });+ if (pendingLinkedStyles > 0) {+ setTimeout(restoreAfterLinkedStyles, retainedStyleWaitMs);+ }+ }++ // React drives value/checked/selected as DOM properties and cloneNode copies+ // attributes, so a populated composer or a ticked box would come back empty.+ // Secret inputs must be identified independently of their presentation type:+ // password and token fields can temporarily become type=text when revealed.+ function isSensitiveField(field) {+ var autocomplete =+ typeof field.autocomplete === "string"+ ? field.autocomplete.toLowerCase()+ : "";+ return (+ field.hasAttribute("data-reload-snapshot-sensitive") ||+ field.type === "password" ||+ field.type === "file" ||+ autocomplete.indexOf("password") !== -1 ||+ autocomplete.indexOf("one-time-code") !== -1 ||+ autocomplete.indexOf("cc-csc") !== -1+ );+ }++ var sensitiveAttributes = ["title", "aria-label", "alt", "placeholder"];++ function mirrorFieldState(original, cloned) {+ var tag = original.tagName;+ if (isSensitiveField(original)) {+ // cloneNode retains input attributes, textarea text, and any secret in a+ // code/span subtree. The same value usually also sits in a tooltip or an+ // accessible name, which clearing children alone would leave behind.+ cloned.removeAttribute("value");+ sensitiveAttributes.forEach(function (name) {+ cloned.removeAttribute(name);+ });+ if (tag !== "INPUT") cloned.replaceChildren();+ return;+ }+ if (tag === "TEXTAREA") {+ cloned.textContent = original.value;+ } else if (tag === "INPUT") {+ cloned.setAttribute("value", original.value);+ if (original.checked) cloned.setAttribute("checked", "");+ else cloned.removeAttribute("checked");+ } else if (tag === "OPTION") {+ if (original.selected) cloned.setAttribute("selected", "");+ else cloned.removeAttribute("selected");+ }+ }++ function hasClippingOverflow(value) {+ return (+ value === "auto" ||+ value === "scroll" ||+ value === "overlay" ||+ value === "hidden"+ );+ }++ function isScrollContainer(element, style) {+ return (+ (hasClippingOverflow(style.overflowY) &&+ element.scrollHeight > element.clientHeight) ||+ (hasClippingOverflow(style.overflowX) &&+ element.scrollWidth > element.clientWidth)+ );+ }++ function nearestScrollContainer(element) {+ var ancestor = element.parentElement;+ while (ancestor && ancestor !== document.body) {+ if (isScrollContainer(ancestor, getComputedStyle(ancestor))) {+ return ancestor;+ }+ ancestor = ancestor.parentElement;+ }+ return null;+ }++ function isOutsideScrollViewport(bounds, scrollContainer) {+ var containerBounds = scrollContainer.getBoundingClientRect();+ var top = Math.max(0, containerBounds.top);+ var right = Math.min(innerWidth, containerBounds.right);+ var bottom = Math.min(innerHeight, containerBounds.bottom);+ var left = Math.max(0, containerBounds.left);+ return (+ bounds.bottom <= top ||+ bounds.right <= left ||+ bounds.top >= bottom ||+ bounds.left >= right+ );+ }++ function hasVisibleLayoutParent(element, scrollContainer) {+ var parent = element.parentElement;+ while (parent && parent !== scrollContainer) {+ var style = getComputedStyle(parent);+ if (style.display !== "contents") {+ return !isOutsideScrollViewport(+ parent.getBoundingClientRect(),+ scrollContainer,+ );+ }+ parent = parent.parentElement;+ }+ return parent === scrollContainer;+ }++ function replaceWithScrollSpacer(cloned, bounds, scrollContainer) {+ var vertical = scrollContainer.scrollHeight > scrollContainer.clientHeight;+ var axis = vertical ? "vertical" : "horizontal";+ var start = vertical ? bounds.top : bounds.left;+ var end = vertical ? bounds.bottom : bounds.right;+ var crossSize = vertical+ ? bounds.right - bounds.left+ : bounds.bottom - bounds.top;+ var next = cloned.nextElementSibling;+ if (+ next &&+ next.getAttribute("data-reload-spacer-axis") === axis+ ) {+ start = Math.min(+ start,+ Number(next.getAttribute("data-reload-spacer-start")),+ );+ end = Math.max(+ end,+ Number(next.getAttribute("data-reload-spacer-end")),+ );+ crossSize = Math.max(+ crossSize,+ Number(next.getAttribute("data-reload-spacer-cross")),+ );+ next.remove();+ }+ var size = Math.max(0, end - start);+ crossSize = Math.max(0, crossSize);+ cloned.replaceChildren();+ Array.from(cloned.attributes).forEach(function (attribute) {+ cloned.removeAttribute(attribute.name);+ });+ cloned.setAttribute("aria-hidden", "true");+ cloned.setAttribute("data-reload-spacer", "");+ cloned.setAttribute("data-reload-spacer-axis", axis);+ cloned.setAttribute("data-reload-spacer-start", String(start));+ cloned.setAttribute("data-reload-spacer-end", String(end));+ cloned.setAttribute("data-reload-spacer-cross", String(crossSize));+ cloned.setAttribute(+ "style",+ "display:block;box-sizing:border-box;flex:none;margin:0;padding:0;" ++ "border:0;overflow:hidden;" ++ (vertical+ ? "height:" ++ size ++ "px;min-height:" ++ size ++ "px;width:" ++ crossSize ++ "px;max-width:100%;"+ : "width:" ++ size ++ "px;min-width:" ++ size ++ "px;height:" ++ crossSize ++ "px;max-height:100%;"),+ );+ }++ function mirrorScrollState(original, cloned) {+ if (original.scrollTop) {+ cloned.setAttribute("data-reload-scroll-top", String(original.scrollTop));+ }+ if (original.scrollLeft) {+ cloned.setAttribute(+ "data-reload-scroll-left",+ String(original.scrollLeft),+ );+ }+ }++ function capturePixels(original, sourceWidth, sourceHeight, bounds) {+ if (+ !bounds ||+ bounds.bottom <= 0 ||+ bounds.right <= 0 ||+ bounds.top >= innerHeight ||+ bounds.left >= innerWidth+ ) {+ return null;+ }+ if (!sourceWidth || !sourceHeight) return null;+ try {+ var pixelRatio = window.devicePixelRatio || 1;+ var scale = Math.min(+ 1,+ ((bounds.right - bounds.left) * pixelRatio) / sourceWidth,+ ((bounds.bottom - bounds.top) * pixelRatio) / sourceHeight,+ );+ var width = Math.max(1, Math.round(sourceWidth * scale));+ var height = Math.max(1, Math.round(sourceHeight * scale));+ if (width * height > maxMaterializedMediaPixels) {+ var pixelScale = Math.sqrt(+ maxMaterializedMediaPixels / (width * height),+ );+ width = Math.max(1, Math.round(width * pixelScale));+ height = Math.max(1, Math.round(height * pixelScale));+ }+ var canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ var context = canvas.getContext("2d");+ if (!context) throw new Error("Canvas 2D context unavailable");+ context.drawImage(original, 0, 0, width, height);+ var dataUrl = canvas.toDataURL("image/webp", 0.82);+ if (!dataUrl || dataUrl === "data:,") throw new Error("Empty media frame");+ return dataUrl;+ } catch (error) {+ return null;+ }+ }++ function hasSensitiveUrl(value) {+ // Dropping a URL only costs the copy an image, so err towards dropping.+ return /[?&](?:access_token|api[-_]?key|apikey|auth|authorization|code|credential|key|secret|sig|signature|token|x-amz-credential|x-amz-signature|x-goog-signature)=/i.test(+ value,+ );+ }++ function materializeEphemeralMedia(original, cloned, bounds) {+ var tag = original.tagName;+ var source = original.currentSrc || original.getAttribute("src") || "";+ if (source.slice(0, 5) !== "blob:" && !hasSensitiveUrl(source)) return;++ // Audio controls still read as a shell without their expiring source.+ // Images and video can carry rendered pixels as a bounded data URL; if a+ // cross-origin frame refuses canvas capture, the URL is dropped, not kept.+ if (tag !== "IMG" && tag !== "VIDEO") {+ cloned.removeAttribute("src");+ return;+ }+ var sourceWidth = tag === "IMG" ? original.naturalWidth : original.videoWidth;+ var sourceHeight =+ tag === "IMG" ? original.naturalHeight : original.videoHeight;+ var dataUrl = capturePixels(original, sourceWidth, sourceHeight, bounds);+ if (!dataUrl) {+ cloned.removeAttribute("src");+ } else if (tag === "IMG") {+ cloned.setAttribute("src", dataUrl);+ cloned.removeAttribute("srcset");+ } else {+ cloned.setAttribute("poster", dataUrl);+ cloned.removeAttribute("src");+ }+ }++ function materializeCanvas(original, cloned, bounds) {+ if (original.tagName !== "CANVAS") return;+ var dataUrl = capturePixels(+ original,+ original.width,+ original.height,+ bounds,+ );+ if (!dataUrl) return;+ var inlineStyle = cloned.getAttribute("style") || "";+ if (inlineStyle && inlineStyle.slice(-1) !== ";") inlineStyle += ";";+ cloned.setAttribute(+ "style",+ inlineStyle ++ "background-image:url(" ++ dataUrl ++ ");background-size:100% 100%;background-repeat:no-repeat;",+ );+ }++ // Pixels are rasterized at devicePixelRatio, so one page costs 4x on a 2x+ // display and can pass the cap alone. Dropping them keeps the layout, which+ // is the point of the copy; dropping the snapshot puts the blank flash back.+ function dropMaterializedMedia(clone) {+ var dropped = 0;+ clone.querySelectorAll("[src], [poster], [style]").forEach(function (el) {+ ["src", "poster"].forEach(function (name) {+ var value = el.getAttribute(name);+ if (value && value.slice(0, 5) === "data:") {+ el.removeAttribute(name);+ dropped += 1;+ }+ });+ var style = el.getAttribute("style");+ if (style && style.indexOf("url(data:") !== -1) {+ el.setAttribute(+ "style",+ style.replace(/background-image:url\(data:[^)]*\);?/g, ""),+ );+ dropped += 1;+ }+ });+ return dropped;+ }++ function saveSnapshot() {+ if (+ document.documentElement.hasAttribute("data-reload-snapshot-private")+ ) {+ clearStoredSnapshot();+ return;+ }+ // A second reload can happen before the replacement app is ready. The+ // visible frame is still the closed-shadow copy, not the loading body+ // underneath it, so carry that retained snapshot forward verbatim.+ if (overlay && retainedSnapshot) {+ try {+ retainedSnapshot.createdAt = Date.now();+ retainedSnapshot.path = location.pathname + location.search;+ sessionStorage.setItem(storageKey, JSON.stringify(retainedSnapshot));+ } catch (error) {+ clearStoredSnapshot();+ }+ return;+ }+ var root = document.getElementById("root");+ if (!root || !root.firstElementChild) return;+ try {+ // Clone the body's rendered surface, not just #root: dialogs, menus and+ // other primitives portal beside the app root and are part of the frame+ // the user sees. Active content is stripped before serialization below.+ var clone = document.body.cloneNode(true);+ var originalElements = Array.from(document.body.querySelectorAll("*"));+ var clonedElements = Array.from(clone.querySelectorAll("*"));+ for (var index = originalElements.length - 1; index >= 0; index -= 1) {+ var original = originalElements[index];+ var cloned = clonedElements[index];+ if (original.closest("svg")) continue;+ // ChartStyle is passive, component-generated CSS needed by the cloned+ // SVG. It has no layout box, so keep it out of rectangle pruning; every+ // unmarked style is still removed by the sanitizer below.+ if (+ original.tagName === "STYLE" &&+ original.hasAttribute("data-reload-snapshot-style")+ ) {+ continue;+ }+ var style = getComputedStyle(original);+ // Two shapes with empty rectangles that are nonetheless visible: a+ // `display: contents` wrapper generates no box however much its+ // children fill, and a closed select still paints its selected+ // option's label. Judging either by its rectangle drops what it shows.+ var paintsThroughSelect =+ (original.tagName === "OPTION" ||+ original.tagName === "OPTGROUP") &&+ original.closest("select");+ var laidOut = !paintsThroughSelect && style.display !== "contents";+ var bounds = laidOut ? original.getBoundingClientRect() : null;+ // Removing children from a scroll container changes its scroll geometry+ // and can shift the visible slice. Fully offscreen subtrees become+ // coalesced spacers at the first laid-out level outside the viewport;+ // this preserves the slice without serializing an unbounded transcript.+ var scrollContainer = nearestScrollContainer(original);+ var outsideViewport =+ laidOut &&+ (scrollContainer+ ? isOutsideScrollViewport(bounds, scrollContainer)+ : bounds.bottom <= 0 ||+ bounds.right <= 0 ||+ bounds.top >= innerHeight ||+ bounds.left >= innerWidth);+ if (+ style.display === "none" ||+ style.visibility === "hidden" ||+ outsideViewport+ ) {+ if (+ scrollContainer &&+ style.display !== "none" &&+ style.visibility !== "hidden" &&+ hasVisibleLayoutParent(original, scrollContainer)+ ) {+ replaceWithScrollSpacer(+ cloned,+ bounds,+ scrollContainer,+ );+ } else {+ cloned.remove();+ }+ } else {+ mirrorFieldState(original, cloned);+ mirrorScrollState(original, cloned);+ materializeEphemeralMedia(original, cloned, bounds);+ materializeCanvas(original, cloned, bounds);+ }+ }+ clone+ .querySelectorAll("iframe, object, embed, script, style, link, base")+ .forEach(function (element) {+ if (+ element.tagName === "STYLE" &&+ element.hasAttribute("data-reload-snapshot-style")+ ) {+ return;+ }+ element.remove();+ });+ clone.querySelectorAll("*").forEach(function (element) {+ // IDs are scoped to the closed shadow root, so they cannot collide with+ // the live document. Keep them for internal references such as+ // SVG fill="url(#gradient-id)" and aria-labelledby.+ element.removeAttribute("autofocus");+ element.removeAttribute("srcdoc");+ // SVG <use> carries the same URLs on xlink:href, which a plain `href`+ // lookup misses. javascript: cannot be activated on an inert copy, but+ // it has no reason to be stored either.+ [+ "src",+ "srcset",+ "poster",+ "href",+ "xlink:href",+ "action",+ "formaction",+ ].forEach(function (name) {+ var value = element.getAttribute(name);+ if (+ value &&+ (value.indexOf("blob:") !== -1 ||+ /^\s*javascript:/i.test(value) ||+ hasSensitiveUrl(value))+ ) {+ element.removeAttribute(name);+ }+ });+ Array.from(element.attributes).forEach(function (attribute) {+ if (attribute.name.toLowerCase().startsWith("on")) {+ element.removeAttribute(attribute.name);+ }+ });+ });+ clone.querySelectorAll("[data-reload-spacer]").forEach(function (element) {+ element.removeAttribute("data-reload-spacer-axis");+ element.removeAttribute("data-reload-spacer-start");+ element.removeAttribute("data-reload-spacer-end");+ element.removeAttribute("data-reload-spacer-cross");+ });+ var html = clone.innerHTML;+ if (html && html.length > maxSnapshotLength && dropMaterializedMedia(clone)) {+ html = clone.innerHTML;+ }+ if (!html || html.length > maxSnapshotLength) {+ clearStoredSnapshot();+ return;+ }+ sessionStorage.setItem(+ storageKey,+ JSON.stringify({+ createdAt: Date.now(),+ path: location.pathname + location.search,+ html: html,+ appearance: readAppearance(),+ tokens: readTokens(),+ styles: readStyleSheets(),+ inlineStyles: readInlineStyleSheets(),+ rootClass: document.documentElement.className,+ }),+ );+ } catch (error) {+ clearStoredSnapshot();+ }+ }++ function removeOverlay() {+ if (removalTimer !== null) {+ clearTimeout(removalTimer);+ removalTimer = null;+ }+ retainedSnapshot = null;+ if (!overlay) return;+ overlay.remove();+ overlay = null;+ }++ window.addEventListener("pageswap", function (event) {+ if (event.activation && event.activation.navigationType === "reload") {+ saveSnapshot();+ }+ });+ // Firefox, WebKitGTK and Safari before 18.2 do not expose pageswap, but+ // still deliver pagehide on reload. Do not register both: Chromium fires+ // pagehide after pageswap and a second full-DOM capture during unload is+ // both expensive and lower fidelity. pagehide cannot tell a reload from any+ // other unload, so on those engines a snapshot is also written when the user+ // navigates away; the restore side discards it (navigationType below).+ if (!("onpageswap" in window)) {+ window.addEventListener("pagehide", function (event) {+ if (!event.persisted) saveSnapshot();+ });+ }+ window.addEventListener("unsloth:app-shell-ready", function () {+ if (!overlay) return;+ requestAnimationFrame(function () {+ requestAnimationFrame(function () {+ removeOverlay();+ });+ });+ });++ // Fail open: the copy is a nicety, the real document is not.+ try {+ restoreSnapshot();+ } catch (error) {+ removeOverlay();+ }+})();diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex eed0c8db7a2..74137077c8c 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -74,6 +74,56 @@ function RouteFallback() {);}+// Retires the retained reload shell (public/reload-snapshot.js). It rides+// inside the route's own Suspense boundary, so a lazy page that is still+// resolving keeps the shell up instead of uncovering RouteFallback.+function signalReloadSnapshotReady() {+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+}++function ReloadSnapshotReady() {+ useLayoutEffect(() => {+ signalReloadSnapshotReady();+ }, []);+ return null;+}++// reload-snapshot.js runs outside React during pageswap. Mirror the in-memory+// privacy state onto the document so Temporary Chat is never serialized even+// briefly into sessionStorage.+function ReloadSnapshotPrivacy() {+ const incognito = useChatRuntimeStore((state) => state.incognito);++ useLayoutEffect(() => {+ document.documentElement.toggleAttribute(+ "data-reload-snapshot-private",+ incognito,+ );+ return () => {+ document.documentElement.removeAttribute(+ "data-reload-snapshot-private",+ );+ };+ }, [incognito]);++ return null;+}++function RouteBoundary({+ children,+ readyWhenCommitted = true,+}: {+ children: ReactNode;+ readyWhenCommitted?: boolean;+}) {+ return (+ <Suspense fallback={<RouteFallback />}>+ {readyWhenCommitted && <ReloadSnapshotReady />}+ {children}+ </Suspense>+ );+}+// ImagesPage is mounted persistently below (not via the /images route) so an in-flight batch survives leaving the tab,// mirroring ChatPage. Kept lazy so its bundle still loads only on the first /images visit.const ImagesPage = lazy(() =>@@ -216,6 +266,16 @@ function RootLayout() {const t = useT();const pathname = useRouterState({ select: (s) => s.location.pathname });const hideNavbar = HIDDEN_NAVBAR_ROUTES.includes(pathname);+ const routeOwnsReloadReadiness =+ pathname === "/hub" ||+ pathname === "/projects" ||+ pathname === "/export" ||+ pathname === "/studio" ||+ pathname === "/api-monitor" ||+ pathname === "/login" ||+ pathname === "/change-password" ||+ pathname === "/data-recipes" ||+ pathname.startsWith("/data-recipes/");const isAuthFlowRoute = useMatches({select: (matches) => matches.some((match) => match.staticData.isAuthFlow),});@@ -372,6 +432,7 @@ function RootLayout() {const content = (<><PersonalizationSyncMount />+ <ReloadSnapshotPrivacy />{!isAuthFlowRoute && <ChatSettingsHydrationMount />}{!isAuthFlowRoute && <SettingsDialog />}{/* Opens itself when API traffic arrives; hides on the full monitor page. */}@@ -383,9 +444,9 @@ function RootLayout() {<StopRunningChatsDialog />{hideNavbar ? (<main className="flex-1 pt-[var(--studio-hidden-route-top-inset,0px)] [--studio-titlebar-height:var(--studio-hidden-route-top-inset,0px)]">- <Suspense fallback={<RouteFallback />}>+ <RouteBoundary readyWhenCommitted={!routeOwnsReloadReadiness}><Outlet />- </Suspense>+ </RouteBoundary></main>) : (<SidebarProvider@@ -429,7 +490,10 @@ function RootLayout() {inert={!isImagesRoute || undefined}><Suspense fallback={<RouteFallback />}>- <ImagesPage active={isImagesRoute} />+ <ImagesPage+ active={isImagesRoute}+ onInitialReady={signalReloadSnapshotReady}+ /></Suspense></div>)}@@ -444,7 +508,10 @@ function RootLayout() {inert={!isVideoRoute || undefined}><Suspense fallback={<RouteFallback />}>- <VideoPage active={isVideoRoute} />+ <VideoPage+ active={isVideoRoute}+ onInitialReady={signalReloadSnapshotReady}+ /></Suspense></div>)}@@ -459,7 +526,10 @@ function RootLayout() {inert={!isAudioRoute || undefined}><Suspense fallback={<RouteFallback />}>- <AudioPage active={isAudioRoute} />+ <AudioPage+ active={isAudioRoute}+ onInitialReady={signalReloadSnapshotReady}+ /></Suspense></div>)}@@ -478,9 +548,9 @@ function RootLayout() {transition={{ duration: 0.06 }}className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-visible">- <Suspense fallback={<RouteFallback />}>+ <RouteBoundary readyWhenCommitted={!routeOwnsReloadReadiness}><Outlet />- </Suspense>+ </RouteBoundary></motion.div></AnimatePresence>)}diff --git a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-preview.tsxindex c084f70db6e..ec1bf1020ab 100644--- a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx@@ -78,16 +78,16 @@ const AttachmentPreviewTrigger: FC<PropsWithChildren> = ({ children }) => {);};-const AttachmentImageDialog: FC<PropsWithChildren<{ src: string }>> = ({- children,- src,-}) => {+const AttachmentImageDialog: FC<+ PropsWithChildren<{ src: string; redactFromReload?: boolean }>+> = ({ children, src, redactFromReload = false }) => {return (<Dialog><AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>{/* Chrome-free lightbox: the image floats on the dimmed backdrop withno dialog panel, and the close button sits in the screen corner. */}<DialogContent+ data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}overlayClassName="bg-black/70"className="aui-attachment-preview-dialog-content top-0 left-0 grid h-dvh w-screen max-h-none max-w-none translate-x-0 translate-y-0 place-items-center overflow-hidden rounded-none border-0 bg-transparent p-0 shadow-none ring-0 sm:max-w-none [&>button]:fixed [&>button]:top-4 [&>button]:right-4 [&>button]:z-20 [&>button]:size-9 [&>button]:rounded-full [&>button]:bg-transparent [&>button]:text-white [&>button]:opacity-100 [&>button]:ring-0! [&>button]:hover:bg-white/25 [&>button]:hover:text-white [&_svg]:text-white">@@ -196,8 +196,8 @@ const AttachmentTextBody: FC<{ text: string; language: string | null }> = ({};const AttachmentTextDialog: FC<- PropsWithChildren<{ source: AttachmentSource }>-> = ({ children, source }) => {+ PropsWithChildren<{ source: AttachmentSource; redactFromReload?: boolean }>+> = ({ children, source, redactFromReload = false }) => {const [opened, setOpened] = useState(false);const state = useAttachmentTextPreview(opened,@@ -249,7 +249,10 @@ const AttachmentTextDialog: FC<}}><AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>- <DialogContent className="aui-attachment-text-dialog-content gap-4 sm:max-w-2xl">+ <DialogContent+ data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}+ className="aui-attachment-text-dialog-content gap-4 sm:max-w-2xl"+ ><DialogHeader className="gap-1 pr-10"><DialogTitle className="truncate">{source.name || "Attachment"}@@ -304,12 +307,15 @@ const AttachmentAudioBody: FC<{ source: AttachmentSource }> = ({ source }) => {};const AttachmentAudioDialog: FC<- PropsWithChildren<{ source: AttachmentSource }>-> = ({ children, source }) => {+ PropsWithChildren<{ source: AttachmentSource; redactFromReload?: boolean }>+> = ({ children, source, redactFromReload = false }) => {return (<Dialog><AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>- <DialogContent className="aui-attachment-audio-dialog-content gap-4 sm:max-w-lg">+ <DialogContent+ data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}+ className="aui-attachment-audio-dialog-content gap-4 sm:max-w-lg"+ ><DialogHeader className="gap-1 pr-10"><DialogTitle className="truncate">{source.name || "Audio attachment"}@@ -329,14 +335,17 @@ const AttachmentAudioDialog: FC<);};-export const AttachmentPreviewDialog: FC<PropsWithChildren> = ({- children,-}) => {+export const AttachmentPreviewDialog: FC<+ /** Composer attachments are local and unsent, so keep them out of the reload snapshot. */+ PropsWithChildren<{ redactFromReload?: boolean }>+> = ({ children, redactFromReload = false }) => {const source = useAttachmentSource();if (source.kind === "image") {return source.src ? (- <AttachmentImageDialog src={source.src}>{children}</AttachmentImageDialog>+ <AttachmentImageDialog src={source.src} redactFromReload={redactFromReload}>+ {children}+ </AttachmentImageDialog>) : (children);@@ -344,7 +353,9 @@ export const AttachmentPreviewDialog: FC<PropsWithChildren> = ({if (source.kind === "audio") {return source.src || source.audio ? (- <AttachmentAudioDialog source={source}>{children}</AttachmentAudioDialog>+ <AttachmentAudioDialog source={source} redactFromReload={redactFromReload}>+ {children}+ </AttachmentAudioDialog>) : (children);@@ -355,6 +366,8 @@ export const AttachmentPreviewDialog: FC<PropsWithChildren> = ({}return (- <AttachmentTextDialog source={source}>{children}</AttachmentTextDialog>+ <AttachmentTextDialog source={source} redactFromReload={redactFromReload}>+ {children}+ </AttachmentTextDialog>);};diff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsxindex eec648089b6..5388bb5a60c 100644--- a/studio/frontend/src/components/assistant-ui/attachment.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx@@ -323,7 +323,7 @@ const AttachmentUI: FC = () => {"aui-attachment-root-composer only:[&>#attachment-tile]:size-16",)}>- <AttachmentPreviewDialog>+ <AttachmentPreviewDialog redactFromReload={isComposer}><TooltipTrigger asChild={true}><buttonclassName={cn(@@ -372,7 +372,10 @@ export const UserMessageAttachments: FC = () => {export const ComposerAttachments: FC = () => {return (- <div className="aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden">+ <div+ data-reload-snapshot-sensitive+ className="aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden"+ ><ComposerPrimitive.Attachmentscomponents={{ Attachment: AttachmentUI }}/>diff --git a/studio/frontend/src/components/image-dropzone.tsx b/studio/frontend/src/components/image-dropzone.tsxindex 7e5a71ae92a..00667642cb2 100644--- a/studio/frontend/src/components/image-dropzone.tsx+++ b/studio/frontend/src/components/image-dropzone.tsx@@ -116,7 +116,10 @@ export function ImageDropzone({if (value) {return (- <div className={cn("relative overflow-hidden rounded-[10px] border border-border", className)}>+ <div+ data-reload-snapshot-sensitive+ className={cn("relative overflow-hidden rounded-[10px] border border-border", className)}+ ><img src={value} alt="Source" className="max-h-44 w-full object-contain bg-muted/30" /><Tooltip><TooltipTrigger asChild={true}>diff --git a/studio/frontend/src/components/ui/chart.tsx b/studio/frontend/src/components/ui/chart.tsxindex 32da410bb5a..234b86f39d5 100644--- a/studio/frontend/src/components/ui/chart.tsx+++ b/studio/frontend/src/components/ui/chart.tsx@@ -153,6 +153,7 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {return (<style+ data-reload-snapshot-styledangerouslySetInnerHTML={{__html: Object.entries(THEMES).map(diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsxindex 888d46f7672..30413c042ca 100644--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx@@ -269,7 +269,11 @@ function RequestRow({{entry.model}</div>{entry.error ? (- <div className="min-w-0 break-words pl-4 text-ui-11 text-red-600 dark:text-red-400">+ // Backend error text can quote the request, so keep it out too.+ <div+ data-reload-snapshot-sensitive+ className="min-w-0 break-words pl-4 text-ui-11 text-red-600 dark:text-red-400"+ >{entry.error}</div>) : null}@@ -312,7 +316,9 @@ function RequestRow({<span>{formatTime(entry.started_at)}</span></span></div>+ {/* A prompt or reply excerpt, same as the expanded payload below it. */}<p+ data-reload-snapshot-sensitiveclassName={cn("line-clamp-2 pl-4 text-ui-11 leading-[1.45]",entry.error@@ -356,7 +362,9 @@ function PayloadBlock({) : null}</div></div>+ {/* Prompt and reply bodies, so keep them out of the reload snapshot. */}<pre+ data-reload-snapshot-sensitiveclassName={cn("max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted/50 p-3 text-ui-11 leading-[1.55]",tone === "error" && "bg-red-500/5 text-red-700 dark:text-red-400",@@ -530,6 +538,14 @@ export function ApiMonitorPage(): ReactElement {loadingDetails,requestDetail,} = useApiMonitor();+ const reloadReadySent = useRef(false);+ useEffect(() => {+ if (loading || reloadReadySent.current) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [loading]);const serverUrl = usePlatformStore((s) => s.serverUrl);const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);const [unloading, setUnloading] = useState(false);diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsxindex e4594e74843..3d9cc7d053b 100644--- a/studio/frontend/src/features/audio/audio-page.tsx+++ b/studio/frontend/src/features/audio/audio-page.tsx@@ -267,7 +267,14 @@ function formatClipDuration(seconds: number): string {return `${minutes}:${String(rest).padStart(2, "0")}`;}-export function AudioPage({ active = true }: { active?: boolean }) {+export function AudioPage({+ active = true,+ onInitialReady,+}: {+ active?: boolean;+ onInitialReady?: () => void;+}) {+ const initialReadySent = useRef(false);const [mode, setMode] = useState<CreateMode>("speak");const [selectorOpen, setSelectorOpen] = useState(false);const [busy, setBusy] = useState<AudioBusy>(null);@@ -648,10 +655,38 @@ export function AudioPage({ active = true }: { active?: boolean }) {// Resync on activation: another tab may have loaded/unloaded models meanwhile.useEffect(() => {if (!active) return;- void refreshStatus();- void refreshSttStatus();- void refreshGallery();- }, [active, refreshStatus, refreshSttStatus, refreshGallery]);+ if (initialReadySent.current) {+ void refreshStatus();+ void refreshSttStatus();+ void refreshGallery();+ return;+ }+ let cancelled = false;+ void (async () => {+ const [initialClips] = await Promise.all([+ refreshGallery(),+ refreshStatus(),+ refreshSttStatus(),+ ]);+ const initialSelection =+ initialClips.find((clip) => clip.id === galleryCache.selectedId) ??+ initialClips[0];+ if (initialSelection) await ensureClipSrc(initialSelection);+ if (cancelled || initialReadySent.current) return;+ initialReadySent.current = true;+ onInitialReady?.();+ })();+ return () => {+ cancelled = true;+ };+ }, [+ active,+ ensureClipSrc,+ onInitialReady,+ refreshGallery,+ refreshStatus,+ refreshSttStatus,+ ]);// Activation alone is not enough: the loaded-models indicator can eject the TTS model// out from under a page that stays active, leaving Generate enabled against an empty@@ -2160,7 +2195,12 @@ export function AudioPage({ active = true }: { active?: boolean }) {<div className="relative flex min-h-[60dvh] min-w-0 flex-1 flex-col overflow-hidden @[50rem]:min-h-0">{mode === "transcribe" ? (- <div className="hover-scrollbar flex flex-1 flex-col gap-3 overflow-auto p-6 px-10 @[50rem]:pt-[60px]">+ <div+ data-reload-snapshot-sensitive={+ transcript || transcribedName ? "" : undefined+ }+ className="hover-scrollbar flex flex-1 flex-col gap-3 overflow-auto p-6 px-10 @[50rem]:pt-[60px]"+ >{busy === "transcribing" ? (<div className="flex items-center gap-2 text-ui-13 text-muted-foreground"><Spinner className="size-4" />diff --git a/studio/frontend/src/features/auth/components/auth-form.tsx b/studio/frontend/src/features/auth/components/auth-form.tsxindex 1330de4b006..4495cfadaa2 100644--- a/studio/frontend/src/features/auth/components/auth-form.tsx+++ b/studio/frontend/src/features/auth/components/auth-form.tsx@@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Link, useNavigate } from "@tanstack/react-router";import { Eye, EyeOff } from "lucide-react";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import type { ReactElement } from "react";import type { SyntheticEvent } from "react";import { refreshSession } from "../api";@@ -88,6 +88,7 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {const [initialized, setInitialized] = useState<boolean | null>(null);const [requiresPasswordChange, setRequiresPasswordChange] = useState(false);const [error, setError] = useState<string | null>(null);+ const reloadReadySent = useRef(false);useEffect(() => {let canceled = false;@@ -153,6 +154,12 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {};}, [navigate]);+ useEffect(() => {+ if (statusLoading || reloadReadySent.current) return;+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [statusLoading]);+// Seed password from bootstrap credentials injected into HTML by web CLI.useEffect(() => {function loadBootstrap() {diff --git a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsxindex b498892ef56..d51be01668e 100644--- a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx@@ -164,6 +164,7 @@ function HeadersEditor({onChange={(e) => update(row.id, { key: e.target.value })}/><Input+ data-reload-snapshot-sensitivevalue={row.value}placeholder={copy.valuePlaceholder}onChange={(e) => update(row.id, { value: e.target.value })}diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 8bde21de737..020b762e201 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -612,6 +612,7 @@ function ComparePane({handleName,header,borderClassName,+ onInitialHistoryReady,}: {modelType: "base" | "lora" | "model1" | "model2";pairId: string;@@ -620,7 +621,15 @@ function ComparePane({handleName: string;header: ReactElement;borderClassName?: string;+ onInitialHistoryReady?: (pane: string) => void;}): ReactElement {+ const signalInitialHistoryReady = useMemo(+ () =>+ onInitialHistoryReady+ ? () => onInitialHistoryReady(modelType)+ : undefined,+ [modelType, onInitialHistoryReady],+ );return (<divclassName={cn(@@ -636,6 +645,7 @@ function ComparePane({projectId={projectId}initialThreadId={initialThreadId}syncActiveThreadId={false}+ onInitialHistoryReady={signalInitialHistoryReady}><RegisterCompareHandle name={handleName} /><Thread hideComposer={true} hideWelcome={true} />@@ -645,6 +655,32 @@ function ComparePane({);}+function useCompareReloadReadiness(pairId: string): (pane: string) => void {+ const stateRef = useRef({+ pairId,+ panes: new Set<string>(),+ sent: false,+ });+ if (stateRef.current.pairId !== pairId) {+ stateRef.current = { pairId, panes: new Set<string>(), sent: false };+ }+ return useCallback(+ (pane: string) => {+ const state = stateRef.current;+ if (state.pairId !== pairId || state.sent) {+ return;+ }+ state.panes.add(pane);+ if (state.panes.size < 2) {+ return;+ }+ state.sent = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ },+ [pairId],+ );+}+/*** Shared shell for both compare variants: a flex column with the two panes* as siblings and the shared composer docked at the bottom. Panes stack on@@ -701,6 +737,8 @@ const LoraCompareContent = memo(function LoraCompareContent({const handlesRef = useRef<Record<string, CompareHandle>>({});const [baseThreadId, setBaseThreadId] = useState<string>();const [loraThreadId, setLoraThreadId] = useState<string>();+ const [threadsSettled, setThreadsSettled] = useState(false);+ const markInitialHistoryReady = useCompareReloadReadiness(pairId);const active = useChatActive();const compareRunning = useChatRuntimeStore(@@ -710,6 +748,7 @@ const LoraCompareContent = memo(function LoraCompareContent({useEffect(() => {if (compareRunning) return;let isActive = true;+ setThreadsSettled(false);listStoredChatThreads({ pairId }).then((threads) => {if (!isActive) return;@@ -720,12 +759,26 @@ const LoraCompareContent = memo(function LoraCompareContent({if (!isExpectedBackgroundChatStorageError(error)) {throw error;}+ })+ .finally(() => {+ if (isActive) setThreadsSettled(true);});return () => {isActive = false;};}, [pairId, compareRunning]);+ useEffect(() => {+ if (!threadsSettled) return;+ if (!baseThreadId) markInitialHistoryReady("base");+ if (!loraThreadId) markInitialHistoryReady("lora");+ }, [+ baseThreadId,+ loraThreadId,+ markInitialHistoryReady,+ threadsSettled,+ ]);+return (<CompareShellhandlesRef={handlesRef}@@ -749,6 +802,9 @@ const LoraCompareContent = memo(function LoraCompareContent({projectId={projectId}initialThreadId={baseThreadId}handleName="base"+ onInitialHistoryReady={+ threadsSettled ? markInitialHistoryReady : undefined+ }header={<div className="shrink-0 px-3 py-1.5"><span className="text-ui-10 font-semibold uppercase tracking-wider text-muted-foreground">@@ -763,6 +819,9 @@ const LoraCompareContent = memo(function LoraCompareContent({projectId={projectId}initialThreadId={loraThreadId}handleName="lora"+ onInitialHistoryReady={+ threadsSettled ? markInitialHistoryReady : undefined+ }borderClassName="border-t border-border/60 md:border-t-0 md:border-l"header={<div className="shrink-0 px-3 py-1.5 text-start md:text-end md:pr-[calc(4rem+var(--studio-chat-header-right-inset,var(--studio-window-control-inset,0px)))]">@@ -876,6 +935,8 @@ const GeneralCompareContent = memo(function GeneralCompareContent({const handlesRef = useRef<Record<string, CompareHandle>>({});const [model1ThreadId, setModel1ThreadId] = useState<string>();const [model2ThreadId, setModel2ThreadId] = useState<string>();+ const [threadsSettled, setThreadsSettled] = useState(false);+ const markInitialHistoryReady = useCompareReloadReadiness(pairId);const globalCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);const globalGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);@@ -911,6 +972,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({useEffect(() => {if (compareRunning) return;let isActive = true;+ setThreadsSettled(false);listStoredChatThreads({ pairId }).then((threads) => {if (!isActive) return;@@ -929,12 +991,26 @@ const GeneralCompareContent = memo(function GeneralCompareContent({if (!isExpectedBackgroundChatStorageError(error)) {throw error;}+ })+ .finally(() => {+ if (isActive) setThreadsSettled(true);});return () => {isActive = false;};}, [pairId, compareRunning]);+ useEffect(() => {+ if (!threadsSettled) return;+ if (!model1ThreadId) markInitialHistoryReady("model1");+ if (!model2ThreadId) markInitialHistoryReady("model2");+ }, [+ markInitialHistoryReady,+ model1ThreadId,+ model2ThreadId,+ threadsSettled,+ ]);+return (<CompareShellhandlesRef={handlesRef}@@ -960,6 +1036,9 @@ const GeneralCompareContent = memo(function GeneralCompareContent({projectId={projectId}initialThreadId={model1ThreadId}handleName="model1"+ onInitialHistoryReady={+ threadsSettled ? markInitialHistoryReady : undefined+ }header={<GeneralCompareHeaderside="left"@@ -991,6 +1070,9 @@ const GeneralCompareContent = memo(function GeneralCompareContent({projectId={projectId}initialThreadId={model2ThreadId}handleName="model2"+ onInitialHistoryReady={+ threadsSettled ? markInitialHistoryReady : undefined+ }borderClassName="border-t border-sidebar-border md:border-t-0 md:border-l"header={<GeneralCompareHeader@@ -1121,10 +1203,12 @@ function ProjectLanding({projectId,projectName,items,+ dataLoaded,}: {projectId: string;projectName: string;items: SidebarItem[];+ dataLoaded: boolean;}): ReactElement {const navigate = useNavigate();// Gates body-portaled surfaces so they can't linger or act while the landing@@ -1149,6 +1233,9 @@ function ProjectLanding({const [previews, setPreviews] = useState<Record<string, { snippet: string; date: string }>>({});+ const [runtimeReady, setRuntimeReady] = useState(false);+ const reloadReadySent = useRef(false);+ const markRuntimeReady = useCallback(() => setRuntimeReady(true), []);// Inline rename, mirroring the sidebar recent-row UX: edit the title in place,// commit on Enter/blur, cancel on Escape. Reuses the projectId-agnostic// renameChatItem so behavior matches the sidebar.@@ -1456,12 +1543,27 @@ function ProjectLanding({};}, [items]);+ useEffect(() => {+ const previewsReady = items.every((item) => previews[item.id] !== undefined);+ if (+ !dataLoaded ||+ !runtimeReady ||+ !previewsReady ||+ reloadReadySent.current+ ) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [dataLoaded, items, previews, runtimeReady]);+return (<ChatRuntimeProviderkey={projectId}projectId={projectId}newThreadNonce={newThreadNonce}listThreads={false}+ onInitialHistoryReady={markRuntimeReady}>{pendingNewThreadId ? (<div className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">@@ -2080,9 +2182,10 @@ export function ChatPage({const currentProject = currentProjectId? (projects.find((project) => project.id === currentProjectId) ?? null): null;- const { items: currentProjectItems } = useChatSidebarItems({+ const { items: currentProjectItems, loaded: currentProjectItemsLoaded } =+ useChatSidebarItems({projectId: currentProjectId ?? "__no_project_selected__",- });+ });const currentChatTitle = activeThreadId? currentProjectItems.find((item) => item.id === activeThreadId)?.title: undefined;@@ -3770,6 +3873,7 @@ export function ChatPage({projectId={view.projectId}projectName={currentProject?.name ?? "Project"}items={currentProjectItems}+ dataLoaded={currentProjectItemsLoaded && !projectsLoading}/>) : view.mode === "single" ? (// Keyed by project only (not thread / new-chat nonce) so switching threads ordiff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsxindex 53d784533ee..4b6aec15a8c 100644--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx@@ -1434,6 +1434,7 @@ export function ChatProvidersSettings({<Inputid="provider-api-key"type={showApiKey ? "text" : "password"}+ data-reload-snapshot-sensitivevalue={apiKey}onChange={(event) => {setApiKey(event.target.value);diff --git a/studio/frontend/src/features/chat/openai-codex-connect.tsx b/studio/frontend/src/features/chat/openai-codex-connect.tsxindex 8382d8a5bad..5b4beb724fd 100644--- a/studio/frontend/src/features/chat/openai-codex-connect.tsx+++ b/studio/frontend/src/features/chat/openai-codex-connect.tsx@@ -180,7 +180,7 @@ export function OpenAICodexConnect({</p></div>{flow?.method === "device" && flow.status === "pending" ? (- <div className="space-y-2 text-sm">+ <div data-reload-snapshot-sensitive className="space-y-2 text-sm"><p>Enter this code in ChatGPT:</p><code className="block w-fit rounded bg-muted px-3 py-2 font-mono text-base">{flow.user_code}</code><p className="text-xs text-muted-foreground">Device login may need to be enabled in ChatGPT security or workspace settings.</p>@@ -203,7 +203,7 @@ export function OpenAICodexConnect({<div className="space-y-2"><p className="text-xs text-muted-foreground">If the browser cannot return automatically, paste the complete localhost callback URL.</p><div className="flex gap-2">- <Input value={callbackUrl} onChange={(event) => setCallbackUrl(event.target.value)} placeholder="http://localhost:1455/auth/callback?..." />+ <Input data-reload-snapshot-sensitive value={callbackUrl} onChange={(event) => setCallbackUrl(event.target.value)} placeholder="http://localhost:1455/auth/callback?..." /><Button type="button" variant="outline" disabled={busy || !callbackUrl.trim()} onClick={() => void complete()}>Complete</Button></div></div>diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsxindex e06f9c250b0..54e13302705 100644--- a/studio/frontend/src/features/chat/projects-page.tsx+++ b/studio/frontend/src/features/chat/projects-page.tsx@@ -121,6 +121,7 @@ export function ProjectsPage() {const [extraCount, setExtraCount] = useState(0);const listRef = useRef<HTMLDivElement>(null);const sentinelRef = useRef<HTMLDivElement>(null);+ const reloadReadySent = useRef(false);const pinnedProjectIds = usePinnedProjectsStore((s) => s.pinnedIds);const togglePinProject = usePinnedProjectsStore((s) => s.togglePin);const pinnedProjectIdSet = useMemo(@@ -256,6 +257,14 @@ export function ProjectsPage() {: sortedProjects.slice(0, visibleCount);const hasMore = !isSearching && sortedProjects.length > visibleCount;+ useEffect(() => {+ if (!hasLoaded || reloadReadySent.current) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [hasLoaded]);+// Estimate how many rows fit below the list's top so the first page fills the// screen without loading everything up front.useEffect(() => {@@ -743,7 +752,15 @@ export function ProjectsPage() {</DialogHeader><p className="text-sm text-muted-foreground">Choose where to import{" "}- <span className="font-medium text-foreground">{importFile?.name}</span>:+ {/* A picked local file, and the dialog portals out of any marked+ ancestor, so the name needs its own marker. */}+ <span+ data-reload-snapshot-sensitive+ className="font-medium text-foreground"+ >+ {importFile?.name}+ </span>+ :</p><Selectvalue={importTargetId ?? "__recents__"}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex ecf72fa49e6..52e4c60fcba 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -1137,6 +1137,8 @@ function createPersistedRunAdapter(function useStudioRuntimeAdapters(modelType: ModelType,pairId?: string,+ reloadReadyThreadId?: string,+ onInitialHistoryReady?: () => void,): StudioRuntimeAdapters {const aui = useAui();@@ -1302,9 +1304,25 @@ function useStudioRuntimeAdapters(const history = useMemo<ThreadHistoryAdapter>(() => ({async load() {+ const completeLoad = <T,>(result: T, loadedThreadId?: string): T => {+ // A runtime bootstraps on an empty thread before switching to the+ // requested one, so an unrequested load is not readiness.+ const loadedTheRequestedThread =+ !reloadReadyThreadId || loadedThreadId === reloadReadyThreadId;+ if (onInitialHistoryReady) {+ if (loadedTheRequestedThread) onInitialHistoryReady();+ } else if (+ modelType === "base" &&+ !pairId &&+ loadedTheRequestedThread+ ) {+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }+ return result;+ };const { remoteId } = aui.threadListItem().getState();if (!remoteId) {- return { messages: [] };+ return completeLoad({ messages: [] });}const roleOrder: Record<string, number> = {system: 0,@@ -1411,18 +1429,24 @@ function useStudioRuntimeAdapters(const hasParentIds = msgs.some((m) => m.parentId != null);if (hasParentIds) {let previousId: string | null = null;- return {- messages: msgs.map((m) => {- const parentId = m.parentId != null ? m.parentId : previousId;- previousId = m.id;- return {- parentId,- message: toThreadMessage(m),- };- }),- };+ return completeLoad(+ {+ messages: msgs.map((m) => {+ const parentId = m.parentId != null ? m.parentId : previousId;+ previousId = m.id;+ return {+ parentId,+ message: toThreadMessage(m),+ };+ }),+ },+ remoteId,+ );}- return ExportedMessageRepository.fromArray(msgs.map(toThreadMessage));+ return completeLoad(+ ExportedMessageRepository.fromArray(msgs.map(toThreadMessage)),+ remoteId,+ );},append({ parentId, message }: ExportedMessageRepositoryItem) {@@ -1527,7 +1551,13 @@ function useStudioRuntimeAdapters(return trackHistoryAppend(message.id, write);},}),- [aui, modelType, pairId],+ [+ aui,+ modelType,+ onInitialHistoryReady,+ pairId,+ reloadReadyThreadId,+ ],);// Always register the adapter so the mic stays clickable for any engine. The@@ -1577,8 +1607,15 @@ function useStudioRuntimeAdapters(function useRuntimeHook(modelType: ModelType,pairId?: string,+ reloadReadyThreadId?: string,+ onInitialHistoryReady?: () => void,): ReturnType<typeof useLocalRuntime> {- const adapters = useStudioRuntimeAdapters(modelType, pairId);+ const adapters = useStudioRuntimeAdapters(+ modelType,+ pairId,+ reloadReadyThreadId,+ onInitialHistoryReady,+ );const persistedChatAdapter = useMemo(() =>createPersistedRunAdapter(@@ -1589,20 +1626,32 @@ function useRuntimeHook(return useLocalRuntime(persistedChatAdapter, { adapters });}-function createRuntimeHook(modelType: ModelType, pairId?: string) {+function createRuntimeHook(+ modelType: ModelType,+ pairId?: string,+ reloadReadyThreadId?: string,+ onInitialHistoryReady?: () => void,+) {return function useConfiguredRuntimeHook(): ReturnType<typeof useLocalRuntime> {- return useRuntimeHook(modelType, pairId);+ return useRuntimeHook(+ modelType,+ pairId,+ reloadReadyThreadId,+ onInitialHistoryReady,+ );};}function ThreadAutoSwitch({threadId,syncActiveThreadId = true,+ onSwitchFailed,}: {threadId: string;syncActiveThreadId?: boolean;+ onSwitchFailed?: () => void;}): ReactElement | null {const aui = useAui();const isLoading = useAuiState(({ threads }) => threads.isLoading);@@ -1622,10 +1671,18 @@ function ThreadAutoSwitch({if (syncActiveThreadId) {useChatRuntimeStore.getState().setActiveThreadId(null);}+ onSwitchFailed?.();});}}- }, [aui, isLoading, mainThreadId, syncActiveThreadId, threadId]);+ }, [+ aui,+ isLoading,+ mainThreadId,+ onSwitchFailed,+ syncActiveThreadId,+ threadId,+ ]);useEffect(() => {if (!syncActiveThreadId || isLoading || mainThreadId !== threadId) {@@ -2174,6 +2231,7 @@ export function ChatRuntimeProvider({newThreadNonce,syncActiveThreadId = true,listThreads = true,+ onInitialHistoryReady,}: {children: ReactNode;modelType?: ModelType;@@ -2183,15 +2241,29 @@ export function ChatRuntimeProvider({newThreadNonce?: string;syncActiveThreadId?: boolean;listThreads?: boolean;+ onInitialHistoryReady?: () => void;}): ReactElement {const runtimeHook = useMemo(- () => createRuntimeHook(modelType, pairId),- [modelType, pairId],+ () =>+ createRuntimeHook(+ modelType,+ pairId,+ initialThreadId,+ onInitialHistoryReady,+ ),+ [initialThreadId, modelType, onInitialHistoryReady, pairId],);const runtime = useRemoteThreadListRuntime({runtimeHook,adapter: createStudioDbAdapter(modelType, pairId, projectId, listThreads),});+ const signalFailedInitialSwitchReady = useCallback(() => {+ if (onInitialHistoryReady) {+ onInitialHistoryReady();+ } else if (modelType === "base" && !pairId) {+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }+ }, [modelType, onInitialHistoryReady, pairId]);const aui = useAui({});@@ -2218,6 +2290,7 @@ export function ChatRuntimeProvider({<ThreadAutoSwitchthreadId={initialThreadId}syncActiveThreadId={syncActiveThreadId}+ onSwitchFailed={signalFailedInitialSwitchReady}/>)}{!initialThreadId && newThreadNonce && (diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex af6dce9e7ae..6cdd34bbf43 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -466,7 +466,10 @@ function PendingImageThumb({if (!src)return <div className="size-14 animate-pulse rounded-[14px] bg-muted" />;return (- <div className="relative size-14 shrink-0 overflow-hidden rounded-[14px] border border-foreground/20 bg-muted">+ <div+ data-reload-snapshot-sensitive+ className="relative size-14 shrink-0 overflow-hidden rounded-[14px] border border-foreground/20 bg-muted"+ ><img src={src} alt={file.name} className="h-full w-full object-cover" /><buttontype="button"@@ -2127,7 +2130,9 @@ export function SharedComposer({{pendingAudio && (<div className="flex items-center gap-2 rounded-lg border border-foreground/20 bg-muted px-3 py-1.5 text-xs"><HeadphonesIcon className="size-3.5 text-muted-foreground" />- <span className="max-w-48 truncate">{pendingAudio.name}</span>+ <span data-reload-snapshot-sensitive className="max-w-48 truncate">+ {pendingAudio.name}+ </span><buttontype="button"onClick={() => {diff --git a/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx b/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsxindex 550a8b5b58e..ad05ca01cd4 100644--- a/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx+++ b/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx@@ -43,7 +43,7 @@ import {import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate } from "@tanstack/react-router";import type { ReactElement } from "react";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import {createRecipeDraft,createRecipeFromLearningRecipe,@@ -318,6 +318,15 @@ export function DataRecipesPage(): ReactElement {const [loadingTemplateId, setLoadingTemplateId] = useState<string | null>(null,);+ const reloadReadySent = useRef(false);++ useEffect(() => {+ if (!ready || reloadReadySent.current) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [ready]);useEffect(() => {if (sessionStorage.getItem(OPEN_LEARNING_RECIPES_ON_ARRIVAL_KEY) !== "1") {diff --git a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsxindex e5a6d3844c5..2c6dd1f9a38 100644--- a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx+++ b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";import { RecipeStudioPage, type RecipePayload } from "@/features/recipe-studio";import { useNavigate } from "@tanstack/react-router";import type { ReactElement } from "react";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { getCachedRecipe, getRecipe, primeRecipeCache, saveRecipe } from "../data/recipes-db";import type { RecipeRecord } from "../types";@@ -44,6 +44,7 @@ function RecipeLoadState({export function EditRecipePage({ recipeId }: EditRecipePageProps): ReactElement {const navigate = useNavigate();+ const reloadReadySent = useRef(false);const [loadState, setLoadState] = useState<LoadState>(() => {const cachedRecipe = getCachedRecipe(recipeId);if (cachedRecipe) {@@ -77,6 +78,14 @@ export function EditRecipePage({ recipeId }: EditRecipePageProps): ReactElement};}, [recipeId]);+ useEffect(() => {+ if (loadState.status === "loading" || reloadReadySent.current) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [loadState.status]);+const handlePersist = useCallback(async (input: { id: string | null; name: string; payload: RecipePayload }) => {const record = await saveRecipe({diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsxindex c5e35435a11..b79aff528f7 100644--- a/studio/frontend/src/features/export/export-page.tsx+++ b/studio/frontend/src/features/export/export-page.tsx@@ -363,6 +363,19 @@ export function ExportPage() {};}, []);+ const reloadReadySent = useRef(false);+ useEffect(() => {+ if (+ loadingCheckpoints ||+ isLoadingLocalModels ||+ reloadReadySent.current+ ) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [isLoadingLocalModels, loadingCheckpoints]);+// ---- Derived state ----const selectedModelData = useMemo(() =>diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex 287bfc738b6..14a893a9dbd 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -400,6 +400,8 @@ export function ModelsPage() {const activeGgufContextLength = useChatRuntimeStore((s) => s.ggufContextLength,);+ const [initialResidentStatusSettled, setInitialResidentStatusSettled] =+ useState(false);// Live settings of the loaded model, so its page shows what it is running with.const { config: activeModelConfig } = useActiveModelConfig();// Shared with the chat model selector: list only models sized for this device.@@ -476,11 +478,15 @@ export function ModelsPage() {// Mount, then whenever this tab could have missed an API-driven switch. Re-reading is safe.useEffect(() => {- void refreshResidentModelStatus();+ let active = true;+ void refreshResidentModelStatus().finally(() => {+ if (active) setInitialResidentStatusSettled(true);+ });const unsubscribe = subscribeResidentStatusRefresh(refreshResidentModelStatus,);return () => {+ active = false;// A response still in flight adopts nothing once the Hub is gone.residentStatusSeq.current += 1;unsubscribe();@@ -785,11 +791,30 @@ export function ModelsPage() {availableSet,partialSet,downloadedReady,+ inventorySettled,inventoryError,inventoryWarning,refreshInventory,} = useHubInventory({ kind: isDatasetMode ? "datasets" : "models" });+ const reloadReadySent = useRef(false);+ useEffect(() => {+ if (+ reloadReadySent.current ||+ !initialResidentStatusSettled ||+ (isDiscoverTab ? isLoading : !inventorySettled)+ ) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [+ initialResidentStatusSettled,+ inventorySettled,+ isDiscoverTab,+ isLoading,+ ]);+const modelDiscoveryInventorySignature = useMemo(() => discoveryInventorySignature(effectiveCachedRows, effectiveLocalRows),[effectiveCachedRows, effectiveLocalRows],diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 8c30651ff61..fd9998fd49d 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -1167,7 +1167,14 @@ type LoadAdvanced = Pick<| "gpu_ids">;-export function ImagesPage({ active = true }: { active?: boolean }) {+export function ImagesPage({+ active = true,+ onInitialReady,+}: {+ active?: boolean;+ onInitialReady?: () => void;+}) {+ const initialReadySent = useRef(false);const { isMobile, pinned } = useSidebar();const hostClass = useHostClass();const imageModels = useImageModels(hostClass);@@ -1761,11 +1768,6 @@ export function ImagesPage({ active = true }: { active?: boolean }) {})();}, [selected, ensureSrc]);- useEffect(() => {- void loadGallery();- }, [loadGallery]);--// Drop an image from the strip. `discardBlob` is for a real delete: the bytes are gone, so the// cached object URL must be revoked and any in-flight fetch told to throw its blob away. An// archived image keeps both, since the archived view shows the same thumbnail.@@ -2088,10 +2090,31 @@ export function ImagesPage({ active = true }: { active?: boolean }) {// Re-sync model status when the tab becomes active: the model may have been evicted while off-tab.useEffect(() => {if (!active) return;+ if (initialReadySent.current) {+ void refreshStatus();+ return;+ }+ let cancelled = false;void (async () => {- await refreshStatus();+ await Promise.all([+ refreshStatus(),+ (async () => {+ await loadGallery();+ const initialSelection =+ galleryCache.images.find(+ (image) => image.id === galleryCache.selectedId,+ ) ?? galleryCache.images[0];+ if (initialSelection) await ensureSrc(initialSelection);+ })(),+ ]);+ if (cancelled || initialReadySent.current) return;+ initialReadySent.current = true;+ onInitialReady?.();})();- }, [active, refreshStatus]);+ return () => {+ cancelled = true;+ };+ }, [active, ensureSrc, loadGallery, onInitialReady, refreshStatus]);// Ejected from the loaded models indicator, which does not run handleUnload:// without this the controls keep offering to generate on a freed runtime, anddiff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsxindex 2c87db30cee..5935b847b15 100644--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx@@ -391,6 +391,7 @@ export function ProjectSourceDropzone({className="size-4 shrink-0 text-muted-foreground"/><span+ data-reload-snapshot-sensitiveclassName="min-w-0 flex-1 truncate text-ui-14 text-foreground"title={entry.name}>@@ -401,6 +402,7 @@ export function ProjectSourceDropzone({</span><buttontype="button"+ data-reload-snapshot-sensitivearia-label={`Remove ${entry.name}`}disabled={disabled}onClick={() =>diff --git a/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx b/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsxindex b7354c1805a..a678dad9a83 100644--- a/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx+++ b/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx@@ -41,6 +41,7 @@ export function InlineModel(props: InlineModelProps): ReactElement {<InlineField label="API key"><InputclassName="nodrag h-8 w-full text-xs"+ data-reload-snapshot-sensitiveplaceholder="Optional"value={props.config.api_key ?? ""}onChange={(event) =>diff --git a/studio/frontend/src/features/recipe-studio/dialogs/models/model-provider-dialog.tsx b/studio/frontend/src/features/recipe-studio/dialogs/models/model-provider-dialog.tsxindex 6d68f8e2e45..632cde60753 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/models/model-provider-dialog.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/models/model-provider-dialog.tsx@@ -183,6 +183,7 @@ export function ModelProviderDialog({<Inputid={apiKeyId}className="nodrag"+ data-reload-snapshot-sensitivevalue={config.api_key ?? ""}onChange={(event) => updateField("api_key", event.target.value)}/>@@ -220,6 +221,7 @@ export function ModelProviderDialog({<Textareaid={extraHeadersId}className="corner-squircle nodrag"+ data-reload-snapshot-sensitiveplaceholder='{"X-Header": "value"}'value={config.extra_headers ?? ""}onChange={(event) =>@@ -236,6 +238,7 @@ export function ModelProviderDialog({<Textareaid={extraBodyId}className="corner-squircle nodrag"+ data-reload-snapshot-sensitiveplaceholder='{"key": "value"}'value={config.extra_body ?? ""}onChange={(event) =>diff --git a/studio/frontend/src/features/recipe-studio/dialogs/seed/seed-dialog.tsx b/studio/frontend/src/features/recipe-studio/dialogs/seed/seed-dialog.tsxindex fedd603a9dc..f21c3c059c1 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/seed/seed-dialog.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/seed/seed-dialog.tsx@@ -1004,6 +1004,7 @@ export function SeedDialog({<Inputid={tokenId}className="nodrag"+ data-reload-snapshot-sensitiveplaceholder="hf_..."value={config.hf_token ?? ""}onChange={(event) =>@@ -1052,7 +1053,10 @@ export function SeedDialog({</p>{(localFile?.name || config.local_file_name?.trim()) && (<p className="text-xs text-muted-foreground">- Selected: {localFile?.name ?? config.local_file_name?.trim()}+ Selected:{" "}+ <span data-reload-snapshot-sensitive>+ {localFile?.name ?? config.local_file_name?.trim()}+ </span></p>)}</div>diff --git a/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx b/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsxindex 983f0607c93..702b9491fe6 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx@@ -293,7 +293,10 @@ export function UnstructuredDropZone({className="size-4 text-red-500"/>)}- <span className="flex-1 truncate">{entry.name}</span>+ {/* Queued local upload, so keep the name out of the snapshot. */}+ <span data-reload-snapshot-sensitive className="flex-1 truncate">+ {entry.name}+ </span><span className="text-muted-foreground text-xs">{formatSize(entry.size)}</span>diff --git a/studio/frontend/src/features/recipe-studio/dialogs/tool-profile/tool-profile-dialog.tsx b/studio/frontend/src/features/recipe-studio/dialogs/tool-profile/tool-profile-dialog.tsxindex 802729fcd89..5c176262fda 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/tool-profile/tool-profile-dialog.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/tool-profile/tool-profile-dialog.tsx@@ -271,6 +271,7 @@ function McpServerCard({/><InputclassName="nodrag"+ data-reload-snapshot-sensitivevalue={item.value}placeholder="value"onChange={(event) =>@@ -329,6 +330,7 @@ function McpServerCard({/><InputclassName="nodrag"+ data-reload-snapshot-sensitivevalue={provider.api_key ?? ""}placeholder="token"onChange={(event) =>diff --git a/studio/frontend/src/features/settings/components/key-reveal-card.tsx b/studio/frontend/src/features/settings/components/key-reveal-card.tsxindex 80c93d77706..a67bbe9c0a7 100644--- a/studio/frontend/src/features/settings/components/key-reveal-card.tsx+++ b/studio/frontend/src/features/settings/components/key-reveal-card.tsx@@ -52,7 +52,10 @@ export function KeyRevealCard({: t("settings.apiKeys.copyAccessToken")}>- <code className="min-w-0 flex-1 break-all text-left text-foreground">+ <code+ className="min-w-0 flex-1 break-all text-left text-foreground"+ data-reload-snapshot-sensitive+ >{rawKey}</code><HugeiconsIcondiff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsxindex f89ce969eeb..12eaafb71cb 100644--- a/studio/frontend/src/features/settings/components/usage-examples.tsx+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx@@ -485,16 +485,21 @@ const codePlugin = createCodePlugin({ themes: SHIKI_THEMES });function HighlightedCode({code,language,+ redactFromReload,}: {code: string;language: string;+ redactFromReload: boolean;}) {const markdown = useMemo(() => `\`\`\`${language}\n${code}\n\`\`\``,[code, language],);return (- <div className="max-w-full overflow-x-auto p-3 pr-16 text-ui-11 leading-relaxed [&_pre]:!m-0 [&_pre]:!whitespace-pre-wrap [&_pre]:!break-words [&_pre]:!border-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:!text-ui-11 [&_pre]:!leading-relaxed [&_code]:!text-ui-11 [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_[data-streamdown=code-block]]:!text-ui-11">+ <div+ className="max-w-full overflow-x-auto p-3 pr-16 text-ui-11 leading-relaxed [&_pre]:!m-0 [&_pre]:!whitespace-pre-wrap [&_pre]:!break-words [&_pre]:!border-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:!text-ui-11 [&_pre]:!leading-relaxed [&_code]:!text-ui-11 [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_[data-streamdown=code-block]]:!text-ui-11"+ data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}+ ><Streamdownmode="static"plugins={{ code: codePlugin }}@@ -838,6 +843,7 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {key={snippets[lang]}code={snippets[lang]}language={shikiLang}+ redactFromReload={Boolean(apiKey)}/></div>) : (@@ -890,7 +896,10 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {})}</div><div className="relative mt-0.5 min-w-0">- <code className="block min-w-0 overflow-x-auto rounded border border-border bg-muted/30 px-2 py-1.5 pr-14 font-mono text-ui-11 text-foreground">+ <code+ className="block min-w-0 overflow-x-auto rounded border border-border bg-muted/30 px-2 py-1.5 pr-14 font-mono text-ui-11 text-foreground"+ data-reload-snapshot-sensitive={apiKey ? "" : undefined}+ >{agentCommand}</code><buttondiff --git a/studio/frontend/src/features/studio/sections/s3-config-form.tsx b/studio/frontend/src/features/studio/sections/s3-config-form.tsxindex e7daffb750d..dc6ac00dffb 100644--- a/studio/frontend/src/features/studio/sections/s3-config-form.tsx+++ b/studio/frontend/src/features/studio/sections/s3-config-form.tsx@@ -115,6 +115,7 @@ export function S3ConfigForm() {</Label><Inputid="s3-access-key"+ data-reload-snapshot-sensitivevalue={config.accessKeyId ?? ""}onChange={(e) => update({ accessKeyId: e.target.value })}placeholder={t("studio.dataset.s3.accessKeyIdPlaceholder")}diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsxindex e47595ecad4..87808544a62 100644--- a/studio/frontend/src/features/studio/studio-page.tsx+++ b/studio/frontend/src/features/studio/studio-page.tsx@@ -157,6 +157,19 @@ export function StudioPage(): ReactElement {// verdict is unknown and writes it to this same store, so no second poll is needed here.const showTrainingHydrating =capabilitiesUnknown || (!hasHydratedRuntime && isHydratingRuntime);+ const reloadReadySent = useRef(false);+ useEffect(() => {+ if (+ capabilitiesUnknown ||+ !hasHydratedRuntime ||+ isHydratingRuntime ||+ reloadReadySent.current+ ) {+ return;+ }+ reloadReadySent.current = true;+ window.dispatchEvent(new Event("unsloth:app-shell-ready"));+ }, [capabilitiesUnknown, hasHydratedRuntime, isHydratingRuntime]);// Two waits share this panel. Hardware detection is a cold `import torch` that can run for// minutes and says so, the way the Video page does; a hydrating runtime is quick and keeps// the runtime wording, which on a machine still being measured just reads as a hang.diff --git a/studio/frontend/src/features/video/reference-picker.tsx b/studio/frontend/src/features/video/reference-picker.tsxindex 8ef81190415..7f0c84044ca 100644--- a/studio/frontend/src/features/video/reference-picker.tsx+++ b/studio/frontend/src/features/video/reference-picker.tsx@@ -75,7 +75,14 @@ export function ReferenceMediaPicker({)}><HugeiconsIcon icon={icon} className="size-3.5 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate text-ui-11 text-foreground">{value.name}</span>+ {/* The file input is early-returned past in this branch, so the+ type=file redaction never sees it: mark the name itself. */}+ <span+ data-reload-snapshot-sensitive+ className="min-w-0 flex-1 truncate text-ui-11 text-foreground"+ >+ {value.name}+ </span><Tooltip><TooltipTrigger asChild={true}><Buttondiff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex 1c4070a4df6..8db31f02700 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -792,9 +792,21 @@ function VideoGate({ children }: { children: ReactNode }) {* on the chat-only verdict too would spin through an MLX self-heal /api/health holds it back for,* which cannot change a Metal answer.*/-export function VideoPage({ active = true }: { active?: boolean }) {+export function VideoPage({+ active = true,+ onInitialReady,+}: {+ active?: boolean;+ onInitialReady?: () => void;+}) {const hardware = useHardwareInfo();+ useEffect(() => {+ if (active && hardware.loaded && hardware.videoSupported === false) {+ onInitialReady?.();+ }+ }, [active, hardware.loaded, hardware.videoSupported, onInitialReady]);+if (!hardware.loaded) {return (<VideoGate>@@ -821,10 +833,19 @@ export function VideoPage({ active = true }: { active?: boolean }) {);}- return <VideoGenerator active={active} />;+ return (+ <VideoGenerator active={active} onInitialReady={onInitialReady} />+ );}-function VideoGenerator({ active = true }: { active?: boolean }) {+function VideoGenerator({+ active = true,+ onInitialReady,+}: {+ active?: boolean;+ onInitialReady?: () => void;+}) {+ const initialReadySent = useRef(false);const hostClass = useHostClass();const videoModels = useVideoModels(hostClass);const [quant, setQuant] = useState<string | null>(galleryCache.quant);@@ -1565,10 +1586,6 @@ function VideoGenerator({ active = true }: { active?: boolean }) {}}, [ensureSrc]);- useEffect(() => {- void loadGallery();- }, [loadGallery]);-// WebM/GIF go through a server-side transcode that can take seconds (and 501s when the codec is missing), so wrap the helper with toasts.const handleDownload = useCallback(async (src: string, video: GalleryVideo, format: "mp4" | "webm" | "gif") => {@@ -1913,10 +1930,31 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// Re-sync model status when the tab becomes active again: while off-tab the video model may have been evicted.useEffect(() => {if (!active) return;+ if (initialReadySent.current) {+ void refreshStatus();+ return;+ }+ let cancelled = false;void (async () => {- await refreshStatus();+ await Promise.all([+ refreshStatus(),+ (async () => {+ await loadGallery();+ const initialSelection =+ galleryCache.videos.find(+ (video) => video.id === galleryCache.selectedId,+ ) ?? galleryCache.videos[0];+ if (initialSelection) await ensureSrc(initialSelection);+ })(),+ ]);+ if (cancelled || initialReadySent.current) return;+ initialReadySent.current = true;+ onInitialReady?.();})();- }, [active, refreshStatus]);+ return () => {+ cancelled = true;+ };+ }, [active, ensureSrc, loadGallery, onInitialReady, refreshStatus]);// Ejected from the loaded models indicator, which does not run handleUnload:// without this the controls keep offering to generate on a freed runtime, anddiff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex feb65dcfed3..f0b37af30b9 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -727,7 +727,13 @@ html[data-chat-font] .aui-root {}:root:not([data-palette]) .palette-card[data-palette-value="standard"],:root[data-palette="classic"] .palette-card[data-palette-value="classic"],-:root[data-palette="minimal"] .palette-card[data-palette-value="minimal"] {+:root[data-palette="minimal"] .palette-card[data-palette-value="minimal"],+.reload-snapshot-shell:not([data-palette])+ .palette-card[data-palette-value="standard"],+.reload-snapshot-shell[data-palette="classic"]+ .palette-card[data-palette-value="classic"],+.reload-snapshot-shell[data-palette="minimal"]+ .palette-card[data-palette-value="minimal"] {/* Selection keeps the card's own border weight, only darker. */border-color: var(--ring-select);}@@ -3263,3 +3269,31 @@ html[data-chat-font] .aui-root {);}}++/* The retained reload shell. Its contents live in a closed shadow tree. The+ script repeats this host rule inline because Vite injects development CSS+ after main.tsx loads; in production this is painted by the render-blocking+ stylesheet. Click-through: the copy is a picture, and the live document+ underneath keeps taking input. */+.reload-snapshot {+ position: fixed;+ inset: 0;+ z-index: 2147483647;+ pointer-events: none;+ background: var(--background);+}++/* The copy is a still, so it must not animate at all. Pausing is not the same+ thing: a paused animation holds its FIRST keyframe, which for the+ animate-in/fade-in entrances is opacity 0, so those elements would render+ invisible for as long as the shell is up. Even collapsing the duration+ leaves them blank for the frame the animation starts on. Dropping the+ animation paints the settled style straight away. This rule reaches the copy+ because the shadow tree loads this same stylesheet and marks its root+ .reload-snapshot-shell. */+.reload-snapshot-shell *,+.reload-snapshot-shell *::before,+.reload-snapshot-shell *::after {+ animation: none !important;+ transition: none !important;+}diff --git a/studio/frontend/tests/openai-codex-connect.test.ts b/studio/frontend/tests/openai-codex-connect.test.tsindex 73096bf4176..d396babd323 100644--- a/studio/frontend/tests/openai-codex-connect.test.ts+++ b/studio/frontend/tests/openai-codex-connect.test.ts@@ -75,6 +75,7 @@ test("renders browser callback completion and cancellation controls", () => {const markup = render({ initialFlow: flow({ method: "browser" }) });assert.match(markup, /paste the complete localhost callback URL/i);assert.match(markup, /http:\/\/localhost:1455\/auth\/callback/);+ assert.match(markup, /<input[^>]*data-reload-snapshot-sensitive="true"/);assert.match(markup, />Complete</);assert.match(markup, />Cancel</);});@@ -85,6 +86,10 @@ test("renders device-code instructions without exposing OAuth internals", () =>});assert.match(markup, /Enter this code in ChatGPT/);assert.match(markup, /ABCD-EFGH/);+ assert.match(+ markup,+ /<div data-reload-snapshot-sensitive="true" class="space-y-2 text-sm">/,+ );assert.match(markup, />Copy code</);assert.doesNotMatch(markup, /code_verifier|device_auth_id|secret-state/);});diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.tsnew file mode 100644index 00000000000..3ef2d9969ce--- /dev/null+++ b/studio/frontend/tests/reload-snapshot.test.ts@@ -0,0 +1,1859 @@+// 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 assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import vm from "node:vm";++const script = readFileSync(+ new URL("../public/reload-snapshot.js", import.meta.url),+ "utf8",+);+const indexHtml = readFileSync(+ new URL("../index.html", import.meta.url),+ "utf8",+);+const indexCss = readFileSync(+ new URL("../src/index.css", import.meta.url),+ "utf8",+);+const rootRouteSource = readFileSync(+ new URL("../src/app/routes/__root.tsx", import.meta.url),+ "utf8",+);+const runtimeProviderSource = readFileSync(+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),+ "utf8",+);+const chatPageSource = readFileSync(+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),+ "utf8",+);+const sharedComposerSource = readFileSync(+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),+ "utf8",+);+const imageDropzoneSource = readFileSync(+ new URL("../src/components/image-dropzone.tsx", import.meta.url),+ "utf8",+);+const attachmentPreviewSource = readFileSync(+ new URL(+ "../src/components/assistant-ui/attachment-preview.tsx",+ import.meta.url,+ ),+ "utf8",+);++const attachmentSource = readFileSync(+ new URL("../src/components/assistant-ui/attachment.tsx", import.meta.url),+ "utf8",+);+const imagesPageSource = readFileSync(+ new URL("../src/features/images/images-page.tsx", import.meta.url),+ "utf8",+);+const videoPageSource = readFileSync(+ new URL("../src/features/video/video-page.tsx", import.meta.url),+ "utf8",+);+const audioPageSource = readFileSync(+ new URL("../src/features/audio/audio-page.tsx", import.meta.url),+ "utf8",+);+const hubPageSource = readFileSync(+ new URL("../src/features/hub/hub-page.tsx", import.meta.url),+ "utf8",+);+const referencePickerSource = readFileSync(+ new URL("../src/features/video/reference-picker.tsx", import.meta.url),+ "utf8",+);++const unstructuredDropZoneSource = readFileSync(+ new URL(+ "../src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx",+ import.meta.url,+ ),+ "utf8",+);++const projectsPageSource = readFileSync(+ new URL("../src/features/chat/projects-page.tsx", import.meta.url),+ "utf8",+);++const seedDialogSource = readFileSync(+ new URL(+ "../src/features/recipe-studio/dialogs/seed/seed-dialog.tsx",+ import.meta.url,+ ),+ "utf8",+);++const projectSourceDropzoneSource = readFileSync(+ new URL(+ "../src/features/rag/components/project-source-dropzone.tsx",+ import.meta.url,+ ),+ "utf8",+);+const dataRecipesPageSource = readFileSync(+ new URL(+ "../src/features/data-recipes/pages/data-recipes-page.tsx",+ import.meta.url,+ ),+ "utf8",+);+const editRecipePageSource = readFileSync(+ new URL(+ "../src/features/data-recipes/pages/edit-recipe-page.tsx",+ import.meta.url,+ ),+ "utf8",+);+const exportPageSource = readFileSync(+ new URL("../src/features/export/export-page.tsx", import.meta.url),+ "utf8",+);+const studioPageSource = readFileSync(+ new URL("../src/features/studio/studio-page.tsx", import.meta.url),+ "utf8",+);+const apiMonitorPageSource = readFileSync(+ new URL("../src/features/api-monitor/api-monitor-page.tsx", import.meta.url),+ "utf8",+);+const authFormSource = readFileSync(+ new URL("../src/features/auth/components/auth-form.tsx", import.meta.url),+ "utf8",+);++type Listener = (event: Record<string, unknown>) => void;++/** A node of the fake #root subtree the capture walks. */+interface ElementSpec {+ tag: string;+ /** Live DOM state React writes as a property rather than an attribute. */+ value?: string;+ checked?: boolean;+ selected?: boolean;+ type?: string;+ autocomplete?: string;+ attributes?: Record<string, string>;+ display?: string;+ visibility?: string;+ overflowX?: string;+ overflowY?: string;+ scrollTop?: number;+ scrollLeft?: number;+ scrollHeight?: number;+ scrollWidth?: number;+ clientHeight?: number;+ clientWidth?: number;+ currentSrc?: string;+ naturalWidth?: number;+ naturalHeight?: number;+ videoWidth?: number;+ videoHeight?: number;+ width?: number;+ height?: number;+ /** [top, right, bottom, left]. Ignored for a `display: contents` box. */+ rect?: [number, number, number, number];+ text?: string;+ children?: ElementSpec[];+}++interface ShadowStub {+ mode: string;+ children: Array<Record<string, unknown>>;+ appendChild(child: Record<string, unknown>): Record<string, unknown>;+}++interface StubElement {+ tagName: string;+ spec: ElementSpec;+ value: string;+ checked: boolean;+ selected: boolean;+ type: string;+ autocomplete: string;+ scrollTop: number;+ scrollLeft: number;+ scrollHeight: number;+ scrollWidth: number;+ clientHeight: number;+ clientWidth: number;+ currentSrc: string;+ naturalWidth: number;+ naturalHeight: number;+ videoWidth: number;+ videoHeight: number;+ width: number;+ height: number;+ textContent: string;+ attributeOverrides: Record<string, string>;+ hasAttribute(name: string): boolean;+ getAttribute(name: string): string | null;+ setAttribute(name: string, value: string): void;+ children: StubElement[];+ parent: StubElement | null;+ readonly parentElement: StubElement | null;+ readonly nextElementSibling: StubElement | null;+ attributes: Array<{ name: string }>;+ closest(selector: string): StubElement | null;+ getBoundingClientRect(): {+ top: number;+ right: number;+ bottom: number;+ left: number;+ };+ remove(): void;+ replaceChildren(): void;+ removeAttribute(name: string): void;+ querySelectorAll(selector: string): StubElement[];+ cloneNode(deep: boolean): StubElement;+ readonly firstElementChild: StubElement | undefined;+ readonly innerHTML: string;+ readonly outerHTML: string;+}++function createElement(spec: ElementSpec, parent: StubElement | null = null) {+ const element = {+ tagName: spec.tag.toUpperCase(),+ spec,+ value: spec.value ?? "",+ checked: spec.checked ?? false,+ selected: spec.selected ?? false,+ type: spec.type ?? "text",+ autocomplete: spec.autocomplete ?? "",+ scrollTop: spec.scrollTop ?? 0,+ scrollLeft: spec.scrollLeft ?? 0,+ scrollHeight: spec.scrollHeight ?? spec.clientHeight ?? 900,+ scrollWidth: spec.scrollWidth ?? spec.clientWidth ?? 1440,+ clientHeight: spec.clientHeight ?? 900,+ clientWidth: spec.clientWidth ?? 1440,+ currentSrc: spec.currentSrc ?? spec.attributes?.src ?? "",+ naturalWidth: spec.naturalWidth ?? 0,+ naturalHeight: spec.naturalHeight ?? 0,+ videoWidth: spec.videoWidth ?? 0,+ videoHeight: spec.videoHeight ?? 0,+ width: spec.width ?? 0,+ height: spec.height ?? 0,+ textContent: spec.text ?? "",+ children: [] as StubElement[],+ parent,+ attributeOverrides: {+ ...(spec.attributes ?? {}),+ ...(spec.autocomplete ? { autocomplete: spec.autocomplete } : {}),+ } as Record<string, string>,+ get attributes() {+ return Object.keys(element.attributeOverrides).map((name) => ({ name }));+ },+ hasAttribute(name: string) {+ return Object.hasOwn(element.attributeOverrides, name);+ },+ getAttribute(name: string) {+ return element.attributeOverrides[name] ?? null;+ },+ closest(selector: string) {+ let node: StubElement | null = element;+ while (node) {+ if (node.tagName.toLowerCase() === selector) return node;+ node = node.parent;+ }+ return null;+ },+ getBoundingClientRect() {+ // Chromium, Firefox and WebKit all report an empty rectangle for a box+ // that is not laid out, whatever its children cover.+ const [top, right, bottom, left] =+ spec.display === "contents"+ ? [0, 0, 0, 0]+ : (spec.rect ?? [0, 1440, 900, 0]);+ return { top, right, bottom, left };+ },+ remove() {+ if (!element.parent) return;+ element.parent.children = element.parent.children.filter(+ (child) => child !== element,+ );+ element.parent = null;+ },+ replaceChildren() {+ for (const child of element.children) child.parent = null;+ element.children = [];+ element.textContent = "";+ },+ setAttribute(name: string, value: string) {+ element.attributeOverrides[name] = value;+ },+ removeAttribute(name: string) {+ delete element.attributeOverrides[name];+ },+ get parentElement() {+ return element.parent;+ },+ get nextElementSibling() {+ if (!element.parent) return null;+ const index = element.parent.children.indexOf(element);+ return element.parent.children[index + 1] ?? null;+ },+ querySelectorAll(selector: string) {+ const wanted = selector.split(",").map((name) => name.trim());+ const found: StubElement[] = [];+ const walk = (node: StubElement) => {+ for (const child of node.children) {+ if (+ selector === "*" ||+ wanted.includes(child.tagName.toLowerCase()) ||+ wanted.some(+ (name) =>+ name.startsWith("[") &&+ name.endsWith("]") &&+ child.hasAttribute(name.slice(1, -1)),+ )+ ) {+ found.push(child);+ }+ walk(child);+ }+ };+ walk(element);+ return found;+ },+ cloneNode() {+ return createElement(spec);+ },+ get firstElementChild() {+ return element.children[0];+ },+ get innerHTML() {+ return element.children+ .map((child) => child.outerHTML)+ .concat(element.textContent)+ .join("");+ },+ get outerHTML() {+ const attributes = Object.entries(element.attributeOverrides)+ .map(([name, value]) => ` ${name}="${value}"`)+ .join("");+ return `<${spec.tag}${attributes}>${element.innerHTML}</${spec.tag}>`;+ },+ } as StubElement;+ element.children = (spec.children ?? []).map((child) =>+ createElement(child, element),+ );+ return element;+}++/** Enough of CSSStyleDeclaration for the inline custom properties on <html>. */+type StubStyle = {+ length: number;+ getPropertyValue(name: string): string;+ setProperty(name: string, value: string): void;+ removeProperty(name: string): void;+} & Record<number, string>;++function createStyle(initial: Record<string, string> = {}) {+ const values = new Map(Object.entries(initial));+ const style = {+ getPropertyValue: (name: string) => values.get(name) ?? "",+ setProperty: (name: string, value: string) => {+ values.set(name, value);+ index();+ },+ removeProperty: (name: string) => {+ values.delete(name);+ index();+ },+ get length() {+ return values.size;+ },+ } as StubStyle;+ const index = () => {+ [...values.keys()].forEach((name, position) => {+ style[position] = name;+ });+ };+ index();+ return style;+}++function createEnvironment(options: {+ navigationType: "navigate" | "reload";+ storage?: Map<string, string>;+ rootHtml?: string;+ rootTree?: ElementSpec;+ bodyPortals?: ElementSpec[];+ viewport?: { width: number; height: number };+ htmlVariables?: Record<string, string>;+ htmlAttributes?: Record<string, string>;+ styleSheets?: string[];+ frameDataBody?: string;+ inlineStyleSheets?: string[];+ trackScrollRestores?: boolean;+ localStorage?: Map<string, string>;+ supportsPageSwap?: boolean;+}) {+ const storage = options.storage ?? new Map<string, string>();+ const listeners = new Map<string, Listener[]>();+ const animationFrames: Array<() => void> = [];+ const fontFaces: Array<{ family: string; source: string }> = [];+ const appended: Array<{ innerHTML: string; removed: boolean }> = [];+ let scrollRestoreCalls = 0;+ const bodyTree = options.rootTree+ ? createElement({+ tag: "body",+ children: [+ {+ ...options.rootTree,+ attributes: { ...options.rootTree.attributes, id: "root" },+ },+ ...(options.bodyPortals ?? []),+ ],+ })+ : null;+ const clone = {+ innerHTML: `<div id="root">${options.rootHtml ?? "<main>Chat is ready</main>"}</div>`,+ querySelectorAll: () => [],+ };+ const root = bodyTree?.children[0] ?? {+ firstElementChild: {},+ querySelectorAll: () => [],+ };+ const body = bodyTree ?? {+ cloneNode: () => clone,+ querySelectorAll: () => [],+ };++ const window = {+ addEventListener(name: string, listener: Listener) {+ const current = listeners.get(name) ?? [];+ current.push(listener);+ listeners.set(name, current);+ },+ };+ if (options.supportsPageSwap) {+ Object.assign(window, { onpageswap: null });+ }+ const htmlAttributes = new Map(Object.entries(options.htmlAttributes ?? {}));+ const documentElement = {+ style: createStyle(options.htmlVariables),+ hasAttribute: (name: string) => htmlAttributes.has(name),+ getAttribute: (name: string) => htmlAttributes.get(name) ?? null,+ setAttribute: (name: string, value: string) => {+ htmlAttributes.set(name, value);+ },+ removeAttribute: (name: string) => {+ htmlAttributes.delete(name);+ },+ appendChild(element: { innerHTML: string; removed: boolean }) {+ appended.push(element);+ },+ };+ const document = {+ body,+ documentElement,+ fonts: {+ add(face: { family: string; source: string }) {+ fontFaces.push(face);+ },+ },+ getElementById: () => root,+ querySelectorAll: (selector: string) => {+ if (selector === 'link[rel="stylesheet"]') {+ return (options.styleSheets ?? []).map((href) => ({ href }));+ }+ if (selector === "style[data-vite-dev-id]") {+ return (options.inlineStyleSheets ?? []).map((textContent) => ({+ textContent,+ }));+ }+ return [];+ },+ createElement: (tag?: string) => {+ if (tag === "canvas") {+ return {+ width: 0,+ height: 0,+ getContext: () => ({ drawImage() {} }),+ toDataURL: () =>+ "data:image/webp;base64," ++ (options.frameDataBody ?? "retained-frame"),+ };+ }+ const element = {+ tagName: (tag ?? "div").toUpperCase(),+ className: "",+ attributes: {} as Record<string, string>,+ style: {+ values: {} as Record<string, string>,+ setProperty(name: string, value: string) {+ element.style.values[name] = value;+ },+ },+ rel: "",+ href: "",+ onload: null as (() => void) | null,+ onerror: null as (() => void) | null,+ inert: false,+ innerHTML: "",+ textContent: "",+ children: [] as Record<string, unknown>[],+ removed: false,+ shadow: null as ShadowStub | null,+ attachShadow(init: { mode: string }) {+ const shadow: ShadowStub = {+ mode: init.mode,+ children: [],+ appendChild(child: Record<string, unknown>) {+ shadow.children.push(child);+ return child;+ },+ };+ element.shadow = shadow;+ return shadow;+ },+ setAttribute(name: string, value: string) {+ element.attributes[name] = value;+ },+ getAttribute(name: string) {+ return element.attributes[name] ?? null;+ },+ querySelectorAll(selector?: string) {+ if (+ tag === "body" &&+ options.trackScrollRestores &&+ selector ===+ "[data-reload-scroll-top], [data-reload-scroll-left]"+ ) {+ scrollRestoreCalls += 1;+ return [+ {+ scrollTop: 0,+ scrollLeft: 0,+ getAttribute(name: string) {+ return name === "data-reload-scroll-top" ? "600" : null;+ },+ },+ ];+ }+ return [];+ },+ appendChild(child: Record<string, unknown>) {+ element.children.push(child);+ return child;+ },+ remove() {+ element.removed = true;+ },+ };+ return element;+ },+ };++ vm.runInNewContext(script, {+ Array,+ Date,+ JSON,+ Object,+ clearTimeout() {+ // Timer bookkeeping is outside this lifecycle test.+ },+ document,+ getComputedStyle: (element: StubElement) =>+ // <html> resolves to its own declaration block, which is where the+ // design tokens the copy has to carry are read from.+ (element as unknown) === documentElement+ ? documentElement.style+ : {+ display: element.spec?.display ?? "block",+ visibility: element.spec?.visibility ?? "visible",+ overflowX: element.spec?.overflowX ?? "visible",+ overflowY: element.spec?.overflowY ?? "visible",+ },+ innerHeight: options.viewport?.height ?? 900,+ innerWidth: options.viewport?.width ?? 1440,+ location: { pathname: "/chat", search: "" },+ localStorage: {+ getItem: (key: string) => options.localStorage?.get(key) ?? null,+ },+ FontFace: class {+ family: string;+ source: string;+ constructor(family: string, source: string) {+ this.family = family;+ this.source = source;+ }+ load() {+ return Promise.resolve(this);+ }+ },+ performance: {+ getEntriesByType: () => [{ type: options.navigationType }],+ },+ requestAnimationFrame(callback: () => void) {+ animationFrames.push(callback);+ },+ sessionStorage: {+ getItem: (key: string) => storage.get(key) ?? null,+ removeItem: (key: string) => storage.delete(key),+ setItem: (key: string, value: string) => storage.set(key, value),+ },+ setTimeout: () => 1,+ window,+ });++ return {+ storage,+ fontFaces,+ appended,+ htmlVariables: documentElement.style,+ htmlAttributes,+ get scrollRestoreCalls() {+ return scrollRestoreCalls;+ },+ /** The host element of the retained shell, if one was restored. */+ get shell() {+ const host = appended[0] as unknown as+ | {+ shadow: ShadowStub | null;+ removed: boolean;+ style: Record<string, unknown>;+ }+ | undefined;+ if (!host?.shadow) return null;+ const children = host.shadow.children;+ const root = children[children.length - 1];+ const body = (+ root?.children as Record<string, unknown>[] | undefined+ )?.find((child) => child.tagName === "BODY");+ return {+ host,+ hostStyle: host.style,+ mode: host.shadow.mode,+ stylesheets: children+ .filter((child) => child.rel === "stylesheet")+ .map((child) => child.href as string),+ inlineStyles: children+ .filter((child) => child.tagName === "STYLE")+ .map((child) => child.textContent as string),+ html: (body?.innerHTML ?? root?.innerHTML ?? "") as string,+ bodyTag: (body?.tagName ?? "") as string,+ rootClass: (root?.className ?? "") as string,+ rootTag: (root?.tagName ?? "") as string,+ rootAttributes: (root?.attributes ?? {}) as Record<string, string>,+ rootTokens: ((+ root?.style as+ | { values?: Record<string, string> }+ | undefined+ )?.values ?? {}) as Record<string, string>,+ rootVisibility: (root?.style as { visibility?: string } | undefined)+ ?.visibility,+ };+ },+ dispatch(name: string, event: Record<string, unknown> = {}) {+ for (const listener of listeners.get(name) ?? []) {+ listener(event);+ }+ },+ loadStyleSheets() {+ const host = appended[0] as unknown as+ | { shadow: ShadowStub | null }+ | undefined;+ for (const child of host?.shadow?.children ?? []) {+ if (child.rel === "stylesheet") {+ (child.onload as (() => void) | null)?.();+ }+ }+ },+ runAnimationFrame() {+ const callbacks = animationFrames.splice(0);+ for (const callback of callbacks) {+ callback();+ }+ },+ };+}++function storedSnapshot(storage: Map<string, string>) {+ const raw = storage.get("unsloth.reload-snapshot.v1");+ assert.ok(raw, "expected a stored snapshot");+ return JSON.parse(raw) as {+ html: string;+ styles?: string[];+ inlineStyles?: string[];+ rootClass?: string;+ tokens?: Record<string, string>;+ appearance?: {+ variables: Record<string, string>;+ attributes: Record<string, string>;+ };+ };+}++test("carries the rendered shell through a reload until the new shell is ready", () => {+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ supportsPageSwap: true,+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.appended.length, 1);+ assert.equal(+ incoming.shell?.html,+ '<div id="root"><main>Existing chat</main></div>',+ );+ assert.equal(incoming.storage.size, 0);++ incoming.dispatch("unsloth:app-shell-ready");+ assert.equal(incoming.appended[0].removed, false);+ incoming.runAnimationFrame();+ assert.equal(incoming.appended[0].removed, false);+ incoming.runAnimationFrame();+ assert.equal(incoming.appended[0].removed, true);+});++test("captures reloads through WebKit's pagehide fallback", () => {+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>WebKit chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ });+ outgoing.dispatch("pagehide", { persisted: false });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.match(incoming.shell?.html ?? "", /WebKit chat/);+});++test("does not run the pagehide fallback when pageswap is available", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Chromium chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ supportsPageSwap: true,+ });+ environment.dispatch("pagehide", { persisted: false });+ assert.equal(environment.storage.size, 0);+});++test("carries the retained shell through consecutive reloads", () => {+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Stable chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ supportsPageSwap: true,+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const firstReload = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ rootHtml: "<main>Still loading</main>",+ supportsPageSwap: true,+ });+ firstReload.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });+ firstReload.dispatch("pagehide", { persisted: false });++ const secondReload = createEnvironment({+ navigationType: "reload",+ storage: firstReload.storage,+ });+ assert.match(secondReload.shell?.html ?? "", /Stable chat/);+ assert.doesNotMatch(secondReload.shell?.html ?? "", /Still loading/);+});++test("restores from a parser-blocking head script before the first body paint", () => {+ const scriptPosition = indexHtml.indexOf(+ '<script src="/reload-snapshot.js">',+ );+ assert.ok(scriptPosition > 0);+ assert.ok(scriptPosition < indexHtml.indexOf("</head>"));+});++test("does not retain the shell for a non-reload navigation", () => {+ const environment = createEnvironment({ navigationType: "navigate" });+ environment.dispatch("pageswap", {+ activation: { navigationType: "push" },+ });+ assert.equal(environment.storage.size, 0);+});++test("never persists a Temporary Chat shell", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Sensitive temporary transcript</main>",+ htmlAttributes: { "data-reload-snapshot-private": "" },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });+ assert.equal(environment.storage.size, 0);+});++test("mirrors Temporary Chat privacy and lets history completion retire chat shells", () => {+ assert.match(+ rootRouteSource,+ /toggleAttribute\(\s*"data-reload-snapshot-private",\s*incognito,/,+ );+ assert.equal(+ [...rootRouteSource.matchAll(/<ReloadSnapshotReady \/>/g)].length,+ 1,+ "chat must not use the generic commit-time readiness marker",+ );+ assert.match(+ runtimeProviderSource,+ /async load\(\) \{[\s\S]*?const completeLoad =[\s\S]*?unsloth:app-shell-ready[\s\S]*?await listStoredChatMessages\(remoteId\)[\s\S]*?return completeLoad/,+ );+ assert.match(+ runtimeProviderSource,+ /!reloadReadyThreadId \|\| loadedThreadId === reloadReadyThreadId/,+ );+ assert.match(+ runtimeProviderSource,+ /switchToThread\(threadId\)[\s\S]*?\.catch\(\(\) => \{[\s\S]*?onSwitchFailed\?\.\(\)/,+ );+ assert.match(+ runtimeProviderSource,+ /const signalFailedInitialSwitchReady = useCallback[\s\S]*?onInitialHistoryReady\(\)[\s\S]*?unsloth:app-shell-ready[\s\S]*?onSwitchFailed=\{signalFailedInitialSwitchReady\}/,+ );+ assert.match(+ runtimeProviderSource,+ /createRuntimeHook\([\s\S]*?modelType,[\s\S]*?pairId,[\s\S]*?initialThreadId,[\s\S]*?onInitialHistoryReady/,+ );+ // A compare pane reports readiness through onInitialHistoryReady, and its+ // runtime bootstraps on an empty thread first, so this branch must check the+ // thread or both panes go ready while their conversations still load.+ assert.match(+ runtimeProviderSource,+ /const completeLoad =[\s\S]*?if \(onInitialHistoryReady\) \{\s*if \(loadedTheRequestedThread\) onInitialHistoryReady\(\);/,+ );+ assert.match(+ runtimeProviderSource,+ /const signalFailedInitialSwitchReady = useCallback[\s\S]*?if \(onInitialHistoryReady\) \{\s*onInitialHistoryReady\(\);/,+ );+ assert.match(+ chatPageSource,+ /state\.panes\.add\(pane\)[\s\S]*?state\.panes\.size < 2[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(+ chatPageSource,+ /\.finally\(\(\) => \{\s*if \(isActive\) setThreadsSettled\(true\)/,+ );+ assert.match(+ chatPageSource,+ /if \(!threadsSettled\) return;\s*if \(!baseThreadId\) markInitialHistoryReady\("base"\);\s*if \(!loraThreadId\) markInitialHistoryReady\("lora"\);/,+ );+ assert.match(+ chatPageSource,+ /if \(!threadsSettled\) return;\s*if \(!model1ThreadId\) markInitialHistoryReady\("model1"\);\s*if \(!model2ThreadId\) markInitialHistoryReady\("model2"\);/,+ );+ assert.match(+ chatPageSource,+ /const previewsReady = items\.every[\s\S]*?!dataLoaded \|\|[\s\S]*?!runtimeReady \|\|[\s\S]*?!previewsReady \|\|[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(+ chatPageSource,+ /dataLoaded=\{currentProjectItemsLoaded && !projectsLoading\}/,+ );+});++test("media pages retire the shell only after gallery and preview hydration", () => {+ assert.doesNotMatch(+ rootRouteSource,+ /<RouteBoundary>\s*<(?:ImagesPage|VideoPage|AudioPage)/,+ );+ assert.match(+ imagesPageSource,+ /Promise\.all\(\[\s*refreshStatus\(\)[\s\S]*?await loadGallery\(\)[\s\S]*?await ensureSrc\(initialSelection\)[\s\S]*?onInitialReady\?\.\(\)/,+ );+ assert.match(+ videoPageSource,+ /Promise\.all\(\[\s*refreshStatus\(\)[\s\S]*?await loadGallery\(\)[\s\S]*?await ensureSrc\(initialSelection\)[\s\S]*?onInitialReady\?\.\(\)/,+ );+ assert.match(+ audioPageSource,+ /Promise\.all\(\[\s*refreshGallery\(\),\s*refreshStatus\(\),\s*refreshSttStatus\(\)[\s\S]*?await ensureClipSrc\(initialSelection\)[\s\S]*?onInitialReady\?\.\(\)/,+ );+ assert.match(+ imagesPageSource,+ /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\)/,+ );+ assert.match(+ videoPageSource,+ /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\)/,+ );+ assert.match(+ audioPageSource,+ /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\);\s*void refreshSttStatus\(\);\s*void refreshGallery\(\)/,+ );+ assert.match(+ audioPageSource,+ /mode === "transcribe"[\s\S]*?data-reload-snapshot-sensitive=\{\s*transcript \|\| transcribedName \? "" : undefined/,+ );+});++test("data-backed routes own reload readiness until hydration settles", () => {+ assert.match(+ rootRouteSource,+ /const routeOwnsReloadReadiness =\s*pathname === "\/hub" \|\|\s*pathname === "\/projects"/,+ );+ assert.match(+ rootRouteSource,+ /readyWhenCommitted=\{!routeOwnsReloadReadiness\}/,+ );+ assert.match(+ hubPageSource,+ /!initialResidentStatusSettled[\s\S]*?\(isDiscoverTab \? isLoading : !inventorySettled\)[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(+ projectsPageSource,+ /if \(!hasLoaded \|\| reloadReadySent\.current\) \{\s*return;\s*\}[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(+ rootRouteSource,+ /pathname === "\/data-recipes" \|\|\s*pathname\.startsWith\("\/data-recipes\/"\)/,+ );+ assert.match(+ dataRecipesPageSource,+ /if \(!ready \|\| reloadReadySent\.current\) \{\s*return;\s*\}[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(+ editRecipePageSource,+ /if \(loadState\.status === "loading" \|\| reloadReadySent\.current\) \{\s*return;\s*\}[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(rootRouteSource, /pathname === "\/export"/);+ assert.match(+ exportPageSource,+ /loadingCheckpoints \|\|[\s\S]*?isLoadingLocalModels \|\|[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(rootRouteSource, /pathname === "\/studio"/);+ assert.match(+ studioPageSource,+ /capabilitiesUnknown \|\|[\s\S]*?!hasHydratedRuntime \|\|[\s\S]*?isHydratingRuntime \|\|[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(rootRouteSource, /pathname === "\/api-monitor"/);+ assert.match(+ apiMonitorPageSource,+ /if \(loading \|\| reloadReadySent\.current\) \{\s*return;\s*\}[\s\S]*?unsloth:app-shell-ready/,+ );+ assert.match(rootRouteSource, /pathname === "\/login"/);+ assert.match(rootRouteSource, /pathname === "\/change-password"/);+ assert.match(+ authFormSource,+ /if \(statusLoading \|\| reloadReadySent\.current\) return;[\s\S]*?unsloth:app-shell-ready/,+ );+});++test("captures Vite's injected development stylesheet", () => {+ const css = ".reload-snapshot-shell { color: rgb(1 2 3); }";+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Development shell</main>",+ inlineStyleSheets: [css],+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const snapshot = storedSnapshot(outgoing.storage);+ assert.deepEqual(snapshot.styles, []);+ assert.deepEqual(snapshot.inlineStyles, [css]);++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.deepEqual(incoming.shell?.inlineStyles, [css]);+});++test("positions the retained host before development CSS arrives", () => {+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Development shell</main>",+ inlineStyleSheets: [".reload-snapshot-shell { display: block; }"],+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.shell?.hostStyle.position, "fixed");+ assert.equal(incoming.shell?.hostStyle.inset, "0");+ assert.equal(incoming.shell?.hostStyle.zIndex, "2147483647");+ assert.equal(incoming.shell?.hostStyle.pointerEvents, "none");+ assert.equal(incoming.shell?.hostStyle.background, "var(--background)");+});++test("restores scroll offsets again after linked styles load", () => {+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Scrolled shell</main>",+ styleSheets: ["/assets/index-abc123.css"],+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ trackScrollRestores: true,+ });+ assert.equal(incoming.scrollRestoreCalls, 1);+ incoming.runAnimationFrame();+ assert.equal(incoming.scrollRestoreCalls, 2);+ incoming.loadStyleSheets();+ assert.equal(incoming.scrollRestoreCalls, 3);+ incoming.loadStyleSheets();+ assert.equal(incoming.scrollRestoreCalls, 3);+});++test("keeps what a display:contents wrapper renders, drops what is offscreen", () => {+ // A `display: contents` box is not laid out, so its rectangle is empty even+ // while its children fill the viewport: /studio wraps its whole page in one.+ const environment = createEnvironment({+ navigationType: "navigate",+ rootTree: {+ tag: "div",+ rect: [0, 1440, 900, 0],+ children: [+ {+ tag: "div",+ display: "contents",+ children: [+ { tag: "main", rect: [0, 1440, 900, 0], text: "Studio is ready" },+ ],+ },+ { tag: "aside", rect: [-400, 1440, -100, 0], text: "Scrolled past" },+ { tag: "footer", display: "none", text: "Collapsed" },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /Studio is ready/);+ assert.doesNotMatch(html, /Scrolled past/);+ assert.doesNotMatch(html, /Collapsed/);+});++test("carries the appearance customization so the shell paints in its own colors", () => {+ // theme-boot.js resolves mode and palette only; the rest lands in a React+ // effect, which is well after the restored shell has painted.+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ htmlVariables: {+ "--background": "#241b2f",+ "--font-sans": '"Inter"',+ "--studio-sidebar-live-width": "317px",+ },+ htmlAttributes: {+ "data-contrast-adjust": "",+ "data-panel-resizing": "true",+ },+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { appearance } = storedSnapshot(outgoing.storage);+ assert.deepEqual(appearance?.variables, {+ "--background": "#241b2f",+ "--font-sans": '"Inter"',+ });+ assert.deepEqual(appearance?.attributes, { "data-contrast-adjust": "" });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(+ incoming.htmlVariables.getPropertyValue("--background"),+ "#241b2f",+ );+ assert.equal(incoming.htmlAttributes.get("data-contrast-adjust"), "");+ // Transient state (a panel mid-drag) is not appearance and must not be replayed.+ assert.equal(incoming.htmlAttributes.has("data-panel-resizing"), false);+ assert.equal(+ incoming.htmlVariables.getPropertyValue("--studio-sidebar-live-width"),+ "",+ );+});++test("adapts root-scoped palette state to the snapshot shell", () => {+ assert.match(+ indexCss,+ /\.reload-snapshot-shell:not\(\[data-palette\]\)[\s\S]*?\.palette-card\[data-palette-value="standard"\]/,+ );+ assert.match(+ indexCss,+ /\.reload-snapshot-shell\[data-palette="classic"\][\s\S]*?\.palette-card\[data-palette-value="classic"\]/,+ );+ assert.match(+ indexCss,+ /\.reload-snapshot-shell\[data-palette="minimal"\][\s\S]*?\.palette-card\[data-palette-value="minimal"\]/,+ );+});++test("loads selected imported fonts before revealing the shell", async () => {+ const persistedAppearance = new Map([+ [+ "unsloth_appearance_customization",+ JSON.stringify({+ state: {+ customization: {+ uiFont: "Studio Sans",+ headingFont: "Bundled Heading",+ chatFont: null,+ codeFont: null,+ importedFonts: [+ {+ name: "Studio Sans",+ dataUrl: "data:font/woff2;base64,QUJD",+ },+ {+ name: "Unused Font",+ dataUrl: "data:font/woff2;base64,REVG",+ },+ ],+ },+ },+ version: 7,+ }),+ ],+ ]);+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ localStorage: persistedAppearance,+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ localStorage: persistedAppearance,+ });+ assert.equal(incoming.shell?.rootVisibility, "hidden");+ assert.deepEqual(+ incoming.fontFaces.map((face) => ({+ family: face.family,+ source: face.source,+ })),+ [+ {+ family: "Studio Sans",+ source: "url(data:font/woff2;base64,QUJD)",+ },+ ],+ );+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(incoming.shell?.rootVisibility, "visible");+});++test("drops the retained shell's animations instead of pausing them", () => {+ // Not reachable from the script tests: a paused animation holds its FIRST+ // keyframe, so `animate-in fade-in` entrances would render at opacity 0 for+ // as long as the shell is up. Only the stylesheet can express this.+ const start = indexCss.indexOf(".reload-snapshot-shell *,");+ assert.ok(start > 0);+ const rule = indexCss.slice(start, indexCss.indexOf("}", start));+ assert.doesNotMatch(rule, /animation-play-state:\s*paused/);+ assert.match(rule, /animation:\s*none\s*!important/);+});++test("leaves the retained shell click-through", () => {+ // A full-viewport overlay that takes pointer events swallows every click for+ // as long as it is up, which is up to the five-second fail-open.+ const start = indexCss.indexOf(".reload-snapshot {");+ assert.ok(start > 0);+ const rule = indexCss.slice(start, indexCss.indexOf("}", start));+ assert.match(rule, /pointer-events:\s*none/);+});++test("builds the retained shell inside a closed shadow tree", () => {+ // The copy duplicates the live markup, so leaving it in the page tree makes+ // every `textarea[aria-label=...]` style query ambiguous while it is up.+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css", "/assets/chat-def456.css"],+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const stored = storedSnapshot(outgoing.storage);+ assert.deepEqual(stored.styles, [+ "/assets/index-abc123.css",+ "/assets/chat-def456.css",+ ]);++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.shell?.mode, "closed");+ assert.equal(+ incoming.shell?.html,+ '<div id="root"><main>Existing chat</main></div>',+ );+ // Selectors do not cross the boundary, so the copy needs its own styles.+ assert.deepEqual(incoming.shell?.stylesheets, [+ "/assets/index-abc123.css",+ "/assets/chat-def456.css",+ ]);+ // The shell's own rules live in that stylesheet and hang off this marker.+ assert.match(incoming.shell?.rootClass ?? "", /^reload-snapshot-shell /);+});++test("roots the copy in an html element so html-anchored rules still match", () => {+ // 80-odd rules in the app stylesheet are anchored on `html`, light/dark+ // theming above all, and a selector cannot reach across the shadow boundary+ // to the real document element.+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ htmlAttributes: { "data-palette": "classic", "data-contrast-adjust": "" },+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.shell?.rootTag, "HTML");+ assert.equal(incoming.shell?.bodyTag, "BODY");+ assert.deepEqual(incoming.shell?.rootAttributes, {+ "data-palette": "classic",+ "data-contrast-adjust": "",+ });+});++test("freezes the design tokens onto the copy's own root", () => {+ // `:root` matches a document's root element only, so tokens declared there+ // never reach a shadow tree; the copy carries the resolved set instead.+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ styleSheets: ["/assets/index-abc123.css"],+ htmlVariables: { "--font-heading": '"Hellix"', "--tracking-normal": "0em" },+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });+ assert.deepEqual(storedSnapshot(outgoing.storage).tokens, {+ "--font-heading": '"Hellix"',+ "--tracking-normal": "0em",+ });++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.shell?.rootTokens["--font-heading"], '"Hellix"');+ assert.equal(incoming.shell?.rootTokens["--tracking-normal"], "0em");+});++test("carries live form state, except what sensitive fields hide", () => {+ // React writes value/checked as DOM properties; cloneNode copies attributes,+ // so a typed composer would come back empty. Secret fields can be revealed as+ // plain text, but their values must stay behind regardless of presentation.+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ rect: [0, 1440, 900, 0],+ children: [+ {+ tag: "textarea",+ rect: [0, 1440, 200, 0],+ value: "half-written prompt",+ },+ {+ tag: "input",+ rect: [0, 1440, 240, 0],+ type: "search",+ value: "gemma",+ },+ {+ tag: "input",+ rect: [0, 1440, 280, 0],+ type: "checkbox",+ checked: true,+ },+ {+ tag: "input",+ rect: [0, 1440, 320, 0],+ type: "password",+ value: "hunter2",+ attributes: { value: "hunter2" },+ },+ {+ tag: "input",+ rect: [0, 1440, 360, 0],+ type: "text",+ autocomplete: "current-password",+ value: "revealed-password",+ attributes: { value: "revealed-password" },+ },+ {+ tag: "input",+ rect: [0, 1440, 400, 0],+ type: "file",+ value: "C:\\fakepath\\private-dataset.jsonl",+ attributes: { value: "C:\\fakepath\\private-dataset.jsonl" },+ },+ {+ tag: "input",+ rect: [0, 1440, 440, 0],+ type: "text",+ value: "revealed-api-key",+ attributes: {+ value: "revealed-api-key",+ "data-reload-snapshot-sensitive": "",+ },+ },+ {+ tag: "textarea",+ rect: [0, 1440, 480, 0],+ value: "Authorization: Bearer secret-header",+ text: "Authorization: Bearer stale-header",+ attributes: { "data-reload-snapshot-sensitive": "" },+ },+ {+ tag: "code",+ rect: [0, 1440, 520, 0],+ text: "Authorization: Bearer rendered-api-key",+ attributes: { "data-reload-snapshot-sensitive": "" },+ },+ {+ // A filename row repeats the value in its tooltip and in the+ // accessible name beside it, so clearing text alone still ships it.+ tag: "span",+ rect: [0, 1440, 560, 0],+ text: "rendered-local-filename.csv",+ attributes: {+ "data-reload-snapshot-sensitive": "",+ title: "rendered-local-filename.csv",+ "aria-label": "Remove rendered-local-filename.csv",+ placeholder: "rendered-local-filename.csv",+ },+ },+ {+ tag: "div",+ rect: [0, 1440, 600, 0],+ attributes: { "data-reload-snapshot-sensitive": "" },+ children: [+ {+ tag: "img",+ rect: [530, 100, 590, 40],+ naturalWidth: 1024,+ naturalHeight: 768,+ attributes: {+ src: "blob:https://studio.test/pending-local-attachment",+ alt: "pending-local-attachment",+ },+ },+ ],+ },+ {+ tag: "div",+ rect: [0, 1440, 700, 0],+ attributes: { "data-reload-snapshot-sensitive": "" },+ children: [+ {+ tag: "img",+ rect: [630, 100, 690, 40],+ naturalWidth: 1024,+ naturalHeight: 768,+ attributes: {+ src: "data:image/png;base64,private-local-picker",+ alt: "Source",+ },+ },+ ],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /half-written prompt/);+ assert.match(html, /value="gemma"/);+ assert.match(html, /checked=""/);+ assert.doesNotMatch(html, /hunter2/);+ assert.doesNotMatch(html, /revealed-password/);+ assert.doesNotMatch(html, /fakepath|private-dataset/);+ assert.doesNotMatch(html, /revealed-api-key/);+ assert.doesNotMatch(html, /secret-header|stale-header/);+ assert.doesNotMatch(html, /rendered-api-key/);+ assert.doesNotMatch(+ html,+ /pending-local-attachment|private-local-picker|retained-frame/,+ );+ assert.doesNotMatch(html, /rendered-local-filename/);+ assert.match(+ sharedComposerSource,+ /function PendingImageThumb[\s\S]*?data-reload-snapshot-sensitive/,+ );+ assert.match(+ imageDropzoneSource,+ /if \(value\)[\s\S]*?data-reload-snapshot-sensitive/,+ );+ // A picked file's NAME renders outside the file input in several places that+ // neither type=file nor a marked ancestor reaches: the dialogs portal out.+ assert.match(+ referencePickerSource,+ /if \(value\)[\s\S]*?data-reload-snapshot-sensitive[\s\S]*?value\.name/,+ );+ assert.match(+ projectsPageSource,+ /data-reload-snapshot-sensitive[\s\S]*?importFile\?\.name/,+ );+ assert.match(+ unstructuredDropZoneSource,+ /data-reload-snapshot-sensitive[\s\S]*?entry\.name/,+ );+ assert.match(+ seedDialogSource,+ /data-reload-snapshot-sensitive[\s\S]*?localFile\?\.name/,+ );+ // The monitor renders prompt/reply text in three places, not just the+ // expanded payload: every row's excerpt, and a lifecycle row's error text.+ assert.match(+ apiMonitorPageSource,+ /function PayloadBlock[\s\S]*?data-reload-snapshot-sensitive/,+ );+ assert.match(+ apiMonitorPageSource,+ /data-reload-snapshot-sensitive[\s\S]*?\{entry\.error\}/,+ );+ assert.match(+ apiMonitorPageSource,+ /data-reload-snapshot-sensitive[\s\S]*?\{preview\}/,+ );+ assert.match(+ sharedComposerSource,+ /data-reload-snapshot-sensitive[\s\S]*?pendingAudio\.name/,+ );+ // Both carriers: the tooltip on the name, and the accessible name on the+ // remove button, a sibling no ancestor marker would reach.+ assert.match(+ projectSourceDropzoneSource,+ /data-reload-snapshot-sensitive[\s\S]*?title=\{entry\.name\}/,+ );+ assert.match(+ projectSourceDropzoneSource,+ /data-reload-snapshot-sensitive\s*\n\s*aria-label=\{`Remove \$\{entry\.name\}`\}/,+ );+ assert.match(+ attachmentSource,+ /export const ComposerAttachments[\s\S]*?data-reload-snapshot-sensitive/,+ );+ // The dialog lives in attachment-preview.tsx; attachment.tsx passes the flag.+ assert.match(attachmentSource, /<AttachmentPreviewDialog redactFromReload=/);+ assert.match(+ attachmentPreviewSource,+ /AttachmentPreviewDialog[\s\S]*?redactFromReload/,+ );+ for (const dialog of [+ "AttachmentImageDialog",+ "AttachmentTextDialog",+ "AttachmentAudioDialog",+ ]) {+ assert.match(+ attachmentPreviewSource,+ new RegExp(+ `${dialog}[\\s\\S]*?data-reload-snapshot-sensitive=\\{redactFromReload \\? "" : undefined\\}`,+ ),+ `${dialog} must redact its portaled content`,+ );+ }+});++test("keeps native select options that paint the closed control label", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "select",+ rect: [100, 420, 140, 200],+ children: [+ {+ tag: "option",+ rect: [0, 0, 0, 0],+ text: "GPU 0",+ },+ {+ tag: "optgroup",+ rect: [0, 0, 0, 0],+ children: [+ {+ tag: "option",+ rect: [0, 0, 0, 0],+ text: "GPU 1",+ selected: true,+ },+ ],+ },+ ],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /<option>GPU 0<\/option>/);+ assert.match(html, /<optgroup><option selected="">GPU 1<\/option><\/optgroup>/);+});++test("preserves IDs that the isolated copy references internally", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "svg",+ children: [+ {+ tag: "linearGradient",+ attributes: { id: "history-fill" },+ },+ {+ tag: "path",+ attributes: { fill: "url(#history-fill)" },+ },+ ],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /id="history-fill"/);+ assert.match(html, /fill="url\(#history-fill\)"/);+});++test("carries visible body portals along with the app root", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [{ tag: "main", text: "Settings page" }],+ },+ bodyPortals: [+ {+ tag: "div",+ rect: [100, 1100, 700, 300],+ attributes: { role: "dialog" },+ text: "Confirm deletion",+ },+ ],+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /Settings page/);+ assert.match(html, /role="dialog"/);+ assert.match(html, /Confirm deletion/);+});++test("keeps scroll-container geometry with a bounded visible slice", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "section",+ overflowY: "auto",+ clientHeight: 300,+ scrollHeight: 1200,+ scrollTop: 600,+ children: [+ {+ tag: "p",+ rect: [-500, 900, -450, 100],+ text: "Earlier message keeps the scroll geometry",+ },+ {+ tag: "p",+ rect: [300, 900, 350, 100],+ text: "Visible message",+ },+ ],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /data-reload-scroll-top="600"/);+ assert.doesNotMatch(html, /Earlier message keeps the scroll geometry/);+ assert.match(html, /data-reload-spacer/);+ assert.match(html, /Visible message/);+});++test("coalesces a transcript larger than the snapshot cap", () => {+ const earlierMessages = Array.from({ length: 1100 }, (_, index) => ({+ tag: "article",+ rect: [-5000 + index * 4, 900, -4996 + index * 4, 100] as [+ number,+ number,+ number,+ number,+ ],+ text: "Earlier message " + "x".repeat(4096),+ }));+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "section",+ overflowY: "auto",+ clientHeight: 300,+ scrollHeight: 6000,+ scrollTop: 5000,+ children: [+ ...earlierMessages,+ {+ tag: "article",+ rect: [300, 900, 350, 100],+ text: "Visible message survives",+ },+ ],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /Visible message survives/);+ assert.equal((html.match(/data-reload-spacer/g) ?? []).length, 1);+ assert.ok(html.length < 3 * 1024 * 1024);+});++test("materializes visible ephemeral media and drops protected URLs", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "img",+ rect: [100, 900, 700, 100],+ naturalWidth: 1024,+ naturalHeight: 768,+ attributes: { src: "blob:https://studio.test/generated-image" },+ },+ {+ tag: "audio",+ rect: [720, 900, 780, 100],+ attributes: {+ controls: "",+ src: "blob:https://studio.test/generated-audio",+ },+ },+ {+ tag: "video",+ rect: [100, 1300, 700, 950],+ videoWidth: 1280,+ videoHeight: 720,+ attributes: {+ src:+ "/api/inference/video/gallery/clip/file-signed?token=clip.123.secret",+ },+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /src="data:image\/webp;base64,retained-frame"/);+ assert.match(html, /<audio controls="">/);+ assert.match(html, /<video poster="data:image\/webp;base64,retained-frame">/);+ assert.doesNotMatch(html, /blob:/);+ assert.doesNotMatch(html, /clip\.123\.secret|[?&]token=/);+});++test("keeps trusted chart CSS while stripping every other style", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "style",+ rect: [0, 0, 0, 0],+ attributes: { "data-reload-snapshot-style": "" },+ text: "[data-chart=loss] { --color-displayLoss: #16a34a; }",+ },+ {+ tag: "style",+ rect: [0, 0, 0, 0],+ text: ".untrusted { display: block; }",+ },+ {+ tag: "svg",+ children: [{ tag: "path", attributes: { "data-chart": "loss" } }],+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /--color-displayLoss: #16a34a/);+ assert.doesNotMatch(html, /\.untrusted/);+});++test("keeps the shell when materialized media alone passes the cap", () => {+ // capturePixels rasterizes at devicePixelRatio, so the same page costs 4x on+ // a 2x display. Discarding the whole snapshot there puts back the blank+ // flash this exists to remove; drop the pixels and keep the layout instead.+ const tiles = Array.from({ length: 6 }, (_, index) => ({+ tag: "img",+ rect: [10 + index, 400, 200 + index, 200] as [number, number, number, number],+ naturalWidth: 1400,+ naturalHeight: 1000,+ attributes: { src: "blob:https://studio/tile-" + index },+ }));+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ frameDataBody: "A".repeat(600 * 1024),+ rootTree: {+ tag: "div",+ children: [+ { tag: "h1", rect: [10, 60, 400, 20], text: "Images" },+ ...tiles,+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(html, /Images/, "the shell must survive the overflow");+ assert.ok(html.length < 3 * 1024 * 1024);+ assert.equal(+ (html.match(/data:image/g) ?? []).length,+ 0,+ "the pixels that caused the overflow must be the thing dropped",+ );+});++test("materializes visible canvas pixels into the retained shell", () => {+ const environment = createEnvironment({+ navigationType: "navigate",+ styleSheets: ["/assets/index-abc123.css"],+ rootTree: {+ tag: "div",+ children: [+ {+ tag: "canvas",+ rect: [100, 900, 700, 100],+ width: 1024,+ height: 768,+ attributes: { class: "absolute inset-0", style: "opacity:0.8" },+ },+ ],+ },+ });+ environment.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });++ const { html } = storedSnapshot(environment.storage);+ assert.match(+ html,+ /style="opacity:0\.8;background-image:url\(data:image\/webp;base64,retained-frame\);background-size:100% 100%;background-repeat:no-repeat;"/,+ );+});++test("skips the shell when the snapshot carries no stylesheets", () => {+ // Without them the copy paints unstyled inside the shadow tree, which reads+ // worse than the blank interval this replaces.+ const outgoing = createEnvironment({+ navigationType: "navigate",+ rootHtml: "<main>Existing chat</main>",+ });+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });+ assert.deepEqual(storedSnapshot(outgoing.storage).styles, []);++ const incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ });+ assert.equal(incoming.appended.length, 0);+});