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: follow redirect pages when reading a web page (#11856)
Nilay405894ced259
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 93a63aad08a..8fcf84f4f6f 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -14088,6 +14088,30 @@ _MIN_SINGLE_BYTE_ASCII_RATIO = 3 / 4_ASCII_TEXT_BYTES = frozenset((*range(0x20, 0x7F), 0x09, 0x0A, 0x0D, 0x1B))_META_CHARSET_SCAN_BYTES = 2048+_META_REFRESH_SCAN_BYTES = 4096+_META_REFRESH_MAX_DELAY = 5+_META_REFRESH_CONTENT_RE = re.compile(+ r"\s*(\d+|(?=\.))(?:\.[\d.]*)?(?:(?=[\s;,])\s*[;,]?\s*(?:url\s*=\s*)?(.*))?\Z",+ re.ASCII | re.IGNORECASE | re.DOTALL,+)+# Browsers leave an unterminated named reference in an attribute alone, so "§ion=" stays literal instead of "§ion=".+_ATTR_CHAR_REF_RE = re.compile(r"&(?:#[0-9]+;?|#[xX][0-9a-fA-F]+;?|[A-Za-z][A-Za-z0-9]*;)")+# <plaintext> has no end tag: everything after it is text.+_META_REFRESH_INERT_TAGS = frozenset(+ (+ b"iframe",+ b"noembed",+ b"noframes",+ b"noscript",+ b"plaintext",+ b"script",+ b"style",+ b"template",+ b"textarea",+ b"title",+ b"xmp",+ )+)# A comment or whole tag, quoted attribute values included, so markup inside them is never read as <meta>. As in the# browser prescan, an unterminated tag ends the scan._HTML_TAG_RE = re.compile(@@ -14242,6 +14266,60 @@ def _sniff_meta_charset(head: bytes, content_type: str) -> str | None:return prolog and _whatwg_codec(prolog.group(1))+def _meta_refresh_target(body: bytes, page_url: str) -> str | None:+ from html import unescape+ from urllib.parse import urldefrag, urljoin, urlparse++ def attr_text(value: bytes) -> str:+ return _ATTR_CHAR_REF_RE.sub(+ lambda ref: unescape(ref.group(0)), value.decode("utf-8", "replace")+ )++ base_url, seen_base, inert = page_url, False, None+ for tag in _HTML_TAG_RE.finditer(body[:_META_REFRESH_SCAN_BYTES]):+ name = (tag.group(1) or b"").lower()+ if inert is not None:+ end = tag.group(0)[: len(inert) + 3].lower()+ if inert != b"plaintext" and end[:-1] == b"</" + inert and end[-1:] in b"\t\n\f\r />":+ inert = None+ elif name in _META_REFRESH_INERT_TAGS:+ inert = name+ elif name in (b"base", b"meta"):+ attrs = {}+ for attr, *values in _META_ATTR_RE.findall(tag.group(2)):+ attrs.setdefault(attr.lower(), b"".join(values))+ if name == b"base":+ # Only the first <base href> counts, and only for a refresh that comes after it.+ if b"href" in attrs and not seen_base:+ seen_base = True+ try:+ href = urljoin(page_url, attr_text(attrs[b"href"]).strip())+ if urlparse(href).scheme in ("http", "https"):+ base_url = href+ except ValueError:+ pass+ continue+ if attrs.get(b"http-equiv", b"").strip().lower() != b"refresh":+ continue+ match = _META_REFRESH_CONTENT_RE.match(attr_text(attrs.get(b"content", b"")))+ if match is None:+ continue+ location = (match.group(2) or "").strip()+ if location[:1] in ("'", '"'):+ location = location[1:].split(location[0], 1)[0].strip()+ if not location or int(match.group(1) or 0) > _META_REFRESH_MAX_DELAY:+ return None+ try:+ target = urljoin(base_url, location)+ scheme = urlparse(target).scheme+ except ValueError:+ return None+ if scheme not in ("http", "https") or urldefrag(target)[0] == urldefrag(page_url)[0]:+ return None+ return target+ return None++def _extract_pdf_text(data: bytes) -> str:"""Extract page-delimited text with the same parser used by RAG ingestion."""from ..rag.parsers import parse_pdf_bytes@@ -14751,6 +14829,21 @@ def _pinned_netloc(ip: str, port: int | None) -> str:return f"{host}:{port}" if port else host+def _redirect_hop(url: str, website_policy, deadline, cancel_event) -> tuple[str | None, str, list]:+ from urllib.parse import urlparse+ from .web_access_policy import check_url_access++ allowed, reason, host = check_url_access(url, website_policy)+ if not allowed:+ return reason, "", []+ parsed = urlparse(url)+ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ ok, reason, pinned_ips = _resolve_with_budget(host, port, deadline, cancel_event)+ if not ok:+ return reason, "", []+ return None, host, pinned_ips++def _fetch_url_raw(url: str,timeout: int = 30,@@ -14861,25 +14954,14 @@ def _fetch_url_raw(if not location:return "Failed to fetch URL: redirect missing Location header.", "", ""current_url = urljoin(current_url, location)- # Server-controlled, so never scheme-upgraded; the gate below reads .port first, so the parse after it- # cannot raise.- allowed, policy_reason, redirect_host = check_url_access(+ hop_error, current_host, pinned_ips = _redirect_hop(current_url,website_policy,- )- if not allowed:- return policy_reason, "", ""- rp = urlparse(current_url)- rp_port = rp.port or (443 if rp.scheme == "https" else 80)- ok2, reason2, pinned_ips = _resolve_with_budget(- redirect_host,- rp_port,deadline,cancel_event,)- if not ok2:- return reason2, "", ""- current_host = redirect_host+ if hop_error is not None:+ return hop_error, "", ""continue# get_content_type() defaults to "text/plain" when the header is absent (RFC 2045); report "" instead so@@ -14925,7 +15007,20 @@ def _fetch_url_raw(if tail_error is not None:return tail_error, "", ""raw_bytes += tail- break+ refresh_url = content_type == "text/html" and _meta_refresh_target(+ raw_bytes, current_url+ )+ if not refresh_url:+ break+ current_url = refresh_url+ hop_error, current_host, pinned_ips = _redirect_hop(+ current_url,+ website_policy,+ deadline,+ cancel_event,+ )+ if hop_error is not None:+ return hop_error, "", ""else:return "Failed to fetch URL: too many redirects.", "", ""diff --git a/studio/backend/tests/test_web_fetch_meta_refresh.py b/studio/backend/tests/test_web_fetch_meta_refresh.pynew file mode 100644index 00000000000..e476e00a948--- /dev/null+++ b/studio/backend/tests/test_web_fetch_meta_refresh.py@@ -0,0 +1,197 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import sys+from email.message import Message+from pathlib import Path+from urllib.parse import urlsplit++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import tools++REAL = b"<html><head><title>Real</title></head><body><main><h1>Linear</h1><p>REAL_PAGE_MARKER</p></main></body></html>"+++def _stub(content: str) -> bytes:+ return (+ b'<!DOCTYPE html><meta charset="utf-8"><title>Redirecting…</title>'+ b'<meta http-equiv="refresh" content="' + content.encode() + b'">'+ b"<p>STUB_MARKER</p>"+ )+++class _Resp:+ def __init__(self, body: bytes):+ self._body = body+ self.headers = Message()+ self.headers["Content-Type"] = "text/html; charset=utf-8"++ def read(self, n: int | None = None) -> bytes:+ chunk, self._body = (self._body, b"") if n is None else (self._body[:n], self._body[n:])+ return chunk+++def _serve(monkeypatch, pages: dict[str, bytes]) -> list[str]:+ requested = []++ def validate(host, port):+ if host == "example.com":+ return True, "", ["93.184.216.34"]+ return original(host, port)++ class Opener:+ def open(+ self,+ req,+ timeout = None,+ ):+ parts = urlsplit(req.full_url)+ url = f"{req.get_header('Host')}{parts.path}" + (+ f"?{parts.query}" if parts.query else ""+ )+ requested.append(url)+ return _Resp(pages[url])++ original = tools._validate_and_resolve_host+ monkeypatch.setattr(tools, "_validate_and_resolve_host", validate)+ monkeypatch.setattr(tools.urllib.request, "build_opener", lambda *a, **k: Opener())+ return requested+++def test_relative_meta_refresh_is_followed(monkeypatch):+ requested = _serve(+ monkeypatch,+ {+ "example.com/docs/stable/a/stub.html": _stub("0; url=../../2.9/a/real.html"),+ "example.com/docs/2.9/a/real.html": REAL,+ },+ )+ out = tools._fetch_page_text("https://example.com/docs/stable/a/stub.html", timeout = 5)+ assert "REAL_PAGE_MARKER" in out+ assert "STUB_MARKER" not in out+ assert requested == ["example.com/docs/stable/a/stub.html", "example.com/docs/2.9/a/real.html"]+++ "location, query",+ [+ ("/p?a=1§ion=2®ion=eu", "a=1§ion=2®ion=eu"),+ ("/p?a=1&copy=2", "a=1©=2"),+ ("/p?a=1&b=2", "a=1&b=2"),+ ],+)+def test_refresh_url_character_references_decode_like_a_browser(monkeypatch, location, query):+ requested = _serve(+ monkeypatch,+ {"example.com/page": _stub(f"0; url={location}"), f"example.com/p?{query}": REAL},+ )+ assert "REAL_PAGE_MARKER" in tools._fetch_page_text("https://example.com/page", timeout = 5)+ assert requested == ["example.com/page", f"example.com/p?{query}"]+++ "content",+ [+ "30",+ "0",+ "0; url=https://example.com/page#top",+ "600; url=/elsewhere",+ "0; url=javascript:alert(1)",+ ],+)+def test_reload_or_non_redirect_refresh_returns_the_page(monkeypatch, content):+ requested = _serve(monkeypatch, {"example.com/page": _stub(content)})+ out = tools._fetch_page_text("https://example.com/page", timeout = 5)+ assert "STUB_MARKER" in out+ assert requested == ["example.com/page"]+++ "wrapper",+ [+ "<script>if (!ok) document.write('{meta}');</script>",+ "<template>{meta}</template>",+ "<textarea>{meta}</textarea>",+ "<style>/* {meta} */</style>",+ "<script>x = '</scripture>{meta}';</script>",+ "<noframes>{meta}</noframes>",+ "<iframe>{meta}</iframe>",+ "<noembed>{meta}</noembed>",+ ],+)+def test_meta_refresh_inside_inert_markup_is_ignored(monkeypatch, wrapper):+ meta = '<meta http-equiv="refresh" content="0; url=/elsewhere">'+ body = f"<html><head>{wrapper.format(meta = meta)}</head><body><p>STUB_MARKER</p></body></html>"+ requested = _serve(monkeypatch, {"example.com/page": body.encode()})+ assert "STUB_MARKER" in tools._fetch_page_text("https://example.com/page", timeout = 5)+ assert requested == ["example.com/page"]+++def test_meta_refresh_after_plaintext_is_ignored():+ body = b'<plaintext></plaintext><meta http-equiv="refresh" content="0; url=/elsewhere">'+ assert tools._meta_refresh_target(body, "https://example.com/page") is None+++def test_meta_refresh_resolves_against_a_preceding_base_href(monkeypatch):+ body = (+ b'<head><base href="/docs/"><meta http-equiv="refresh" content="0; url=next.html"></head>'+ )+ requested = _serve(+ monkeypatch, {"example.com/a/b/stub.html": body, "example.com/docs/next.html": REAL}+ )+ assert "REAL_PAGE_MARKER" in tools._fetch_page_text(+ "https://example.com/a/b/stub.html", timeout = 5+ )+ assert requested == ["example.com/a/b/stub.html", "example.com/docs/next.html"]+++def test_noscript_meta_refresh_is_ignored(monkeypatch):+ body = b'<html><head><noscript><meta http-equiv="refresh" content="0; url=/nojs"></noscript></head><body><p>STUB_MARKER</p></body></html>'+ requested = _serve(monkeypatch, {"example.com/page": body})+ assert "STUB_MARKER" in tools._fetch_page_text("https://example.com/page", timeout = 5)+ assert requested == ["example.com/page"]+++def test_meta_refresh_loop_is_bounded_by_the_hop_limit(monkeypatch):+ requested = _serve(+ monkeypatch,+ {"example.com/a": _stub("0; url=/b"), "example.com/b": _stub("0; url=/a")},+ )+ out = tools._fetch_page_text("https://example.com/a", timeout = 5)+ assert out == "Failed to fetch URL: too many redirects."+ assert len(requested) == 5+++ "target",+ [+ "http://127.0.0.1:8080/admin",+ "http://169.254.169.254/latest/meta-data/",+ "http://localhost/",+ ],+)+def test_meta_refresh_to_private_host_is_blocked(monkeypatch, target):+ requested = _serve(monkeypatch, {"example.com/page": _stub(f"0; url={target}")})+ out = tools._fetch_page_text("https://example.com/page", timeout = 5)+ assert out.startswith("Blocked")+ assert requested == ["example.com/page"]+++def test_meta_refresh_rechecks_website_policy(monkeypatch):+ requested = _serve(+ monkeypatch, {"example.com/page": _stub("0; url=https://other.example.org/x")}+ )+ out = tools._fetch_page_text(+ "https://example.com/page",+ timeout = 5,+ website_policy = {"allowedDomains": ["example.com"], "blockedDomains": []},+ )+ assert "Blocked: website access policy disallows other.example.org" in out+ assert requested == ["example.com/page"]