Skip to content

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.

Studio: make Back in the browser panel work like a browser's (#14283)

Nilaya25776e1d457
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.py
index 41b4391928b..3644e1d1246 100644
--- a/studio/backend/routes/browser.py
+++ b/studio/backend/routes/browser.py
@@ -401,7 +401,16 @@ _FRAME_HTML = r"""<!doctype html>
// Without a <base> of its own a document's base is its URL, so the shell's follows the router:
// relative links and requests after a pushState resolve as in a browser.
const routedBase = cfg.url && !cfg.ownBase ? document.querySelector("base") : null;
- const post = (message) => parent.postMessage({ source: "unsloth-browser", ...message }, "*");
+ let scrollTimer = 0;
+ const post = (message) => {
+ if (scrollTimer && message.type === "navigate") reportScroll();
+ parent.postMessage({ source: "unsloth-browser", ...message }, "*");
+ };
+ const reportScroll = () => {
+ clearTimeout(scrollTimer);
+ scrollTimer = 0;
+ post({ type: "scroll", x: scrollX, y: scrollY });
+ };
// URLs built from location point at this shell; map them to the page's site.
const toPage = (url) => {
if (!cfg.url || url.origin !== shellOrigin) return url.href;
@@ -423,12 +432,12 @@ _FRAME_HTML = r"""<!doctype html>
const resolve = (href) => {
try { return toPage(new URL(href, document.baseURI)); } catch { return null; }
};
+ addEventListener("scroll", () => { scrollTimer ||= setTimeout(reportScroll, 200); }, { passive: true });
const samePage = (url) => {
const a = new URL(url), b = new URL(pageUrl);
return a.origin === b.origin && a.pathname === b.pathname && a.search === b.search;
};
// Best effort: give routers the page's path. Chromium refuses this for opaque origins.
- const originalPush = history.pushState;
const originalReplace = history.replaceState;
const shellPath = (url) => {
if (!cfg.url) return undefined;
@@ -445,15 +454,16 @@ _FRAME_HTML = r"""<!doctype html>
const target = document.getElementById(id) || document.getElementsByName(id)[0];
target?.scrollIntoView();
};
- // An in-page jump: scroll, and show its fragment in the address bar.
+ // An in-page jump: a Back step that scrolls, with its fragment in the address bar.
const followHash = (hash) => {
- scrollToHash(hash);
+ const from = pageUrl;
try {
const next = new URL(pageUrl);
next.hash = hash;
- pageUrl = next.href;
- reportUrl();
+ if (next.href !== pageUrl) pushRoute(null, "", next.href);
} catch {}
+ scrollToHash(hash);
+ tellHashChange(from);
};
const navigate = (raw, newTab, background) => {
const url = resolve(raw);
@@ -516,28 +526,98 @@ _FRAME_HTML = r"""<!doctype html>
post({ type: "url", url: pageUrl });
}, 200);
};
- for (const [method, original] of [["pushState", originalPush], ["replaceState", originalReplace]]) {
+ const setRoute = (state, title, next) => {
+ try { originalReplace.call(history, state, title, next ? shellPath(next) : undefined); }
+ catch {
+ // An opaque frame keeps its URL; carry the fragment, which hash routers read.
+ try { originalReplace.call(history, state, title, location.href.split("#")[0] + new URL(next).hash); }
+ catch { originalReplace.call(history, state, title); }
+ }
+ if (next) {
+ if (!samePage(next)) edited(false);
+ pageUrl = next;
+ routedBase?.setAttribute("href", pageUrl);
+ reportUrl();
+ }
+ };
+ // The frame shares Studio's session history: a native push would add to Studio's own Back.
+ const routes = [{ state: history.state, url: pageUrl }];
+ let route = 0;
+ // As in browsers, the panel's Back and Forward skip entries a page added without the user acting.
+ const stepFrom = (step) => {
+ let to = route + step;
+ while (routes[to]?.skip && navigator.userActivation?.hasBeenActive === false) to += step;
+ return to;
+ };
+ const tellHashChange = (from) => {
+ if (new URL(from).hash !== new URL(pageUrl).hash) dispatchEvent(new HashChangeEvent("hashchange", { oldURL: from, newURL: pageUrl }));
+ };
+ const tellHistory = () => post({ type: "history", back: Boolean(routes[stepFrom(-1)]), forward: Boolean(routes[stepFrom(1)]) });
+ const pushRoute = (state, title, next) => {
+ routes[route].scroll = { x: scrollX, y: scrollY };
+ routes[route].skip = navigator.userActivation?.hasBeenActive === false;
+ setRoute(state, title, next);
+ routes.splice(++route);
+ routes[route] = { state: history.state, url: pageUrl };
+ tellHistory();
+ };
+ const moveRoute = (to) => {
+ const target = routes[to], from = pageUrl;
+ routes[route].scroll = { x: scrollX, y: scrollY };
+ route = to;
+ setRoute(target.state, "", target.url);
+ dispatchEvent(new PopStateEvent("popstate", { state: history.state }));
+ if (target.scroll && history.scrollRestoration !== "manual") scrollTo(target.scroll.x, target.scroll.y);
+ tellHashChange(from);
+ tellHistory();
+ };
+ for (const method of ["pushState", "replaceState"]) {
history[method] = function (state, title, url) {
const raw = url != null ? String(url) : null;
let next = raw !== null ? resolve(raw) : null;
// A router that builds its URL from location.pathname gets "srcdoc": put the page's path back.
- const fromShell = raw !== null && /^(?:about:)?srcdoc(?=[?#]|$)/.exec(raw);
+ // Next.js cuts location.href past "about://" and gets "cdoc", which its state keeps for Back.
+ const fromShell = raw !== null && (/^(?:about:)?srcdoc(?=[?#]|$)/.exec(raw) || /^\/?cdoc(?=[?#]|$)/.exec(raw));
if (fromShell && cfg.url) {
const page = new URL(pageUrl);
- next = new URL(page.pathname + raw.slice(fromShell[0].length), page.origin).href;
+ const path = page.pathname + raw.slice(fromShell[0].length);
+ next = new URL(path, page.origin).href;
+ if (state?.__N && state.as === raw) state = { ...state, as: path };
}
// A router re-asserting the shell's own path is not a navigation.
if (next && new URL(next).pathname === shellPathname) next = null;
- try { original.call(this, state, title, next ? shellPath(next) : undefined); }
- catch { original.call(this, state, title); }
- if (next) {
- if (!samePage(next)) edited(false);
- pageUrl = next;
- routedBase?.setAttribute("href", pageUrl);
- reportUrl();
+ if (method === "pushState") pushRoute(state, title, next);
+ else {
+ setRoute(state, title, next);
+ routes[route] = { state: history.state, url: pageUrl };
}
};
}
+ history.go = function (delta) {
+ const step = Math.trunc(Number(delta)) || 0;
+ setTimeout(() => {
+ if (!step) post({ type: "reload" });
+ else if (!routes[route + step]) post({ type: step < 0 ? "back" : "forward" });
+ else moveRoute(route + step);
+ });
+ };
+ history.back = () => history.go(-1);
+ history.forward = () => history.go(1);
+ // A script's location.hash is a native step (history.length grows): the page's Back takes it too.
+ let nativeLength = history.length;
+ addEventListener("hashchange", (event) => {
+ if (!event.isTrusted) return;
+ const pushed = history.length > nativeLength;
+ nativeLength = history.length;
+ const next = new URL(pageUrl);
+ next.hash = location.hash;
+ if (next.href === pageUrl) return;
+ if (pushed) pushRoute(history.state, "", next.href);
+ else {
+ setRoute(history.state, "", next.href);
+ routes[route] = { state: history.state, url: pageUrl };
+ }
+ });
// Catch navigations the click and submit handlers miss (location.href, reload).
if (window.navigation) {
window.navigation.addEventListener("navigate", (event) => {
@@ -708,7 +788,14 @@ _FRAME_HTML = r"""<!doctype html>
title: document.title || "",
favicon: icon ? resolve(icon.getAttribute("href")) : resolve("/favicon.ico"),
});
- if (new URL(pageUrl).hash) scrollToHash(new URL(pageUrl).hash);
+ tellHistory();
+ if (cfg.scroll && history.scrollRestoration !== "manual") {
+ const restore = () => scrollTo(cfg.scroll.x, cfg.scroll.y);
+ restore();
+ // Again after images load and grow the page, unless the reader has scrolled.
+ const settled = scrollY;
+ addEventListener("load", () => { if (scrollY === settled) restore(); }, { once: true });
+ } else if (new URL(pageUrl).hash) scrollToHash(new URL(pageUrl).hash);
};
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", report, { once: true });
else report();
@@ -1003,6 +1090,11 @@ _FRAME_HTML = r"""<!doctype html>
else if (data.command === "find" && typeof data.query === "string" && data.query.length <= 1000) finder.search(data.query);
else if (data.command === "findStep") finder.step(data.delta === -1 ? -1 : 1);
else if (data.command === "snapshot") post({ type: "snapshot", html: snapshot() });
+ else if (data.command === "go") {
+ const to = stepFrom(data.delta === -1 ? -1 : 1);
+ if (routes[to]) moveRoute(to);
+ else post({ type: to < route ? "back" : "forward" });
+ }
else if (data.command === "agent" && typeof data.id === "string") {
// Browser use: the panel's agent code (agent/page-agent.ts), installed on first use.
if (!agent && typeof data.code === "string" && data.code.length <= 262144) {
@@ -1053,7 +1145,7 @@ _FRAME_HTML = r"""<!doctype html>
}
// Only the parent may drive the shell, once.
if (!data || data.type !== "unsloth:browser-html" || typeof data.html !== "string") return;
- const cfg = { url: data.url || null, ownBase: data.ownBase === true, anyOrigin: data.anyOrigin === true, refresh: data.refresh || null, zoom: Number(data.zoom) || 1, muted: data.muted === true, storage: data.storage || null };
+ const cfg = { url: data.url || null, ownBase: data.ownBase === true, anyOrigin: data.anyOrigin === true, refresh: data.refresh || null, zoom: Number(data.zoom) || 1, muted: data.muted === true, storage: data.storage || null, scroll: data.scroll || null };
const base = data.base ? `<base href="${escapeAttr(data.base)}">` : "";
const script = `<script>(${boot.toString()})(${JSON.stringify(cfg).replace(/</g, "\\u003c")});<\/script>`;
page = document.createElement("iframe");
diff --git a/studio/backend/tests/test_browser_routes.py b/studio/backend/tests/test_browser_routes.py
index 8419db3a508..2b08ec9ca96 100644
--- a/studio/backend/tests/test_browser_routes.py
+++ b/studio/backend/tests/test_browser_routes.py
@@ -144,6 +144,9 @@ def test_the_shell_counts_the_pages_requests_and_maps_srcdoc_paths():
for guard in (
"return nativeFetch(input, init).finally(done);",
"/^(?:about:)?srcdoc(?=[?#]|$)/",
+ "/^\\/?cdoc(?=[?#]|$)/",
+ # Back to Next.js's first route would otherwise route to /cdoc and crash the page.
+ "if (state?.__N && state.as === raw) state = { ...state, as: path };",
):
assert guard in shell, guard
@@ -160,6 +163,112 @@ def test_the_shells_base_follows_the_router_only_without_a_page_base():
)
+def test_the_pages_history_stays_out_of_studios():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ assert "history.pushState" not in boot and "originalPush" not in boot
+ for guard in (
+ 'if (method === "pushState") pushRoute(state, title, next);',
+ "history.back = () => history.go(-1);",
+ "history.forward = () => history.go(1);",
+ 'post({ type: step < 0 ? "back" : "forward" });',
+ 'dispatchEvent(new PopStateEvent("popstate", { state: history.state }));',
+ ):
+ assert guard in boot, guard
+
+
+def test_an_anchor_jump_is_a_back_step_that_returns_to_the_same_spot():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ follow = boot[boot.index("const followHash = ") : boot.index("const navigate = ")]
+ assert 'if (next.href !== pageUrl) pushRoute(null, "", next.href);' in follow
+ assert follow.index("pushRoute(") < follow.index("scrollToHash(hash);")
+ for guard in (
+ "routes[route].scroll = { x: scrollX, y: scrollY };",
+ 'if (target.scroll && history.scrollRestoration !== "manual") scrollTo(target.scroll.x, target.scroll.y);',
+ 'post({ type: "history", back: Boolean(routes[stepFrom(-1)]), forward: Boolean(routes[stepFrom(1)]) });',
+ "routes[route].skip = navigator.userActivation?.hasBeenActive === false;",
+ "const to = stepFrom(data.delta === -1 ? -1 : 1);",
+ 'post({ type: to < route ? "back" : "forward" });',
+ ):
+ assert guard in boot, guard
+
+
+def test_a_fresh_page_reports_its_history_and_skips_entries_only_until_the_reader_acts():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ report = boot[
+ boot.index("const report = () => {") : boot.index('if (document.readyState === "loading")')
+ ]
+ # A remounted frame starts with one route: the panel must not keep the old frame's Back and Forward.
+ assert (
+ report.index('type: "loaded"')
+ < report.index("tellHistory();")
+ < report.index("if (cfg.scroll && ")
+ )
+ # As Chromium's intervention: a gesture at any time makes the page's entries reachable again.
+ assert (
+ "while (routes[to]?.skip && navigator.userActivation?.hasBeenActive === false) to += step;"
+ in boot
+ )
+ assert (
+ "isActive === false"
+ not in boot[boot.index("const routes = ") : boot.index("const moveRoute = ")]
+ )
+
+
+def test_moving_between_fragments_fires_hashchange_for_hash_routers():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ assert (
+ 'dispatchEvent(new HashChangeEvent("hashchange", { oldURL: from, newURL: pageUrl }));'
+ in boot
+ )
+ assert 'location.href.split("#")[0] + new URL(next).hash' in boot
+ move = boot[boot.index("const moveRoute = ") : boot.index("for (const method of")]
+ assert move.index('new PopStateEvent("popstate"') < move.index("tellHashChange(from);")
+ follow = boot[boot.index("const followHash = ") : boot.index("const navigate = ")]
+ assert follow.index("scrollToHash(hash);") < follow.index("tellHashChange(from);")
+
+
+def test_a_scripts_fragment_change_is_a_back_step_of_the_page():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ # location.hash = "..." (AngularJS, hand-rolled hash routers) is a native push: history.back() must undo it.
+ start = boot.index("let nativeLength = history.length;")
+ hashes = boot[start : boot.index("// Catch navigations the click")]
+ for guard in (
+ "if (!event.isTrusted) return;",
+ "const pushed = history.length > nativeLength;",
+ 'if (pushed) pushRoute(history.state, "", next.href);',
+ # A location.replace redirect stays one step, so Back cannot land on it and redirect again.
+ 'setRoute(history.state, "", next.href);',
+ ):
+ assert guard in hashes, guard
+
+
+def test_a_page_that_manages_its_own_scroll_is_left_where_it_puts_itself():
+ shell = browser_mod._FRAME_HTML
+ assert 'if (cfg.scroll && history.scrollRestoration !== "manual") {' in shell
+
+
+def test_the_shell_reports_and_restores_where_the_page_was_scrolled():
+ shell = browser_mod._FRAME_HTML
+ boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
+ for guard in (
+ 'post({ type: "scroll", x: scrollX, y: scrollY });',
+ 'if (scrollTimer && message.type === "navigate") reportScroll();',
+ "scrollTimer ||= setTimeout(reportScroll, 200);",
+ "const restore = () => scrollTo(cfg.scroll.x, cfg.scroll.y);",
+ 'addEventListener("load", () => { if (scrollY === settled) restore(); }, { once: true });',
+ ):
+ assert guard in boot, guard
+ assert boot.index("if (cfg.scroll && ") < boot.index(
+ "} else if (new URL(pageUrl).hash) scrollToHash("
+ )
+ assert "scroll: data.scroll || null" in shell
+
+
def test_paths_resolved_against_the_shells_location_land_on_the_page():
shell = browser_mod._FRAME_HTML
boot = shell[shell.index("const boot = ") : shell.index("const escapeAttr")]
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 6c42d217dd4..957ab8d25c3 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -336,8 +336,10 @@ export const BUDGET = {
// Sharing a connection with every account adds the shared flags to the eager provider mapping: 180 B raw /
// 20 B transfer (6,862,624 -> 6,862,804 B raw, 2,066,394 -> 2,066,414 B transfer against 723a43b02, one
// machine and build, Node 22, 96 chunks); the share switch itself is in the lazy Connections tab. Raised by that.
- transferBytes: 2_070_754,
- rawBytes: 6_876_402,
+ // The browser panel's page history (#14283) on top measures 6,876,588 B raw / 2,070,700 B transfer (merged with
+ // main at 04d2beec9, Node 24, 97 chunks). Raised to that plus the same margin.
+ transferBytes: 2_070_889,
+ rawBytes: 6_876_748,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsx
index 7415b615199..845b2188399 100644
--- a/studio/frontend/src/features/browser/browser-panel.tsx
+++ b/studio/frontend/src/features/browser/browser-panel.tsx
@@ -169,6 +169,7 @@ import {
pageDownload,
useBrowserStore,
} from "./store";
+import { sendFrameCommand } from "./page-frame";
import { TabView } from "./tab-view";
import { ZOOM_STEPS, canZoom, homeZoom, stepZoom, zoomTab } from "./zoom";
import { useShallow } from "zustand/shallow";
@@ -1436,21 +1437,21 @@ function WebToolbar({ tab, visible }: { tab: BrowserTab | undefined; visible: bo
const { goBack, goForward, reload } = useBrowserStore.getState();
const native = nativePage(tab);
const canGoBack = Boolean(
- tab && (tab.index > 0 || (native && (tab.nativeError || tab.nativeHistory?.back))),
+ tab && (tab.index > 0 || tab.pageHistory?.back || (native && (tab.nativeError || tab.nativeHistory?.back))),
);
const canGoForward = Boolean(
- tab && (tab.index < tab.history.length - 1 || (native && tab.nativeHistory?.forward)),
+ tab && (tab.index < tab.history.length - 1 || tab.pageHistory?.forward || (native && tab.nativeHistory?.forward)),
);
const back = () => {
if (!tab) return;
if (native && tab.nativeError && returnToNativePage(tab.id)) return;
if (native && tab.nativeHistory?.back) nativeAction(tab.id, "back");
- else goBack(tab.id);
+ else if (!tab.pageHistory?.back || !sendFrameCommand(tab.id, { command: "go", delta: -1 })) goBack(tab.id);
};
const forward = () => {
if (!tab) return;
if (native && tab.nativeHistory?.forward) nativeAction(tab.id, "forward");
- else goForward(tab.id);
+ else if (!tab.pageHistory?.forward || !sendFrameCommand(tab.id, { command: "go", delta: 1 })) goForward(tab.id);
};
return (
<>
diff --git a/studio/frontend/src/features/browser/frame-message.ts b/studio/frontend/src/features/browser/frame-message.ts
index a87eb3228ad..af61b7690fc 100644
--- a/studio/frontend/src/features/browser/frame-message.ts
+++ b/studio/frontend/src/features/browser/frame-message.ts
@@ -19,7 +19,9 @@ export type FrameMessage =
| { type: "loaded"; title: string; favicon: string | null }
| { type: "title"; title: string }
| { type: "url"; url: string }
- | { type: "reload" }
+ | { type: "reload" | "back" | "forward" }
+ | { type: "scroll"; x: number; y: number }
+ | { type: "history"; back: boolean; forward: boolean }
| { type: "upload" }
| { type: "scriptNavigation" }
| { type: "needsBrowser" }
@@ -223,7 +225,16 @@ export function parseFrameMessage(data: unknown): FrameMessage | null {
case "title":
return { type: "title", title: title(message.title) };
case "reload":
- return { type: "reload" };
+ case "back":
+ case "forward":
+ return { type: message.type };
+ case "scroll": {
+ const x = coord(message.x);
+ const y = coord(message.y);
+ return x === null || y === null ? null : { type: "scroll", x, y };
+ }
+ case "history":
+ return { type: "history", back: message.back === true, forward: message.forward === true };
case "upload":
case "scriptNavigation":
case "needsBrowser":
diff --git a/studio/frontend/src/features/browser/page-frame.tsx b/studio/frontend/src/features/browser/page-frame.tsx
index e8e3510d2b7..3dc6b78dd26 100644
--- a/studio/frontend/src/features/browser/page-frame.tsx
+++ b/studio/frontend/src/features/browser/page-frame.tsx
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "react";
import { browserFrameUrl, type PageResponse, requestForPage } from "./api";
import { type AnnotateEvent, type FrameMessage, parseFrameMessage, userActionGate } from "./frame-message";
import { pageRequests } from "./page-requests";
+import { type ScrollPosition, useBrowserStore } from "./store";
import {
onPageStorageClear,
onPageStorageWrite,
@@ -24,6 +25,7 @@ export type FrameCommand =
| { command: "find"; query: string }
| { command: "findStep"; delta: -1 | 1 }
| { command: "snapshot" }
+ | { command: "go"; delta: -1 | 1 }
| { command: "zoom"; value: number }
| { command: "mute"; on: boolean }
| { command: "clearStorage" }
@@ -125,11 +127,13 @@ export function PageFrame({
tabId,
zoom = 1,
muted = false,
+ scroll,
onMessage,
}: {
tabId: string;
zoom?: number;
muted?: boolean;
+ scroll?: ScrollPosition;
html: string;
url: string | null;
base: string | null;
@@ -216,6 +220,11 @@ export function PageFrame({
left = true;
// An unrequested redirect replaces this page, as browsers keep it off Back.
if (message.type === "navigate" && !userActive(frame, message)) message = { ...message, replace: true };
+ } else if (message.type === "back" || message.type === "forward") {
+ // At the tab's first or last page nothing moves and the frame stays, so it has not left.
+ const tab = useBrowserStore.getState().tabs.find((candidate) => candidate.id === tabIdRef.current);
+ if (left || !tab?.history[tab.index + (message.type === "back" ? -1 : 1)]) return;
+ left = true;
}
onMessageRef.current(message);
};
@@ -297,6 +306,7 @@ export function PageFrame({
refresh: refresh ?? null,
zoom: zoomRef.current,
muted: mutedRef.current,
+ scroll: scroll ?? null,
storage: origin ? readPageStorage(origin, tabId) : null,
},
"*",
diff --git a/studio/frontend/src/features/browser/store.ts b/studio/frontend/src/features/browser/store.ts
index 15b7cc99aa6..9532533bd35 100644
--- a/studio/frontend/src/features/browser/store.ts
+++ b/studio/frontend/src/features/browser/store.ts
@@ -89,6 +89,7 @@ export type BrowserTab = {
nativeError: string | null;
/** The proxied page failed to load, so an error shows instead of its frame. */
pageError?: boolean;
+ pageHistory?: { back: boolean; forward: boolean } | null;
typedAt?: number;
/** The name the reader gave the tab; kept as it navigates. */
customTitle: string | null;
@@ -181,6 +182,24 @@ export function clearPageCache(): void {
pageCache.clear();
}
+export type ScrollPosition = { x: number; y: number };
+
+const scrollPositions = new WeakMap<BrowserEntry, ScrollPosition & { url: string }>();
+
+const withoutFragment = (url: string) => url.split("#")[0];
+
+/** Remember where a page was scrolled, with the address it showed: a route the page moved to is another view. */
+export function saveScroll(entry: BrowserEntry, position: ScrollPosition, url = entry.kind === "web" ? entry.url : ""): void {
+ scrollPositions.set(entry, { x: position.x, y: position.y, url });
+}
+
+/** `loaded` is where the page ended up after redirects, which is what its scroll was taken on. */
+export function savedScroll(entry: BrowserEntry, loaded = entry.kind === "web" ? entry.url : ""): ScrollPosition | undefined {
+ const saved = scrollPositions.get(entry);
+ if (!saved || entry.kind !== "web" || withoutFragment(saved.url) !== withoutFragment(loaded)) return undefined;
+ return { x: saved.x, y: saved.y };
+}
+
// Posted entries already sent: loading one again asks rather than resubmitting (tab-view.tsx).
export const sentPosts = new WeakSet<BrowserEntry>();
@@ -357,7 +376,16 @@ type BrowserState = {
patch: Partial<
Pick<
BrowserTab,
- "title" | "favicon" | "documentType" | "displayUrl" | "loading" | "nativeHistory" | "nativeError" | "pageError" | "typedAt"
+ | "title"
+ | "favicon"
+ | "documentType"
+ | "displayUrl"
+ | "loading"
+ | "nativeHistory"
+ | "nativeError"
+ | "pageError"
+ | "pageHistory"
+ | "typedAt"
>
>,
) => void;
@@ -422,6 +450,7 @@ function pushEntry(tab: BrowserTab, entry: BrowserEntry, replace = false): Brows
openKey: null,
nativeError: null,
pageError: false,
+ pageHistory: null,
typedAt: undefined,
zoom,
};
@@ -441,6 +470,7 @@ function moveTo(tab: BrowserTab, index: number): BrowserTab {
openKey: entry.kind === "file" ? (entry.openKey ?? null) : null,
nativeError: null,
pageError: false,
+ pageHistory: null,
typedAt: undefined,
};
}
@@ -729,8 +759,10 @@ export const useBrowserStore = create<BrowserState>((set, get) => {
set((state) => ({
tabs: patchTab(state.tabs, tabId, (tab) => {
const moved = routerEntry(tab);
- if (!moved) return { ...tab, reloadKey: tab.reloadKey + 1, typedAt: undefined };
+ if (!moved) return { ...tab, reloadKey: tab.reloadKey + 1, pageHistory: null, typedAt: undefined };
// Swapped in place, as a browser's reload: Forward keeps its pages.
+ const scroll = scrollPositions.get(currentEntry(tab));
+ if (scroll) scrollPositions.set(moved, scroll);
const next = pushEntry(tab, moved, true);
return { ...next, history: [...next.history, ...tab.history.slice(tab.index + 1)], reloadKey: tab.reloadKey + 1 };
}),
diff --git a/studio/frontend/src/features/browser/tab-view.tsx b/studio/frontend/src/features/browser/tab-view.tsx
index 171ae269c86..0b0cc426a1c 100644
--- a/studio/frontend/src/features/browser/tab-view.tsx
+++ b/studio/frontend/src/features/browser/tab-view.tsx
@@ -36,6 +36,8 @@ import {
cachedPage,
currentEntry,
entryKey,
+ saveScroll,
+ savedScroll,
sentPosts,
setPageDownload,
useBrowserStore,
@@ -80,7 +82,7 @@ function loadTemporary(tabId: string, entry: BrowserEntry): boolean {
return (entry.kind === "web" && entry.temporary === true) || temporaryLoads.get(tabId) === true;
}
-function useFrameMessages(tabId: string, origin: string | null) {
+function useFrameMessages(tabId: string, origin: string | null, entry: BrowserEntry) {
const t = useT();
return useCallback(
(message: FrameMessage) => {
@@ -166,6 +168,20 @@ function useFrameMessages(tabId: string, origin: string | null) {
case "reload":
store.reload(tabId);
break;
+ case "back":
+ store.goBack(tabId);
+ break;
+ case "forward":
+ store.goForward(tabId);
+ break;
+ case "scroll": {
+ const tab = store.tabs.find((candidate) => candidate.id === tabId);
+ saveScroll(entry, { x: message.x, y: message.y }, pageAddress(tab) ?? (entry.kind === "web" ? entry.url : ""));
+ break;
+ }
+ case "history":
+ store.updateTab(tabId, { pageHistory: { back: message.back, forward: message.forward } });
+ break;
case "typed":
store.updateTab(tabId, { typedAt: message.reset ? undefined : Date.now() });
break;
@@ -209,7 +225,7 @@ function useFrameMessages(tabId: string, origin: string | null) {
break;
}
},
- [tabId, origin, t],
+ [tabId, origin, entry, t],
);
}
@@ -297,7 +313,7 @@ function WebPage({
});
const blocked = state.status === "error" && state.resubmit === true;
const pageOrigin = state.status === "ready" ? new URL(state.page.url).origin : null;
- const onFrameMessage = useFrameMessages(tab.id, pageOrigin);
+ const onFrameMessage = useFrameMessages(tab.id, pageOrigin, entry);
// A notice's action opens the tab's current address, so it goes with the page it is about.
useEffect(
() => () => {
@@ -420,6 +436,7 @@ function WebPage({
tabId={tab.id}
zoom={tab.zoom}
muted={tab.muted}
+ scroll={savedScroll(entry, page.url)}
onMessage={onFrameMessage}
/>
);
diff --git a/studio/frontend/tests/browser-frame-message.test.ts b/studio/frontend/tests/browser-frame-message.test.ts
index bcab4887139..90eb869da0b 100644
--- a/studio/frontend/tests/browser-frame-message.test.ts
+++ b/studio/frontend/tests/browser-frame-message.test.ts
@@ -54,6 +54,11 @@ test("an upload notice carries nothing a page could fill", () => {
assert.deepEqual(from({ type: "scriptNavigation", url: "https://evil.example/" }), { type: "scriptNavigation" });
});
+test("a page's Back and Forward reach the panel bare", () => {
+ assert.deepEqual(from({ type: "back", url: "https://evil.example/" }), { type: "back" });
+ assert.deepEqual(from({ type: "forward", steps: 9 }), { type: "forward" });
+});
+
test("a page the sandbox refused a feature reaches the panel as a bare notice", () => {
assert.deepEqual(from({ type: "needsBrowser", url: "https://evil.example/" }), { type: "needsBrowser" });
});
diff --git a/studio/frontend/tests/browser-page-history.test.ts b/studio/frontend/tests/browser-page-history.test.ts
new file mode 100644
index 00000000000..146a02f6a0e
--- /dev/null
+++ b/studio/frontend/tests/browser-page-history.test.ts
@@ -0,0 +1,47 @@
+// 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 { register } from "node:module";
+import { test } from "node:test";
+import { readSrc } from "./helpers/kit.ts";
+
+register("./helpers/browser-store-resolver.mjs", import.meta.url);
+const { parseFrameMessage } = await import("../src/features/browser/frame-message.ts");
+const { useBrowserStore } = await import("../src/features/browser/store.ts");
+
+test("a page's own Back and Forward reach the panel as two flags", () => {
+ const from = (message: Record<string, unknown>) => parseFrameMessage({ source: "unsloth-browser", ...message });
+ assert.deepEqual(from({ type: "history", back: true, forward: false, url: "https://evil.example/" }), {
+ type: "history",
+ back: true,
+ forward: false,
+ });
+ assert.deepEqual(from({ type: "history", back: "yes", forward: 1 }), { type: "history", back: false, forward: false });
+});
+
+test("a page's Back or Forward that the panel cannot follow leaves its links working", () => {
+ // Back on a tab's first page (or Forward at its last) moves nothing, so the frame has not left.
+ const source = readSrc("features/browser/page-frame.tsx");
+ const latch = source.slice(source.indexOf('if (message.type === "loaded") {'), source.indexOf("onMessageRef.current(message);"));
+ assert.ok(latch.includes('(message.type === "navigate" && !message.newTab) || message.type === "reload"'));
+ assert.ok(latch.includes('if (left || !tab?.history[tab.index + (message.type === "back" ? -1 : 1)]) return;'));
+ assert.equal(latch.split("left = true;").length, 3);
+});
+
+test("a page's in-page Back steps are not carried to another page", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("https://en.wikipedia.org/wiki/Alan_Turing", { newTab: true });
+ const id = useBrowserStore.getState().activeTabId ?? "";
+ const tab = () => useBrowserStore.getState().tabs.find((candidate) => candidate.id === id);
+ store.updateTab(id, { pageHistory: { back: true, forward: false } });
+ assert.deepEqual(tab()?.pageHistory, { back: true, forward: false });
+ store.navigate(id, { url: "https://en.wikipedia.org/wiki/Albert_Einstein" });
+ assert.equal(tab()?.pageHistory, null);
+ store.updateTab(id, { pageHistory: { back: true, forward: false } });
+ store.goBack(id);
+ assert.equal(tab()?.pageHistory, null);
+ store.updateTab(id, { pageHistory: { back: false, forward: true } });
+ store.reload(id);
+ assert.equal(tab()?.pageHistory, null);
+});
diff --git a/studio/frontend/tests/browser-scroll-restore.test.ts b/studio/frontend/tests/browser-scroll-restore.test.ts
new file mode 100644
index 00000000000..bcb41e86630
--- /dev/null
+++ b/studio/frontend/tests/browser-scroll-restore.test.ts
@@ -0,0 +1,69 @@
+// 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 { register } from "node:module";
+import { test } from "node:test";
+
+register("./helpers/browser-store-resolver.mjs", import.meta.url);
+const { parseFrameMessage } = await import("../src/features/browser/frame-message.ts");
+const { currentEntry, saveScroll, savedScroll, useBrowserStore } = await import("../src/features/browser/store.ts");
+
+test("a page's scroll position reaches the panel as numbers only", () => {
+ const from = (message: Record<string, unknown>) => parseFrameMessage({ source: "unsloth-browser", ...message });
+ assert.deepEqual(from({ type: "scroll", x: 0, y: 4000, extra: 1 }), { type: "scroll", x: 0, y: 4000 });
+ assert.equal(from({ type: "scroll", x: 0, y: "4000" }), null);
+ assert.equal(from({ type: "scroll", x: 0, y: Number.NaN }), null);
+});
+
+test("Back and Forward return each page to where it was scrolled", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("https://en.wikipedia.org/wiki/Alan_Turing", { newTab: true });
+ const id = useBrowserStore.getState().activeTabId ?? "";
+ const shown = () => currentEntry(useBrowserStore.getState().tabs.find((tab) => tab.id === id)!);
+ saveScroll(shown(), { x: 0, y: 4000 });
+ store.navigate(id, { url: "https://en.wikipedia.org/wiki/Albert_Einstein" });
+ assert.equal(savedScroll(shown()), undefined);
+ saveScroll(shown(), { x: 0, y: 1200 });
+ store.goBack(id);
+ assert.deepEqual(savedScroll(shown()), { x: 0, y: 4000 });
+ store.goForward(id);
+ assert.deepEqual(savedScroll(shown()), { x: 0, y: 1200 });
+ store.goBack(id);
+ store.navigate(id, { url: "https://en.wikipedia.org/wiki/Albert_Einstein" });
+ assert.equal(savedScroll(shown()), undefined);
+});
+
+test("a scroll taken on a route the page moved to is not applied to the page it was opened at", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("https://huggingface.co/models", { newTab: true });
+ const id = useBrowserStore.getState().activeTabId ?? "";
+ const shown = () => currentEntry(useBrowserStore.getState().tabs.find((tab) => tab.id === id)!);
+ saveScroll(shown(), { x: 0, y: 900 }, "https://huggingface.co/models?search=qwen");
+ assert.equal(savedScroll(shown()), undefined);
+ saveScroll(shown(), { x: 0, y: 300 }, "https://huggingface.co/models#top");
+ assert.deepEqual(savedScroll(shown()), { x: 0, y: 300 });
+});
+
+test("Reload keeps the scroll of a page that moved its route", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("https://huggingface.co/models", { newTab: true });
+ const id = useBrowserStore.getState().activeTabId ?? "";
+ const shown = () => currentEntry(useBrowserStore.getState().tabs.find((tab) => tab.id === id)!);
+ store.updateTab(id, { displayUrl: "https://huggingface.co/models?search=qwen" });
+ saveScroll(shown(), { x: 0, y: 900 }, "https://huggingface.co/models?search=qwen");
+ store.reload(id);
+ const entry = shown();
+ assert.equal(entry.kind === "web" && entry.url, "https://huggingface.co/models?search=qwen");
+ assert.deepEqual(savedScroll(shown()), { x: 0, y: 900 });
+});
+
+test("a page that redirected gets its scroll back on Back", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("http://example.com/docs", { newTab: true });
+ const id = useBrowserStore.getState().activeTabId ?? "";
+ const shown = () => currentEntry(useBrowserStore.getState().tabs.find((tab) => tab.id === id)!);
+ saveScroll(shown(), { x: 0, y: 700 }, "https://example.com/docs/");
+ assert.deepEqual(savedScroll(shown(), "https://example.com/docs/"), { x: 0, y: 700 });
+ assert.equal(savedScroll(shown(), "https://example.com/docs/other"), undefined);
+});