Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep site settings across pages in the browser panel (#13762)
Nilay7f600f6488eb
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.pyindex 5b99574d4bf..e65c5032274 100644--- a/studio/backend/routes/browser.py+++ b/studio/backend/routes/browser.py@@ -180,6 +180,200 @@ _FRAME_CSP = ("treat-as-public-address")+# Opaque origins throw on storage and cookies: these keep a site's data in the panel (page-storage.ts) for the session.+_PAGE_STORAGE_JS = r"""+ // Past the panel's quota (page-storage.ts) a value stays in this page only.+ const kept = (key, value) => key.length + value.length <= 131072;+ // Numbered so the panel's echo of an older write can't undo a newer one still on its way.+ let writes = 0;+ const sync = (area, key, value) => {+ const seq = ++writes;+ const store = pageStores[area];+ if (key === null) {+ store.clearedAt = seq;+ store.latest.clear();+ } else store.latest.set(key, seq);+ post({+ type: "storage", area, key, url: pageUrl, seq,+ value: key !== null && value !== null && kept(key, value) ? value : null,+ });+ };+ const pageStores = {};+ const pageStore = (area) => {+ const data = new Map(cfg.storage?.[area] || []);+ const store = {+ data,+ latest: new Map(),+ acked: new Map(),+ clearedAt: 0,+ clearAcked: 0,+ set: (key, value) => {+ data.set(key, value);+ sync(area, key, value);+ },+ // Always sent: another tab may have written the key since this page loaded.+ remove: (key) => {+ data.delete(key);+ sync(area, key, null);+ },+ clear: () => {+ data.clear();+ sync(area, null, null);+ },+ };+ pageStores[area] = store;+ return store;+ };+ const text = (value) => value === null || typeof value === "string";+ const storages = {};+ window.addEventListener("message", (event) => {+ const data = event.data;+ if (event.source !== parent || !data || data.type !== "unsloth:browser-command") return;+ // Clearing browsing data empties the open page's copy too. The clear is sent back after any write+ // still on its way to the panel, so that write can't refill the cleared store.+ if (data.command === "clearStorage") {+ for (const [area, store] of Object.entries(pageStores)) {+ store.data.clear();+ sync(area, null, null);+ }+ }+ // Another open page of this site changed its data, as other tabs do in a browser.+ else if (data.command === "storageSync" && (data.area === "local" || data.area === "cookie") && text(data.key) && text(data.value)) {+ const store = pageStores[data.area];+ if (!store) return;+ // This page's write or clear of the key is still on its way: its own echo settles the key.+ const pending = (key) =>+ store.clearedAt > store.clearAcked || (key !== null && (store.latest.get(key) ?? 0) > (store.acked.get(key) ?? 0));+ const oldValue = data.key === null ? null : (store.data.get(data.key) ?? null);+ if (data.own === true) {+ const seq = Number(data.seq) || 0;+ if (data.key === null) store.clearAcked = Math.max(store.clearAcked, seq);+ else store.acked.set(data.key, Math.max(store.acked.get(data.key) ?? 0, seq));+ // Refused by the panel's quota: the value stays in this page only.+ if (data.refused === true) return;+ if (store.clearedAt > seq || (data.key !== null && (store.latest.get(data.key) ?? 0) > seq)) return;+ if (data.key === null) {+ // Keys written after the clear stay.+ for (const key of Array.from(store.data.keys())) if ((store.latest.get(key) ?? 0) <= seq) store.data.delete(key);+ return;+ }+ if (data.value === null && oldValue !== null && !kept(data.key, oldValue)) return;+ } else if (data.key === null ? Array.from(store.data.keys()).some(pending) : pending(data.key)) {+ if (data.key !== null) return;+ for (const key of Array.from(store.data.keys())) if (!pending(key)) store.data.delete(key);+ return;+ }+ // Like a browser, a write that changes nothing fires no event (two pages could echo it forever).+ if (data.key === null ? !store.data.size : oldValue === data.value) return;+ if (data.key === null) store.data.clear();+ else if (data.value === null) store.data.delete(data.key);+ else store.data.set(data.key, data.value);+ // This page's own write, coming back in order to settle a race with another page: no event.+ if (data.area === "local" && data.own !== true) {+ try {+ const url = typeof data.url === "string" ? data.url : "";+ const change = new StorageEvent("storage", { key: data.key, oldValue, newValue: data.value, url });+ // The init dictionary only takes a real Storage, so sites' `storageArea === localStorage` checks need this.+ Object.defineProperty(change, "storageArea", { value: storages.local });+ window.dispatchEvent(change);+ } catch {}+ }+ }+ });+ for (const [name, area] of [["localStorage", "local"], ["sessionStorage", "session"]]) {+ try { void window[name]; } catch {+ const store = pageStore(area);+ const methods = {+ get length() { return store.data.size; },+ key: (i) => Array.from(store.data.keys())[i] ?? null,+ getItem: (k) => store.data.get(String(k)) ?? null,+ setItem: (k, v) => store.set(String(k), String(v)),+ removeItem: (k) => store.remove(String(k)),+ clear: store.clear,+ [Symbol.toStringTag]: "Storage",+ };+ // Keys are properties too, as on Storage: sites read and write localStorage.theme.+ const named = (key) => typeof key === "string" && !(key in methods) && store.data.has(key);+ const storage = new Proxy(Object.create(methods), {+ get: (_, key) => (named(key) ? store.data.get(key) : Reflect.get(methods, key)),+ set: (_, key, value) => {+ if (typeof key === "string") store.set(key, String(value));+ return true;+ },+ has: (_, key) => named(key) || key in methods,+ deleteProperty: (_, key) => {+ if (named(key)) store.remove(key);+ return true;+ },+ ownKeys: () => Array.from(store.data.keys()),+ getOwnPropertyDescriptor: (_, key) =>+ named(key) ? { value: store.data.get(key), writable: true, enumerable: true, configurable: true } : undefined,+ });+ storages[area] = storage;+ try { Object.defineProperty(window, name, { value: storage, configurable: true }); } catch {}+ }+ }+ // Keyed "<name>=<path>" (a name has no "="), valued "<deadline>|<value>": a cookie keeps its+ // path and its Max-Age or Expires across pages.+ const cookies = pageStore("cookie");+ const pagePath = () => {+ try { return new URL(pageUrl).pathname; } catch { return "/"; }+ };+ const defaultPath = (path) => (path.startsWith("/") && path.lastIndexOf("/") > 0 ? path.slice(0, path.lastIndexOf("/")) : "/");+ const pathMatch = (scope, path) =>+ path === scope || (path.startsWith(scope) && (scope.endsWith("/") || path[scope.length] === "/"));+ const setCookie = (raw) => {+ const [pair, ...attributes] = String(raw).split(";");+ const at = pair.indexOf("=");+ const name = at < 0 ? "" : pair.slice(0, at).trim();+ const value = (at < 0 ? pair : pair.slice(at + 1)).trim();+ if ((!name && !value) || name.length + value.length > 4096) return;+ let maxAge = null, expires = null, path = null, domain = "";+ for (const attribute of attributes) {+ const eq = attribute.indexOf("=");+ const key = (eq < 0 ? attribute : attribute.slice(0, eq)).trim().toLowerCase();+ const setting = eq < 0 ? "" : attribute.slice(eq + 1).trim();+ if (key === "max-age" && /^-?\d+$/.test(setting)) maxAge = Number(setting);+ else if (key === "expires") expires = Date.parse(setting);+ else if (key === "path" && setting.startsWith("/")) path = setting;+ else if (key === "domain") domain = setting.replace(/^\./, "").toLowerCase();+ }+ if (domain) {+ let host = "";+ try { host = new URL(pageUrl).hostname; } catch {}+ // A browser refuses a Domain the page isn't on; one it is on still stays with this site only.+ if (host !== domain && !host.endsWith("." + domain)) return;+ }+ const id = name + "=" + (path ?? defaultPath(pagePath()));+ const deadline = maxAge !== null ? Date.now() + maxAge * 1000 : expires !== null && !Number.isNaN(expires) ? expires : null;+ if (deadline !== null && deadline <= Date.now()) cookies.remove(id);+ else cookies.set(id, (deadline ?? "") + "|" + value);+ };+ const liveCookies = () => {+ const path = pagePath();+ const live = [];+ for (const [id, stored] of cookies.data) {+ const at = stored.indexOf("|");+ if (at > 0 && Number(stored.slice(0, at)) <= Date.now()) {+ cookies.remove(id);+ continue;+ }+ const eq = id.indexOf("=");+ const scope = id.slice(eq + 1);+ if (pathMatch(scope, path)) live.push([scope.length, eq ? id.slice(0, eq) + "=" + stored.slice(at + 1) : stored.slice(at + 1)]);+ }+ // Longer paths first, as browsers order them.+ return live.sort((a, b) => b[0] - a[0]).map(([, cookie]) => cookie).join("; ");+ };+ try {+ Object.defineProperty(document, "cookie", {+ get: liveCookies,+ set: setCookie,+ configurable: true,+ });+ } catch {}+"""+# Page shell: injects <base> and a script turning navigations into panel messages. The page is a# srcdoc child; the shell then sets frame-src 'none' on itself so the child can't be navigated# (it keeps its own policy copy, so embeds still load), independent of the embedder's policy.@@ -253,27 +447,7 @@ _FRAME_HTML = r"""<!doctype html>if (!cfg.url && new URL(url).origin === shellOrigin) return;post({ type: "navigate", url, newTab: Boolean(newTab), background: Boolean(background) });};- const fallbackStorage = () => {- const data = new Map();- return {- get length() { return data.size; },- key: (i) => Array.from(data.keys())[i] ?? null,- getItem: (k) => data.has(String(k)) ? data.get(String(k)) : null,- setItem: (k, v) => void data.set(String(k), String(v)),- removeItem: (k) => void data.delete(String(k)),- clear: () => data.clear(),- };- };- // Opaque origins throw on storage and cookies; stub them so pages don't crash.- for (const name of ["localStorage", "sessionStorage"]) {- try { void window[name]; } catch {- try { Object.defineProperty(window, name, { value: fallbackStorage(), configurable: true }); } catch {}- }- }- try {- let jar = "";- Object.defineProperty(document, "cookie", { get: () => jar, set: () => {}, configurable: true });- } catch {}+ /* PAGE_STORAGE_JS */let refused = false;const tellRefused = () => {if (refused) return;@@ -778,7 +952,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 };+ 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 base = data.base ? `<base href="${escapeAttr(data.base)}">` : "";const script = `<script>(${boot.toString()})(${JSON.stringify(cfg).replace(/</g, "\\u003c")});<\/script>`;page = document.createElement("iframe");@@ -804,6 +978,7 @@ _FRAME_HTML = r"""<!doctype html></html>"""_FRAME_HTML = _FRAME_HTML.replace("/* BROWSER_NETWORK_JS */", BROWSER_NETWORK_JS.strip(), 1)+_FRAME_HTML = _FRAME_HTML.replace("/* PAGE_STORAGE_JS */", _PAGE_STORAGE_JS.strip(), 1)# Annotate, the body of a function of `post` that the page shell's `install` runs on the panel's# request: while it is on, pointer input is the panel's, and the page only reports the block underdiff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex cf33bbf707f..15a180107c5 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -136,8 +136,12 @@ export const BUDGET = {// Main was 48 B raw / 29 B transfer over at ffa8fc3b9 (6,771,709 B raw, 2,035,904 B transfer). The browser// panel's notice for pages that hit a sandbox limit (#13761) adds 143 B raw / 44 B transfer (-> 6,771,852 B raw,// 2,035,948 B transfer, one machine and build, Node 24, chunk count unchanged at 95). Raised by both.- transferBytes: 2_035_948,- rawBytes: 6_771_852,+ // Keeping site storage across browser panel pages (#13762) adds 1,644 B raw / 466 B transfer, the page-storage+ // module the eager browser store imports for tab close and duplicate (6,771,852 -> 6,773,496 B raw, 2,035,948 ->+ // 2,036,414 B transfer against 82f16ca55, one machine and build, Node 24, chunk count unchanged at 95). Raised by+ // that growth.+ transferBytes: 2_036_414,+ rawBytes: 6_773_496,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/features/browser/clear-data-dialog.tsx b/studio/frontend/src/features/browser/clear-data-dialog.tsxindex e107a795baf..5ff11bd56fd 100644--- a/studio/frontend/src/features/browser/clear-data-dialog.tsx+++ b/studio/frontend/src/features/browser/clear-data-dialog.tsx@@ -15,6 +15,7 @@ import { useT } from "@/i18n";import { toast } from "@/lib/toast";import { useBrowserHistoryStore } from "./history-store";import { clearNativeBrowsingData, useNativeBrowser } from "./native-support";+import { clearPageStorage } from "./page-storage";import { useBrowserPrefsStore } from "./prefs-store";import { clearPageCache } from "./store";@@ -44,6 +45,7 @@ export function ClearBrowsingDataDialog({history.clearHistory();history.clearDownloads();clearPageCache();+ clearPageStorage();// Suggestions come from history, so the ones taken off come back with it gone.useBrowserPrefsStore.getState().restoreSuggestions();clearNativeBrowsingData().then(diff --git a/studio/frontend/src/features/browser/frame-message.ts b/studio/frontend/src/features/browser/frame-message.tsindex e6c1827e0a9..25749f44aa2 100644--- a/studio/frontend/src/features/browser/frame-message.ts+++ b/studio/frontend/src/features/browser/frame-message.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import type { PageStorageArea } from "./page-storage";+export type FrameMessage =| {type: "navigate";@@ -32,7 +34,15 @@ export type FrameMessage =/** A fetch or XHR to the page's own site, for the panel to make (routes/browser_network.py);* `request` is null for one the panel won't make (malformed, too large), which then fails. */| { type: "request"; id: string; request: PageRequest | null }- | { type: "requestAbort"; id: string };+ | { type: "requestAbort"; id: string }+ | {+ type: "storage";+ area: PageStorageArea;+ key: string | null;+ value: string | null;+ url: string | null;+ seq: number | null;+ };export type RedirectMode = "follow" | "error" | "manual";@@ -86,6 +96,10 @@ const MAX_REQUEST_BODY_BYTES = 1024 * 1024;const text = (value: unknown, max: number): string | null =>typeof value === "string" && value.length <= max ? value : null;+const STORAGE_AREAS = new Set<unknown>(["local", "session", "cookie"]);+// An area's quota (page-storage.ts).+const MAX_STORAGE_CHARS = 128 * 1024;+const title = (value: unknown): string => (typeof value === "string" ? value.slice(0, MAX_TITLE_CHARS) : "");const coord = (value: unknown): number | null =>@@ -232,6 +246,18 @@ export function parseFrameMessage(data: unknown): FrameMessage | null {if (!id) return null;return message.type === "request" ? { type: "request", id, request: pageRequest(message) } : { type: "requestAbort", id };}+ case "storage": {+ const { area, key, value } = message;+ if (!STORAGE_AREAS.has(area)) return null;+ const url = text(message.url, MAX_URL_CHARS);+ const seq = Number.isSafeInteger(message.seq) && (message.seq as number) > 0 ? (message.seq as number) : null;+ if (key === null) return { type: "storage", area: area as PageStorageArea, key: null, value: null, url, seq };+ const name = text(key, MAX_STORAGE_CHARS);+ const stored = value === null ? null : text(value, MAX_STORAGE_CHARS);+ return name === null || (value !== null && stored === null)+ ? null+ : { type: "storage", area: area as PageStorageArea, key: name, value: stored, url, seq };+ }default:return null;}diff --git a/studio/frontend/src/features/browser/page-frame.tsx b/studio/frontend/src/features/browser/page-frame.tsxindex 8f4bae0a931..20741ae26ff 100644--- a/studio/frontend/src/features/browser/page-frame.tsx+++ b/studio/frontend/src/features/browser/page-frame.tsx@@ -5,6 +5,14 @@ import { useEffect, useRef, useState } from "react";import { browserFrameUrl, type PageResponse, requestForPage } from "./api";import { type AnnotateEvent, type FrameMessage, parseFrameMessage } from "./frame-message";import { pageRequests } from "./page-requests";+import {+ onPageStorageClear,+ onPageStorageWrite,+ type PageStorageArea,+ pageOrigin,+ readPageStorage,+ writePageStorage,+} from "./page-storage";export type { FrameMessage };@@ -18,6 +26,17 @@ export type FrameCommand =| { command: "snapshot" }| { command: "zoom"; value: number }| { command: "mute"; on: boolean }+ | { command: "clearStorage" }+ | {+ command: "storageSync";+ area: PageStorageArea;+ key: string | null;+ value: string | null;+ url: string | null;+ own: boolean;+ seq: number | null;+ refused: boolean;+ }| { command: "annotateInstall"; code: string }| { command: "annotate"; on: boolean; color?: string }| { command: "annotateForget"; id: number }@@ -139,6 +158,8 @@ export function PageFrame({urlRef.current = url;});const [loadId] = useState(() => String(++loadCounter));+ // Fixed per frame, from the address the panel loaded: never from what the page says.+ const [origin] = useState(() => pageOrigin(url));const postedRef = useRef(false);useEffect(() => {@@ -180,6 +201,19 @@ export function PageFrame({agentRequests.get(message.id)?.({ installed: message.installed, result: message.result });return;}+ if (message.type === "storage") {+ if (origin) writePageStorage(+ origin,+ tabIdRef.current,+ message.area,+ message.key,+ message.value,+ frame,+ message.url,+ message.seq,+ );+ return;+ }if (isUserAction(message)) {if (!userActive(frame, message)) return;// Shortcuts too: a script can queue many before the first one moves focus off the page.@@ -199,11 +233,32 @@ export function PageFrame({onMessageRef.current(message);};window.addEventListener("message", listener);+ const stopClearing = onPageStorageClear(() => sendFrameCommand(tabIdRef.current, { command: "clearStorage" }));+ // sessionStorage belongs to one tab, which shows one page.+ const stopSyncing = onPageStorageWrite(({ origin: site, area, key, value, requested, from, url, seq }) => {+ const target = frameRef.current;+ if (!target || site !== origin || area === "session") return;+ const own = from === target;+ // The writer hears back too, so racing pages settle on the store's value; a refused value stays in its page.+ const command: FrameCommand = {+ command: "storageSync",+ area,+ key,+ value,+ url: url ?? null,+ own,+ seq: own ? (seq ?? null) : null,+ refused: own && value !== requested,+ };+ target.contentWindow?.postMessage({ type: "unsloth:browser-command", ...command }, "*");+ });return () => {window.removeEventListener("message", listener);+ stopClearing();+ stopSyncing();requests.stop();};- }, []);+ }, [origin]);useEffect(() => {const frame = frameRef.current;@@ -253,6 +308,7 @@ export function PageFrame({refresh: refresh ?? null,zoom: zoomRef.current,muted: mutedRef.current,+ storage: origin ? readPageStorage(origin, tabId) : null,},"*",);diff --git a/studio/frontend/src/features/browser/page-storage.ts b/studio/frontend/src/features/browser/page-storage.tsnew file mode 100644index 00000000000..aac754fc10b--- /dev/null+++ b/studio/frontend/src/features/browser/page-storage.ts@@ -0,0 +1,130 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type PageStorageArea = "local" | "session" | "cookie";+export type PageStorage = Record<PageStorageArea, Array<[string, string]>>;++// Per area and site, in characters, so caches like a site's script store aren't kept.+const PAGE_STORAGE_QUOTA = 128 * 1024;+const MAX_TOTAL_CHARS = 4 * 1024 * 1024;++type Store = { items: Map<string, string>; chars: number };++// In memory only, so nothing outlives the session.+const stores = new Map<string, Store>();+let totalChars = 0;++const storeKey = (origin: string, tabId: string, area: PageStorageArea) =>+ area === "session" ? `session ${tabId} ${origin}` : `${area} ${origin}`;++export function pageOrigin(url: string | null): string | null {+ if (!url) return null;+ try {+ const parsed = new URL(url);+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.origin : null;+ } catch {+ return null;+ }+}++export function readPageStorage(origin: string, tabId: string): PageStorage {+ const entries = (area: PageStorageArea) => Array.from(stores.get(storeKey(origin, tabId, area))?.items ?? []);+ return { local: entries("local"), session: entries("session"), cookie: entries("cookie") };+}++export type PageStorageWrite = {+ origin: string;+ tabId: string;+ area: PageStorageArea;+ key: string | null;+ value: string | null;+ /** What the page asked to store; `value` is what the store kept. */+ requested: string | null;+ from?: unknown;+ url?: string | null;+ seq?: number | null;+};++const writeListeners = new Set<(write: PageStorageWrite) => void>();++export function onPageStorageWrite(listener: (write: PageStorageWrite) => void): () => void {+ writeListeners.add(listener);+ return () => writeListeners.delete(listener);+}++/** One change a page made: a null value removes the key, a null key clears the area. */+export function writePageStorage(+ origin: string,+ tabId: string,+ area: PageStorageArea,+ key: string | null,+ value: string | null,+ from?: unknown,+ url?: string | null,+ seq?: number | null,+): void {+ save(origin, tabId, area, key, value);+ const kept = key === null ? null : (stores.get(storeKey(origin, tabId, area))?.items.get(key) ?? null);+ for (const listener of writeListeners) listener({ origin, tabId, area, key, value: kept, requested: value, from, url, seq });+}++function evict(): void {+ for (const [other, { chars: otherChars }] of stores) {+ if (totalChars <= MAX_TOTAL_CHARS) break;+ stores.delete(other);+ totalChars -= otherChars;+ }+}++function save(origin: string, tabId: string, area: PageStorageArea, key: string | null, value: string | null): void {+ const id = storeKey(origin, tabId, area);+ const store = stores.get(id) ?? { items: new Map<string, string>(), chars: 0 };+ stores.delete(id);+ totalChars -= store.chars;+ if (key === null) return;+ const old = store.items.get(key);+ store.chars -= old === undefined ? 0 : key.length + old.length;+ if (value !== null && store.chars + key.length + value.length <= PAGE_STORAGE_QUOTA) {+ store.items.set(key, value);+ store.chars += key.length + value.length;+ } else {+ store.items.delete(key);+ }+ if (store.items.size === 0) return;+ stores.set(id, store);+ totalChars += store.chars;+ evict();+}++export function dropTabPageStorage(tabId: string): void {+ const prefix = `session ${tabId} `;+ for (const [id, store] of stores) {+ if (!id.startsWith(prefix)) continue;+ stores.delete(id);+ totalChars -= store.chars;+ }+}++/** A duplicated tab starts with a copy of the original's sessionStorage, as in a browser. */+export function copyTabPageStorage(fromTabId: string, toTabId: string): void {+ const prefix = `session ${fromTabId} `;+ for (const [id, store] of Array.from(stores)) {+ if (!id.startsWith(prefix)) continue;+ stores.set(`session ${toTabId} ${id.slice(prefix.length)}`, { items: new Map(store.items), chars: store.chars });+ totalChars += store.chars;+ }+ evict();+}++const clearListeners = new Set<() => void>();++export function onPageStorageClear(listener: () => void): () => void {+ clearListeners.add(listener);+ return () => clearListeners.delete(listener);+}++export function clearPageStorage(): void {+ stores.clear();+ totalChars = 0;+ for (const listener of clearListeners) listener();+}diff --git a/studio/frontend/src/features/browser/store.ts b/studio/frontend/src/features/browser/store.tsindex 68bd2b03e3f..8ca97f30eda 100644--- a/studio/frontend/src/features/browser/store.ts+++ b/studio/frontend/src/features/browser/store.ts@@ -6,6 +6,7 @@ import { create } from "zustand";import { unwrapRedirect } from "./address";import type { BrowserPage } from "./api";import { PageCache, cacheLimits, reportedDeviceMemory } from "./page-cache";+import { copyTabPageStorage, dropTabPageStorage } from "./page-storage";import { setShownBrowserChat } from "./panel-availability";import { defaultZoom } from "./prefs-store";import { REACT_PREVIEW_KEY_PREFIX, REACT_PREVIEW_TYPE } from "./react-preview-type";@@ -584,7 +585,9 @@ export const useBrowserStore = create<BrowserState>((set, get) => {duplicateTab: (tabId) => {const tab = get().tabs.find((candidate) => candidate.id === tabId);if (!tab) return;- openTab(copyTab(tab), false, tabId, tab.chat);+ const copy = copyTab(tab);+ copyTabPageStorage(tab.id, copy.id);+ openTab(copy, false, tabId, tab.chat);},openPinned: (pinnedId, url, title) => {const shown = chatTabs(get()).find((tab) => tab.pinnedId === pinnedId);@@ -756,6 +759,7 @@ export const useBrowserStore = create<BrowserState>((set, get) => {for (const entry of closing.history) pageCache.delete(entry);releaseFiles(remaining);pageDownloads.delete(tabId);+ dropTabPageStorage(tabId);const { [tabId]: _closed, ...fileViews } = get().fileViews;const annotateTabId = get().annotateTabId === tabId ? null : get().annotateTabId;const renamingTabId = get().renamingTabId === tabId ? null : get().renamingTabId;diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 77f606bda6d..6d1188597b3 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -261,7 +261,7 @@ export const ar = {annotationScreenshotsAlways: "التضمين دائمًا",annotationScreenshotsNever: "عدم التضمين أبدًا",clearDataSetting: "مسح بيانات التصفح",- clearDataSettingDescription: "مسح سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا. لا تحتفظ الصفحات بأي ملفات تعريف ارتباط أو بيانات مواقع.",+ clearDataSettingDescription: "مسح سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا. تحتفظ الصفحات بملفات تعريف الارتباط وبيانات المواقع فقط حتى إعادة تحميل Studio.",manage: "إدارة",fullView: {enter: "عرض كامل",@@ -437,7 +437,7 @@ export const ar = {},clearData: {title: "هل تريد مسح بيانات التصفح؟",- description: "سيؤدي هذا إلى مسح سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا. تبقى الملفات التي تم تنزيلها على جهاز الكمبيوتر.",+ description: "يمسح هذا سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا وملفات تعريف الارتباط وبيانات المواقع، مما يسجّل خروجك من المواقع. تبقى الملفات المنزّلة على جهازك.",cancel: "إلغاء",confirm: "مسح البيانات",done: "تم مسح بيانات التصفح",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex c553cb7b577..7e4fe99abee 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -261,7 +261,7 @@ export const de = {annotationScreenshotsAlways: "Immer beifügen",annotationScreenshotsNever: "Nie beifügen",clearDataSetting: "Browserdaten löschen",- clearDataSettingDescription: "Löscht Browserverlauf, Download-Verlauf und zwischengespeicherte Seiten. Seiten speichern keine Cookies oder Website-Daten.",+ clearDataSettingDescription: "Löscht Browserverlauf, Download-Verlauf und zwischengespeicherte Seiten. Seiten speichern Cookies und Website-Daten nur, bis Studio neu geladen wird.",manage: "Verwalten",fullView: {enter: "Vollansicht",@@ -437,7 +437,7 @@ export const de = {},clearData: {title: "Browserdaten löschen?",- description: "Dadurch werden dein Browserverlauf, Download-Verlauf und zwischengespeicherte Seiten gelöscht. Heruntergeladene Dateien bleiben auf deinem Computer.",+ description: "Dadurch werden Browserverlauf, Downloadverlauf, zwischengespeicherte Seiten sowie Cookies und Websitedaten gelöscht, und du wirst von Websites abgemeldet. Heruntergeladene Dateien bleiben auf deinem Computer.",cancel: "Abbrechen",confirm: "Daten löschen",done: "Browserdaten gelöscht",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 861070e049b..60a36e1ccdb 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -258,7 +258,7 @@ export const en = {annotationScreenshotsAlways: "Always include",annotationScreenshotsNever: "Never include",clearDataSetting: "Clear browsing data",- clearDataSettingDescription: "Clear browsing history, download history and cached pages. Pages keep no cookies or site data.",+ clearDataSettingDescription: "Clear browsing history, download history and cached pages. Pages keep cookies and site data only until Studio is reloaded.",manage: "Manage",fullView: {enter: "Enter full view",@@ -434,7 +434,7 @@ export const en = {},clearData: {title: "Clear browsing data?",- description: "This clears your browsing history, download history and cached pages. Downloaded files stay on your computer.",+ description: "This clears your browsing history, download history, cached pages, and site cookies and data, which signs you out of sites. Downloaded files stay on your computer.",cancel: "Cancel",confirm: "Clear data",done: "Browsing data cleared",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 94cc547951f..be3fc9cb0ae 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -261,7 +261,7 @@ export const es = {annotationScreenshotsAlways: "Incluir siempre",annotationScreenshotsNever: "No incluir nunca",clearDataSetting: "Borrar datos de navegación",- clearDataSettingDescription: "Borra el historial de navegación, el historial de descargas y las páginas en caché. Las páginas no guardan cookies ni datos de sitios.",+ clearDataSettingDescription: "Borra el historial de navegación, el historial de descargas y las páginas en caché. Las páginas guardan cookies y datos de sitios solo hasta que se recarga Studio.",manage: "Administrar",fullView: {enter: "Vista completa",@@ -437,7 +437,7 @@ export const es = {},clearData: {title: "¿Borrar datos de navegación?",- description: "Se borrarán tu historial de navegación, el historial de descargas y las páginas en caché. Los archivos descargados se quedan en tu equipo.",+ description: "Esto borra el historial de navegación, el historial de descargas, las páginas en caché y las cookies y datos de sitios, lo que cierra tu sesión en los sitios. Los archivos descargados se quedan en tu equipo.",cancel: "Cancelar",confirm: "Borrar datos",done: "Datos de navegación borrados",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 5068426ab0e..07ea036a856 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -261,7 +261,7 @@ export const fr = {annotationScreenshotsAlways: "Toujours inclure",annotationScreenshotsNever: "Ne jamais inclure",clearDataSetting: "Effacer les données de navigation",- clearDataSettingDescription: "Efface l’historique de navigation, l’historique des téléchargements et les pages en cache. Les pages ne conservent aucun cookie ni aucune donnée de site.",+ clearDataSettingDescription: "Efface l’historique de navigation, l’historique des téléchargements et les pages en cache. Les pages ne conservent les cookies et les données de site que jusqu’au rechargement de Studio.",manage: "Gérer",fullView: {enter: "Plein écran",@@ -437,7 +437,7 @@ export const fr = {},clearData: {title: "Effacer les données de navigation ?",- description: "Cette action efface votre historique de navigation, l’historique des téléchargements et les pages en cache. Les fichiers téléchargés restent sur votre ordinateur.",+ description: "Cela efface l'historique de navigation, l'historique des téléchargements, les pages en cache ainsi que les cookies et données de sites, ce qui vous déconnecte des sites. Les fichiers téléchargés restent sur votre ordinateur.",cancel: "Annuler",confirm: "Effacer les données",done: "Données de navigation effacées",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 192bf2cce73..500cf4353c8 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -271,7 +271,7 @@ export const he = {annotationScreenshotsNever: "לעולם לא לכלול",clearDataSetting: "ניקוי נתוני גלישה",clearDataSettingDescription:- "נקה את היסטוריית הגלישה, היסטוריית ההורדות והדפים השמורים במטמון. הדפים אינם שומרים קובצי Cookie או נתוני אתרים.",+ "נקה את היסטוריית הגלישה, היסטוריית ההורדות והדפים השמורים במטמון. הדפים שומרים קובצי Cookie ונתוני אתרים רק עד לטעינה מחדש של Studio.",manage: "ניהול",fullView: {enter: "עבור לתצוגה מלאה",@@ -448,7 +448,7 @@ export const he = {clearData: {title: "לנקות את נתוני הגלישה?",description:- "פעולה זו מנקה את היסטוריית הגלישה, היסטוריית ההורדות והדפים השמורים במטמון. קבצים שהורדו יישארו במחשב שלך.",+ "פעולה זו מנקה את היסטוריית הגלישה, היסטוריית ההורדות, הדפים השמורים במטמון וקובצי Cookie ונתוני אתרים, מה שינתק אותך מאתרים. קבצים שהורדו יישארו במחשב שלך.",cancel: "ביטול",confirm: "נקה נתונים",done: "נתוני הגלישה נוקו",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 632c0baa912..9ec854f0897 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -261,7 +261,7 @@ export const hi = {annotationScreenshotsAlways: "हमेशा शामिल करें",annotationScreenshotsNever: "कभी शामिल न करें",clearDataSetting: "ब्राउज़िंग डेटा साफ़ करें",- clearDataSettingDescription: "ब्राउज़िंग हिस्ट्री, डाउनलोड हिस्ट्री और कैश किए गए पेज साफ़ करें। पेज कोई कुकी या साइट डेटा नहीं रखते।",+ clearDataSettingDescription: "ब्राउज़िंग हिस्ट्री, डाउनलोड हिस्ट्री और कैश किए गए पेज साफ़ करें। पेज कुकी और साइट डेटा सिर्फ़ तब तक रखते हैं जब तक Studio फिर से लोड न हो।",manage: "मैनेज करें",fullView: {enter: "पूर्ण दृश्य",@@ -437,7 +437,7 @@ export const hi = {},clearData: {title: "ब्राउज़िंग डेटा साफ़ करें?",- description: "इससे आपकी ब्राउज़िंग हिस्ट्री, डाउनलोड हिस्ट्री और कैश किए गए पेज साफ़ हो जाते हैं। डाउनलोड की गई फ़ाइलें आपके कंप्यूटर पर बनी रहती हैं।",+ description: "इससे आपका ब्राउज़िंग इतिहास, डाउनलोड इतिहास, कैश किए गए पेज और साइट कुकीज़ व डेटा साफ़ हो जाते हैं, और आप साइटों से साइन आउट हो जाते हैं। डाउनलोड की गई फ़ाइलें आपके कंप्यूटर पर रहती हैं।",cancel: "रद्द करें",confirm: "डेटा साफ़ करें",done: "ब्राउज़िंग डेटा साफ़ हो गया",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 3dc903b5de1..bbfb27990fc 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -260,7 +260,7 @@ export const it = {annotationScreenshotsAlways: "Includi sempre",annotationScreenshotsNever: "Non includere mai",clearDataSetting: "Cancella dati di navigazione",- clearDataSettingDescription: "Cancella la cronologia di navigazione, la cronologia download e le pagine nella cache. Le pagine non conservano cookie né dati dei siti.",+ clearDataSettingDescription: "Cancella la cronologia di navigazione, la cronologia download e le pagine nella cache. Le pagine conservano cookie e dati dei siti solo fino al ricaricamento di Studio.",manage: "Gestisci",fullView: {enter: "Vista completa",@@ -436,7 +436,7 @@ export const it = {},clearData: {title: "Cancellare i dati di navigazione?",- description: "Verranno cancellate la cronologia di navigazione, la cronologia download e le pagine nella cache. I file scaricati restano sul tuo computer.",+ description: "Questo cancella cronologia di navigazione, cronologia dei download, pagine in cache e cookie e dati dei siti, disconnettendoti dai siti. I file scaricati restano sul computer.",cancel: "Annulla",confirm: "Cancella dati",done: "Dati di navigazione cancellati",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 72cfdb02a1a..35a3f122aa2 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -262,7 +262,7 @@ export const ja = {annotationScreenshotsAlways: "常に含める",annotationScreenshotsNever: "含めない",clearDataSetting: "閲覧データを消去",- clearDataSettingDescription: "閲覧履歴、ダウンロード履歴、キャッシュされたページを消去します。ページには Cookie やサイトデータは保存されません。",+ clearDataSettingDescription: "閲覧履歴、ダウンロード履歴、キャッシュされたページを消去します。ページの Cookie やサイトデータは Studio を再読み込みするまでのみ保持されます。",manage: "管理",fullView: {enter: "全画面表示",@@ -438,7 +438,7 @@ export const ja = {},clearData: {title: "閲覧データを消去しますか?",- description: "閲覧履歴、ダウンロード履歴、キャッシュされたページを消去します。ダウンロードしたファイルはコンピュータに残ります。",+ description: "閲覧履歴、ダウンロード履歴、キャッシュされたページ、サイトの Cookie とデータを消去し、サイトからログアウトします。ダウンロードしたファイルはコンピューターに残ります。",cancel: "キャンセル",confirm: "データを消去",done: "閲覧データを消去しました",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex a5dac398aeb..9216de09e23 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -261,7 +261,7 @@ export const ko = {annotationScreenshotsAlways: "항상 포함",annotationScreenshotsNever: "포함하지 않음",clearDataSetting: "인터넷 사용 기록 삭제",- clearDataSettingDescription: "방문 기록, 다운로드 기록, 캐시된 페이지를 삭제합니다. 페이지는 쿠키나 사이트 데이터를 저장하지 않습니다.",+ clearDataSettingDescription: "방문 기록, 다운로드 기록, 캐시된 페이지를 삭제합니다. 페이지는 Studio를 다시 불러올 때까지만 쿠키와 사이트 데이터를 저장합니다.",manage: "관리",fullView: {enter: "전체 보기",@@ -437,7 +437,7 @@ export const ko = {},clearData: {title: "인터넷 사용 기록을 삭제할까요?",- description: "방문 기록, 다운로드 기록, 캐시된 페이지가 삭제됩니다. 다운로드한 파일은 컴퓨터에 그대로 남습니다.",+ description: "방문 기록, 다운로드 기록, 캐시된 페이지, 사이트 쿠키와 데이터를 삭제하며 사이트에서 로그아웃됩니다. 다운로드한 파일은 컴퓨터에 남아 있습니다.",cancel: "취소",confirm: "데이터 삭제",done: "인터넷 사용 기록을 삭제했습니다",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex f1ad70b301f..7a03948df22 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -261,7 +261,7 @@ export const ptBR = {annotationScreenshotsAlways: "Sempre incluir",annotationScreenshotsNever: "Nunca incluir",clearDataSetting: "Limpar dados de navegação",- clearDataSettingDescription: "Limpa o histórico de navegação, o histórico de downloads e as páginas em cache. As páginas não guardam cookies nem dados de sites.",+ clearDataSettingDescription: "Limpa o histórico de navegação, o histórico de downloads e as páginas em cache. As páginas guardam cookies e dados de sites só até o Studio ser recarregado.",manage: "Gerenciar",fullView: {enter: "Visualização completa",@@ -437,7 +437,7 @@ export const ptBR = {},clearData: {title: "Limpar dados de navegação?",- description: "Isso limpa seu histórico de navegação, o histórico de downloads e as páginas em cache. Os arquivos baixados continuam no seu computador.",+ description: "Isso limpa o histórico de navegação, o histórico de downloads, as páginas em cache e os cookies e dados de sites, o que encerra sua sessão nos sites. Os arquivos baixados continuam no seu computador.",cancel: "Cancelar",confirm: "Limpar dados",done: "Dados de navegação limpos",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 3c04f5398c0..615a05b6d8a 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -261,7 +261,7 @@ export const ru = {annotationScreenshotsAlways: "Всегда добавлять",annotationScreenshotsNever: "Никогда не добавлять",clearDataSetting: "Очистить данные браузера",- clearDataSettingDescription: "Очищает историю просмотров, историю загрузок и кешированные страницы. Страницы не сохраняют файлы cookie и данные сайтов.",+ clearDataSettingDescription: "Очищает историю просмотров, историю загрузок и кешированные страницы. Страницы хранят файлы cookie и данные сайтов только до перезагрузки Studio.",manage: "Управлять",fullView: {enter: "Полный экран",@@ -437,7 +437,7 @@ export const ru = {},clearData: {title: "Очистить данные браузера?",- description: "Будут очищены история просмотров, история загрузок и кешированные страницы. Скачанные файлы останутся на вашем компьютере.",+ description: "Будут очищены история просмотров, история загрузок, кэшированные страницы, а также файлы cookie и данные сайтов, и вы выйдете из аккаунтов на сайтах. Загруженные файлы останутся на компьютере.",cancel: "Отмена",confirm: "Очистить данные",done: "Данные браузера очищены",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 453c90af2a4..436b3a3e37d 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -273,7 +273,7 @@ export const sv = {annotationScreenshotsNever: "Ta aldrig med",clearDataSetting: "Rensa webbdata",clearDataSettingDescription:- "Rensa webbhistorik, hämtningshistorik och cachade sidor. Sidor sparar inga cookies eller webbplatsdata.",+ "Rensa webbhistorik, hämtningshistorik och cachade sidor. Sidor sparar cookies och webbplatsdata bara tills Studio laddas om.",manage: "Hantera",fullView: {enter: "Öppna helvy",@@ -452,7 +452,7 @@ export const sv = {clearData: {title: "Rensa webbdata?",description:- "Detta rensar din webbhistorik, hämtningshistorik och cachade sidor. Hämtade filer finns kvar på datorn.",+ "Detta rensar din webbhistorik, hämtningshistorik, cachade sidor samt webbplatsers cookies och data, vilket loggar ut dig från webbplatser. Hämtade filer finns kvar på datorn.",cancel: "Avbryt",confirm: "Rensa data",done: "Webbdata rensades",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex ece39729964..0848aec769a 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -261,7 +261,7 @@ export const zhCN = {annotationScreenshotsAlways: "始终附带",annotationScreenshotsNever: "从不附带",clearDataSetting: "清除浏览数据",- clearDataSettingDescription: "清除浏览历史记录、下载历史记录和缓存的页面。页面不会保留任何 Cookie 或网站数据。",+ clearDataSettingDescription: "清除浏览历史记录、下载历史记录和缓存的页面。页面仅在重新加载 Studio 之前保留 Cookie 和网站数据。",manage: "管理",fullView: {enter: "全屏视图",@@ -437,7 +437,7 @@ export const zhCN = {},clearData: {title: "清除浏览数据?",- description: "这将清除你的浏览历史记录、下载历史记录和缓存的页面。已下载的文件会保留在你的电脑上。",+ description: "这会清除浏览历史、下载历史、缓存的页面以及网站 Cookie 和数据,并让你退出各网站。已下载的文件会保留在你的电脑上。",cancel: "取消",confirm: "清除数据",done: "已清除浏览数据",diff --git a/studio/frontend/tests/browser-page-storage.test.ts b/studio/frontend/tests/browser-page-storage.test.tsnew file mode 100644index 00000000000..399a707d5fe--- /dev/null+++ b/studio/frontend/tests/browser-page-storage.test.ts@@ -0,0 +1,442 @@+// 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 { runInNewContext } from "node:vm";+import { parseFrameMessage } from "../src/features/browser/frame-message.ts";+import {+ clearPageStorage,+ copyTabPageStorage,+ dropTabPageStorage,+ onPageStorageClear,+ onPageStorageWrite,+ pageOrigin,+ readPageStorage,+ writePageStorage,+} from "../src/features/browser/page-storage.ts";++// The page shell's cookie and storage stand-ins (routes/browser.py), run as shipped.+const source = readFileSync(new URL("../../backend/routes/browser.py", import.meta.url), "utf8")+ .split('_PAGE_STORAGE_JS = r"""')[1]+ .split('"""')[0];++const clock = { now: Date.UTC(2026, 9, 15) };+const pageDate = { now: () => clock.now, parse: Date.parse };+class StorageEvent {+ constructor(type: string, init: Record<string, unknown>) {+ Object.assign(this, init, { type });+ }+}+const stopPages: Array<() => void> = [];+// Messages between pages and the panel, held in order when a test needs them in flight.+let deferred: Array<() => void> | null = null;+const deliver = (run: () => void) => (deferred ? deferred.push(run) : run());++function flush() {+ while (deferred?.length) {+ deferred.shift()?.();+ }+ deferred = null;+}++function reset() {+ deferred = null;+ clearPageStorage();+ for (const stop of stopPages.splice(0)) {+ stop();+ }+}++function openPage(url: string, tabId = "tab-1") {+ const origin = pageOrigin(url);+ const parent = {};+ const self = {};+ const listeners: Array<(event: { source: unknown; data: unknown }) => void> = [];+ const events: Array<{ key: string | null; newValue: string | null; storageArea: unknown; url: string }> = [];+ const window = {+ addEventListener: (type: string, listener: (event: { source: unknown; data: unknown }) => void) => {+ if (type === "message") {+ listeners.push(listener);+ }+ },+ dispatchEvent: (event: { key: string | null; newValue: string | null; storageArea: unknown; url: string }) =>+ events.push(event),+ };+ for (const name of ["localStorage", "sessionStorage"]) {+ Object.defineProperty(window, name, {+ configurable: true,+ get: () => {+ throw new Error("SecurityError");+ },+ });+ }+ const document = {};+ const post = (message: Record<string, unknown>) => {+ const parsed = parseFrameMessage({ source: "unsloth-browser", ...message });+ if (parsed?.type === "storage" && origin) {+ deliver(() =>+ writePageStorage(origin, tabId, parsed.area, parsed.key, parsed.value, self, parsed.url, parsed.seq),+ );+ }+ };+ const cfg = { storage: origin ? readPageStorage(origin, tabId) : null };+ runInNewContext(source, { window, document, cfg, post, parent, Date: pageDate, StorageEvent, URL, pageUrl: url });+ const message = (data: unknown, source: unknown = parent) => {+ for (const listener of listeners) {+ listener({ source, data });+ }+ };+ // As page-frame.tsx does for every open page.+ stopPages.push(+ onPageStorageWrite(({ origin: site, area, key, value, requested, from, url: writer, seq }) => {+ const own = from === self;+ if (site === origin && area !== "session") {+ const refused = own && value !== requested;+ const command = { command: "storageSync", area, key, value, url: writer ?? null, own, seq: own ? seq : null, refused };+ deliver(() => message({ type: "unsloth:browser-command", ...command }));+ }+ }),+ );+ return {+ window: window as unknown as Record<string, Storage>,+ document: document as { cookie: string },+ message,+ events,+ };+}++test("a cookie set on one page is there on the same site's next page", () => {+ reset();+ const first = openPage("https://en.wikipedia.org/wiki/Cat");+ first.document.cookie = "enwikimwclientpreferences=skin-theme-clientpref-night; path=/; max-age=2592000; secure";+ first.document.cookie = "consent=yes; path=/";+ assert.equal(first.document.cookie, "enwikimwclientpreferences=skin-theme-clientpref-night; consent=yes");+ const next = openPage("https://en.wikipedia.org/wiki/Dog");+ assert.equal(next.document.cookie, "enwikimwclientpreferences=skin-theme-clientpref-night; consent=yes");+});++test("expired cookies are removed", () => {+ reset();+ const page = openPage("https://example.com/");+ page.document.cookie = "a=1";+ page.document.cookie = "b=2";+ page.document.cookie = "a=; expires=Thu, 01 Jan 1970 00:00:00 GMT";+ page.document.cookie = "b=2; max-age=0";+ assert.equal(page.document.cookie, "");+ assert.equal(openPage("https://example.com/next").document.cookie, "");+});++test("localStorage carries over within the site, and sessionStorage within the tab", () => {+ reset();+ const first = openPage("https://example.com/");+ first.window.localStorage.setItem("banner", "closed");+ first.window.sessionStorage.setItem("step", "2");+ const next = openPage("https://example.com/about");+ assert.equal(next.window.localStorage.getItem("banner"), "closed");+ assert.equal(next.window.sessionStorage.getItem("step"), "2");+ assert.equal(openPage("https://example.com/", "tab-2").window.sessionStorage.getItem("step"), null);+ next.window.localStorage.removeItem("banner");+ assert.equal(openPage("https://example.com/").window.localStorage.getItem("banner"), null);+ next.window.sessionStorage.clear();+ assert.equal(openPage("https://example.com/").window.sessionStorage.length, 0);+});++test("one site never sees another site's cookies or storage", () => {+ reset();+ const site = openPage("https://a.example/");+ site.document.cookie = "session=secret";+ site.window.localStorage.setItem("token", "secret");+ for (const url of ["https://b.example/", "http://a.example/", "https://a.example:8443/", "https://sub.a.example/"]) {+ const other = openPage(url);+ assert.equal(other.document.cookie, "", url);+ assert.equal(other.window.localStorage.getItem("token"), null, url);+ }+ const local = openPage("about:blank");+ local.document.cookie = "x=1";+ assert.deepEqual(readPageStorage("null", "tab-1"), { local: [], session: [], cookie: [] });+});++test("values past the quota stay in their page, and the store stays bounded", () => {+ reset();+ const page = openPage("https://example.com/");+ page.window.localStorage.setItem("small", "kept");+ page.window.localStorage.setItem("cache", "x".repeat(200 * 1024));+ assert.equal(page.window.localStorage.getItem("cache")?.length, 200 * 1024);+ const next = openPage("https://example.com/next");+ assert.equal(next.window.localStorage.getItem("small"), "kept");+ assert.equal(next.window.localStorage.getItem("cache"), null);+ next.window.localStorage.setItem("small", "x".repeat(200 * 1024));+ assert.equal(openPage("https://example.com/").window.localStorage.getItem("small"), null);+ for (let i = 0; i < 40; i++) writePageStorage(`https://site${i}.example`, "tab-1", "local", "k", "x".repeat(120_000));+ assert.deepEqual(readPageStorage("https://site0.example", "tab-1").local, []);+ assert.equal(readPageStorage("https://site39.example", "tab-1").local.length, 1);+});++test("malformed storage messages are dropped", () => {+ const from = (message: Record<string, unknown>) => parseFrameMessage({ source: "unsloth-browser", type: "storage", ...message });+ assert.equal(from({ area: "indexedDB", key: "a", value: "b" }), null);+ assert.equal(from({ area: "local", key: 1, value: "b" }), null);+ assert.equal(from({ area: "local", key: "a", value: {} }), null);+ assert.equal(from({ area: "local", key: "a", value: "x".repeat(128 * 1024 + 1) }), null);+ assert.deepEqual(from({ area: "cookie", key: null, value: "ignored" }), {+ type: "storage",+ area: "cookie",+ key: null,+ value: null,+ url: null,+ seq: null,+ });+ assert.deepEqual(from({ area: "local", key: "a", value: null, url: "https://example.com/" }), {+ type: "storage",+ area: "local",+ key: "a",+ value: null,+ url: "https://example.com/",+ seq: null,+ });+});++test("keys read and write as properties too, as on a real Storage", () => {+ reset();+ const first = openPage("https://example.com/");+ (first.window.localStorage as unknown as Record<string, string>).currentTheme = "dark";+ const next = openPage("https://example.com/docs");+ const storage = next.window.localStorage as unknown as Record<string, unknown>;+ assert.equal(storage.currentTheme, "dark");+ assert.equal("currentTheme" in storage, true);+ assert.deepEqual(Object.keys(storage), ["currentTheme"]);+ assert.equal(typeof storage.getItem, "function");+ assert.equal(storage.missing, undefined);+ Reflect.deleteProperty(storage, "currentTheme");+ assert.equal(openPage("https://example.com/").window.localStorage.getItem("currentTheme"), null);+});++test("a removal reaches the store for a key another tab wrote after this page loaded", () => {+ reset();+ const older = openPage("https://example.com/", "tab-1");+ const newer = openPage("https://example.com/", "tab-2");+ newer.window.localStorage.setItem("token", "t");+ newer.document.cookie = "sid=1";+ older.window.localStorage.removeItem("token");+ older.document.cookie = "sid=; max-age=0";+ const next = openPage("https://example.com/next", "tab-1");+ assert.equal(next.window.localStorage.getItem("token"), null);+ assert.equal(next.document.cookie, "");+ newer.window.localStorage.setItem("banner", "closed");+ older.window.localStorage.clear();+ assert.equal(openPage("https://example.com/", "tab-1").window.localStorage.length, 0);+});++test("clearing browsing data empties the pages that are open, too", () => {+ reset();+ const page = openPage("https://example.com/");+ page.window.localStorage.setItem("banner", "closed");+ page.document.cookie = "sid=1";+ const clear = { type: "unsloth:browser-command", command: "clearStorage" };+ page.message(clear, {});+ assert.equal(page.window.localStorage.getItem("banner"), "closed");+ const stop = onPageStorageClear(() => page.message(clear));+ clearPageStorage();+ stop();+ assert.equal(page.window.localStorage.getItem("banner"), null);+ assert.equal(page.document.cookie, "");+ page.window.localStorage.setItem("seen", "1");+ assert.deepEqual(readPageStorage("https://example.com", "tab-1"), { local: [["seen", "1"]], session: [], cookie: [] });+});++test("a cookie's Max-Age or Expires still ends it on later pages", () => {+ reset();+ const page = openPage("https://example.com/");+ page.document.cookie = "flag=1; Max-Age=60";+ page.document.cookie = `promo=shown; Expires=${new Date(clock.now + 120_000).toUTCString()}`;+ page.document.cookie = "theme=dark";+ assert.equal(openPage("https://example.com/next").document.cookie, "flag=1; promo=shown; theme=dark");+ clock.now += 61_000;+ assert.equal(page.document.cookie, "promo=shown; theme=dark");+ clock.now += 60_000;+ assert.equal(openPage("https://example.com/later").document.cookie, "theme=dark");+});++test("a write shows up at once in the site's other open pages", () => {+ reset();+ const first = openPage("https://example.com/", "tab-1");+ const second = openPage("https://example.com/reader", "tab-2");+ const other = openPage("https://other.example/", "tab-3");+ first.window.localStorage.setItem("state", '{"theme":"dark"}');+ first.document.cookie = "sid=1";+ first.window.sessionStorage.setItem("step", "2");+ assert.equal(second.window.localStorage.getItem("state"), '{"theme":"dark"}');+ assert.equal(second.document.cookie, "sid=1");+ assert.equal(second.window.sessionStorage.getItem("step"), null);+ assert.equal(other.window.localStorage.getItem("state"), null);+ assert.deepEqual(+ second.events.map((event) => [event.key, event.newValue]),+ [["state", '{"theme":"dark"}']],+ );+ assert.equal(second.events[0]?.storageArea, second.window.localStorage);+ assert.equal(second.events[0]?.url, "https://example.com/");+ first.window.localStorage.setItem("state", '{"theme":"dark"}');+ first.window.localStorage.removeItem("missing");+ assert.equal(second.events.length, 1);+ first.window.localStorage.removeItem("state");+ assert.equal(second.window.localStorage.getItem("state"), null);+});++test("a closed tab's sessionStorage is dropped", () => {+ reset();+ const page = openPage("https://example.com/", "tab-1");+ page.window.sessionStorage.setItem("step", "2");+ page.window.localStorage.setItem("banner", "closed");+ dropTabPageStorage("tab-1");+ const next = openPage("https://example.com/", "tab-1");+ assert.equal(next.window.sessionStorage.getItem("step"), null);+ assert.equal(next.window.localStorage.getItem("banner"), "closed");+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").session, []);+});++test("a cookie keeps its path, as in a browser", () => {+ reset();+ const login = openPage("https://example.com/account/login");+ login.document.cookie = "mode=account";+ login.document.cookie = "theme=dark; path=/";+ login.document.cookie = "mode=root; path=/";+ assert.equal(openPage("https://example.com/").document.cookie, "theme=dark; mode=root");+ assert.equal(openPage("https://example.com/account/settings").document.cookie, "mode=account; theme=dark; mode=root");+ assert.equal(openPage("https://example.com/accounts").document.cookie, "theme=dark; mode=root");+ login.document.cookie = "mode=; max-age=0";+ assert.equal(openPage("https://example.com/account/settings").document.cookie, "theme=dark; mode=root");+});++test("a duplicated tab starts with the original's sessionStorage", () => {+ reset();+ const page = openPage("https://example.com/", "tab-1");+ page.window.sessionStorage.setItem("step", "2");+ copyTabPageStorage("tab-1", "tab-2");+ const copy = openPage("https://example.com/", "tab-2");+ assert.equal(copy.window.sessionStorage.getItem("step"), "2");+ copy.window.sessionStorage.setItem("step", "3");+ assert.equal(openPage("https://example.com/", "tab-1").window.sessionStorage.getItem("step"), "2");+});++test("racing writes from two open pages settle on the store's value", () => {+ reset();+ const first = openPage("https://example.com/", "tab-1");+ const second = openPage("https://example.com/", "tab-2");+ deferred = [];+ first.window.localStorage.setItem("k", "a");+ second.window.localStorage.setItem("k", "b");+ flush();+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").local, [["k", "b"]]);+ assert.equal(first.window.localStorage.getItem("k"), "b");+ assert.equal(second.window.localStorage.getItem("k"), "b");+});++test("a write on its way during Clear browsing data doesn't come back", () => {+ reset();+ const page = openPage("https://example.com/");+ const stop = onPageStorageClear(() =>+ deliver(() => page.message({ type: "unsloth:browser-command", command: "clearStorage" })),+ );+ deferred = [];+ page.window.localStorage.setItem("banner", "closed");+ clearPageStorage();+ flush();+ stop();+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").local, []);+ assert.equal(page.window.localStorage.getItem("banner"), null);+});++test("a cookie for a domain the page isn't on is refused", () => {+ reset();+ const page = openPage("https://www.example.com/");+ page.document.cookie = "a=1; Domain=other.example";+ page.document.cookie = "b=2; Domain=.example.com";+ page.document.cookie = "c=3; Domain=www.example.com";+ assert.equal(page.document.cookie, "b=2; c=3");+});++test("an earlier write's echo doesn't undo a newer write in the same page", () => {+ reset();+ const page = openPage("https://example.com/");+ deferred = [];+ page.window.localStorage.setItem("k", "a");+ page.window.localStorage.setItem("k", "b");+ // The panel takes the first write and echoes it before the second arrives.+ deferred.shift()?.();+ deferred.pop()?.();+ assert.equal(page.window.localStorage.getItem("k"), "b");+ flush();+ assert.equal(page.window.localStorage.getItem("k"), "b");+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").local, [["k", "b"]]);+});++test("a value too large for the panel stays in the page after a smaller one", () => {+ reset();+ const page = openPage("https://example.com/");+ const large = "x".repeat(140_000);+ deferred = [];+ page.window.localStorage.setItem("k", "small");+ page.window.localStorage.setItem("k", large);+ flush();+ assert.equal(page.window.localStorage.getItem("k"), large);+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").local, []);+});++test("a clear's echo doesn't drop a key the page wrote after it", () => {+ reset();+ const page = openPage("https://example.com/");+ page.window.localStorage.setItem("old", "1");+ deferred = [];+ page.window.localStorage.clear();+ page.window.localStorage.setItem("k", "v");+ deferred.shift()?.();+ deferred.pop()?.();+ assert.equal(page.window.localStorage.getItem("k"), "v");+ flush();+ assert.equal(page.window.localStorage.getItem("k"), "v");+ assert.equal(page.window.localStorage.getItem("old"), null);+ assert.deepEqual(readPageStorage("https://example.com", "tab-1").local, [["k", "v"]]);+});++test("another page's older write doesn't undo this page's write still on its way", () => {+ reset();+ const first = openPage("https://example.com/", "tab-1");+ const second = openPage("https://example.com/", "tab-2");+ deferred = [];+ first.window.localStorage.setItem("k", "a");+ second.window.localStorage.setItem("k", "b");+ // The panel stores the first page's write and tells the second before the second's write lands.+ deferred.shift()?.();+ for (let i = deferred.length - 1; i >= 1; i--) {+ deferred.splice(i, 1)[0]?.();+ }+ assert.equal(second.window.localStorage.getItem("k"), "b");+ flush();+ assert.equal(first.window.localStorage.getItem("k"), "b");+ assert.equal(second.window.localStorage.getItem("k"), "b");+});++test("a value too large for the panel stays in its page when another page wrote the key first", () => {+ reset();+ const first = openPage("https://example.com/", "tab-1");+ const second = openPage("https://example.com/", "tab-2");+ const large = "x".repeat(140_000);+ deferred = [];+ first.window.localStorage.setItem("k", "small");+ second.window.localStorage.setItem("k", large);+ flush();+ assert.equal(second.window.localStorage.getItem("k"), large);+});++test("a value refused for the site's total quota stays in its page and doesn't block later syncs", () => {+ reset();+ const first = openPage("https://example.com/", "tab-1");+ const second = openPage("https://example.com/", "tab-2");+ first.window.localStorage.setItem("fill", "y".repeat(120_000));+ second.window.localStorage.setItem("k", "z".repeat(20_000));+ assert.equal(second.window.localStorage.getItem("k")?.length, 20_000);+ first.window.localStorage.setItem("k", "later");+ assert.equal(second.window.localStorage.getItem("k"), "later");+});