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
# 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 os
import sys
import pytest
from core import agents_md
from routes import chat_history
@pytest.fixture
def home(tmp_path, monkeypatch):
monkeypatch.setattr(agents_md, "_owner_home", lambda: tmp_path / "home")
monkeypatch.setattr(agents_md, "workspace_root", lambda: tmp_path / "home/.unsloth/studio")
monkeypatch.setattr(agents_md, "is_owner_context", lambda: True)
monkeypatch.delenv("UNSLOTH_STUDIO_AGENTS_MD", raising = False)
for name in ("home/.agents", "home/.claude", "home/.unsloth/studio", "proj/sandbox", "host"):
(tmp_path / name).mkdir(parents = True)
return tmp_path
def _project(home, **extra):
return {
"rootPath": str(home / "proj"),
"sandboxPath": str(home / "proj/sandbox"),
"archived": False,
**extra,
}
def _write(path, text):
path.write_text(text, encoding = "utf-8")
def test_nothing_on_disk_reads_as_empty(home):
assert agents_md.agents_md_text(None) == ""
assert agents_md.agents_md_text(_project(home)) == ""
def test_global_then_project_then_sandbox_each_under_its_source(home):
_write(home / "home/.unsloth/studio/AGENTS.md", "Be brief.\n")
_write(home / "proj/AGENTS.md", "Use pnpm.")
_write(home / "proj/sandbox/AGENTS.md", "Notes: tests pass.")
assert agents_md.agents_md_text(_project(home)) == (
"# Source: ~/.unsloth/studio/AGENTS.md\n\nBe brief.\n\n"
f"# Source: {(home / 'proj/AGENTS.md').as_posix()}\n\nUse pnpm.\n\n"
f"# Source: {(home / 'proj/sandbox/AGENTS.md').as_posix()}\n\nNotes: tests pass."
)
# A chat outside any project still gets the global file.
assert agents_md.agents_md_text(None) == "# Source: ~/.unsloth/studio/AGENTS.md\n\nBe brief."
def test_other_tools_global_files_are_not_read(home):
_write(home / "home/.agents/AGENTS.md", "agents rules")
_write(home / "home/.claude/CLAUDE.md", "claude rules")
assert agents_md.agents_md_text(_project(home)) == ""
def test_claude_md_only_stands_in_for_a_missing_agents_md(home):
_write(home / "proj/CLAUDE.md", "From CLAUDE.md")
assert agents_md.agents_md_text(_project(home)).endswith("From CLAUDE.md")
_write(home / "proj/AGENTS.md", "From AGENTS.md")
text = agents_md.agents_md_text(_project(home))
assert text.endswith("From AGENTS.md") and "CLAUDE.md" not in text
@pytest.mark.skipif(
sys.platform == "win32", reason = "symlinks need admin or developer mode on Windows"
)
def test_project_root_link_reads_but_sandbox_link_does_not(home):
_write(home / "proj/AGENTS.md", "Use pnpm.")
# CLAUDE.md -> AGENTS.md at the root is common and stays readable.
os.symlink(home / "proj/AGENTS.md", home / "proj/CLAUDE.md")
(home / "proj/AGENTS.md").unlink()
_write(home / "proj/real.md", "Linked rules")
os.symlink(home / "proj/real.md", home / "proj/AGENTS.md")
assert agents_md.agents_md_text(_project(home)).endswith("Linked rules")
# A link the model plants in its sandbox must not pull a host file into the prompt.
_write(home / "host/secret.txt", "HOST SECRET")
os.symlink(home / "host/secret.txt", home / "proj/sandbox/AGENTS.md")
os.symlink(home / "host/secret.txt", home / "proj/sandbox/CLAUDE.md")
assert "HOST SECRET" not in agents_md.agents_md_text(_project(home))
def test_edits_are_seen_and_size_is_capped(home):
target = home / "home/.unsloth/studio/AGENTS.md"
_write(target, "first")
assert agents_md.agents_md_text(None).endswith("first")
_write(target, "second edit")
assert agents_md.agents_md_text(None).endswith("second edit")
_write(target, "x" * (agents_md.MAX_AGENTS_MD_BYTES * 2))
text = agents_md.agents_md_text(None)
assert text.endswith(agents_md.TRUNCATED_NOTE)
assert len(text) == agents_md.MAX_AGENTS_MD_BYTES + len(agents_md.TRUNCATED_NOTE)
def test_managed_account_reads_its_workspace_never_the_host(home, monkeypatch):
_write(home / "proj/AGENTS.md", "Host project rules")
monkeypatch.setattr(agents_md, "is_owner_context", lambda: False)
monkeypatch.setattr(agents_md, "workspace_root", lambda: home / "account")
(home / "account").mkdir()
assert agents_md.agents_md_text(_project(home)) == ""
_write(home / "account/AGENTS.md", "Account rules")
text = agents_md.agents_md_text(_project(home))
assert text.endswith("Account rules") and "Host" not in text
def test_archived_project_and_kill_switch(home, monkeypatch):
_write(home / "home/.unsloth/studio/AGENTS.md", "Be brief.")
_write(home / "proj/AGENTS.md", "Use pnpm.")
assert "pnpm" not in agents_md.agents_md_text(_project(home, archived = True))
for off in ("0", "false", "no", "off"):
monkeypatch.setenv("UNSLOTH_STUDIO_AGENTS_MD", off)
assert agents_md.agents_md_text(_project(home)) == ""
def test_route_returns_the_text(home, monkeypatch):
_write(home / "proj/AGENTS.md", "Use pnpm.")
project = _project(home)
monkeypatch.setattr(
chat_history, "get_chat_project", lambda pid: project if pid == "p1" else None
)
assert chat_history.get_agents_md("p1", current_subject = "owner").text.endswith("Use pnpm.")
assert chat_history.get_agents_md(None, current_subject = "owner").text == ""
assert chat_history.get_agents_md("missing", current_subject = "owner").text == ""
def test_sandbox_hard_link_and_fifo_are_not_read(home):
root = home / "p"
sandbox = root / "sandbox"
sandbox.mkdir(parents = True)
project = {"rootPath": str(root), "sandboxPath": str(sandbox), "archived": False}
secret = home / "secret.txt"
secret.write_text("host secret", encoding = "utf-8")
os.link(secret, sandbox / "AGENTS.md")
assert "host secret" not in agents_md.agents_md_text(project)
if hasattr(os, "mkfifo"):
(sandbox / "AGENTS.md").unlink()
os.mkfifo(sandbox / "AGENTS.md")
assert agents_md.agents_md_text(project) == ""
@pytest.mark.skipif(
sys.platform == "win32", reason = "symlinks need admin or developer mode on Windows"
)
def test_sandbox_outside_the_project_is_not_read(home):
# Same layout tools._get_project_workdir refuses: sandbox linked out of the project folder.
(home / "host/elsewhere").mkdir()
_write(home / "host/elsewhere/AGENTS.md", "outside rules")
root = home / "linked"
root.mkdir()
os.symlink(home / "host/elsewhere", root / "sandbox")
project = {"rootPath": str(root), "sandboxPath": str(root / "sandbox"), "archived": False}
assert agents_md.agents_md_text(project) == ""
def test_memory_save_is_idempotent_and_empty_removes_the_file(home):
path = home / "home/.unsloth/studio/AGENTS.md"
assert agents_md.read_memory() == ""
assert agents_md.write_memory(" I use uv.\r\nReply in British English.\n\n") == (
"I use uv.\nReply in British English.\n"
)
first = path.read_bytes()
agents_md.write_memory(agents_md.read_memory())
assert path.read_bytes() == first
assert agents_md.agents_md_text(None).endswith("I use uv.\nReply in British English.")
assert agents_md.write_memory(" ") == ""
assert not path.exists()
agents_md.write_memory("")
assert not path.exists()
assert not list(path.parent.glob(".AGENTS.md.*"))
def test_memory_refuses_oversize_text_and_a_linked_file(home):
path = home / "home/.unsloth/studio/AGENTS.md"
with pytest.raises(ValueError, match = "32 KiB"):
agents_md.write_memory("x" * agents_md.MAX_AGENTS_MD_BYTES)
assert not path.exists()
if not hasattr(os, "symlink"):
return
target = home / "host/notes.md"
_write(target, "kept")
try:
os.symlink(target, path)
except OSError:
pytest.skip(
reason = "Windows without Developer Mode refuses os.symlink; the link refusal needs a real link"
)
assert agents_md.read_memory() == "kept"
with pytest.raises(ValueError, match = "link"):
agents_md.write_memory("new")
assert target.read_text(encoding = "utf-8") == "kept"
def test_memory_switch_drops_only_the_global_file(home):
_write(home / "home/.unsloth/studio/AGENTS.md", "Be brief.")
_write(home / "proj/AGENTS.md", "Use pnpm.")
assert agents_md.memory_enabled() is True
assert agents_md.set_memory_enabled(False) is False
assert agents_md.agents_md_text(None) == ""
assert agents_md.agents_md_text(_project(home)) == (
f"# Source: {(home / 'proj/AGENTS.md').as_posix()}\n\nUse pnpm."
)
agents_md.set_memory_enabled(True)
assert agents_md.agents_md_text(None).endswith("Be brief.")
with pytest.raises(ValueError):
agents_md.set_memory_enabled("off")
def test_memory_route_reads_writes_and_needs_a_ui_session(home):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from routes import settings
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "owner"
via_key = {"value": False}
app.dependency_overrides[settings.authenticated_via_api_key] = lambda: via_key["value"]
client = TestClient(app, raise_server_exceptions = False)
body = client.get("/chat-memory").json()
assert body == {
"enabled": True,
"text": "",
"path": "~/.unsloth/studio/AGENTS.md",
"max_bytes": agents_md.MAX_AGENTS_MD_BYTES,
"locked_by_environment": False,
}
saved = client.put("/chat-memory", json = {"text": "I use uv.", "enabled": False}).json()
assert saved["text"] == "I use uv.\n" and saved["enabled"] is False
assert client.put("/chat-memory", json = {"enabled": True}).json()["text"] == "I use uv.\n"
too_big = client.put("/chat-memory", json = {"text": "x" * agents_md.MAX_AGENTS_MD_BYTES})
assert too_big.status_code == 400 and "32 KiB" in too_big.json()["detail"]
assert client.put("/chat-memory", json = {"enabled": "no"}).status_code == 422
via_key["value"] = True
assert client.put("/chat-memory", json = {"text": "planted"}).status_code == 403
assert agents_md.read_memory() == "I use uv.\n"
def test_memory_editor_loads_a_hand_edited_file_whole_and_fails_closed(home, monkeypatch):
big = "note\n" * (agents_md.MAX_AGENTS_MD_BYTES // 5 + 100)
target = home / "home/.unsloth/studio/AGENTS.md"
target.parent.mkdir(parents = True, exist_ok = True)
# Bytes, not write_text: Windows text mode writes CRLF, and read_memory returns the file as it is.
target.write_bytes(big.encode("utf-8"))
# Chats still get the 32 KiB cut; the editor gets everything, so a save cannot drop the tail unseen.
assert agents_md.agents_md_text(None).endswith(agents_md.TRUNCATED_NOTE)
assert agents_md.read_memory() == big
import storage.studio_db as studio_db
def broken(*_args, **_kwargs):
raise OSError("database is unreadable")
monkeypatch.setattr(studio_db, "get_app_setting", broken)
assert agents_md.memory_enabled() is False
assert agents_md.agents_md_text(None) == ""
def test_memory_save_refuses_to_recreate_a_retired_workspace(home, monkeypatch):
from utils.paths import storage_roots
def retired(path):
raise storage_roots.RetiredAccountError(f"refusing to recreate {path}")
monkeypatch.setattr(agents_md, "ensure_dir", retired)
with pytest.raises(storage_roots.RetiredAccountError):
agents_md.write_memory("late save")
assert not (home / "home/.unsloth/studio/AGENTS.md").exists()