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: view, edit and turn off chat memory in Settings > Chat (#14357)
Daniel Handd5d02ed62e6
diff --git a/studio/backend/core/agents_md.py b/studio/backend/core/agents_md.pyindex 3dafb936b3f..4ed06edae21 100644--- a/studio/backend/core/agents_md.py+++ b/studio/backend/core/agents_md.py@@ -7,16 +7,20 @@ from __future__ import annotationsimport osimport stat+import tempfilefrom pathlib import Path-from typing import Optional+from typing import Any, Optionalfrom utils.account_context import is_owner_context-from utils.paths import workspace_root+from utils.paths import ensure_dir, workspace_root# Codex's project_doc_max_bytes default, for the global and project text together.MAX_AGENTS_MD_BYTES = 32 * 1024TRUNCATED_NOTE = "\n[AGENTS.md truncated at 32 KiB]"_DISABLE_ENV = "UNSLOTH_STUDIO_AGENTS_MD"+MEMORY_ENABLED_KEY = "chat_memory_enabled"+# The editor loads the whole file, not the chat's 32 KiB cut: saving a prefix would drop the rest.+MAX_MEMORY_EDIT_BYTES = 1024 * 1024def agents_md_enabled() -> bool:@@ -27,7 +31,11 @@ def _owner_home() -> Path:return Path.home()-def _read(path: Path, confine: Optional[Path] = None) -> bytes:+def _read(+ path: Path,+ confine: Optional[Path] = None,+ limit: int = MAX_AGENTS_MD_BYTES,+) -> bytes:# The model writes in the sandbox but this read is unsandboxed: no link there may pull in a host file# (project and global files may be links, CLAUDE.md -> AGENTS.md). Non-blocking so a FIFO cannot hang.flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)@@ -48,7 +56,7 @@ def _read(path: Path, confine: Optional[Path] = None) -> bytes:if not stat.S_ISREG(status.st_mode) or (confine is not None and status.st_nlink > 1):return b""# One byte over the cap is enough to know it was cut.- return handle.read(MAX_AGENTS_MD_BYTES + 1)+ return handle.read(limit + 1)except OSError:return b""@@ -71,9 +79,64 @@ def _label(path: Path) -> str:return text.replace(os.sep, "/")+def global_agents_md_path() -> Path:+ return workspace_root() / "AGENTS.md"+++def memory_enabled() -> bool:+ try:+ from storage.studio_db import get_app_setting+ stored = get_app_setting(MEMORY_ENABLED_KEY, True)+ except Exception:+ # Fail closed: an unreadable opt-out must not send notes the user turned off.+ return False+ return stored is not False+++def set_memory_enabled(value: Any) -> bool:+ if not isinstance(value, bool):+ raise ValueError("Memory must be turned on or off.")+ from storage.studio_db import upsert_app_settings++ upsert_app_settings({MEMORY_ENABLED_KEY: value}, read_back = False)+ return value+++def read_memory() -> str:+ raw = _read(global_agents_md_path(), limit = MAX_MEMORY_EDIT_BYTES)[:MAX_MEMORY_EDIT_BYTES]+ return raw.decode("utf-8", errors = "ignore")+++def write_memory(text: str) -> str:+ """Replace the global file with ``text``; empty text removes it. Saving the same text twice is a no-op."""+ body = text.replace("\r\n", "\n").strip()+ data = (body + "\n").encode("utf-8") if body else b""+ if len(data) > MAX_AGENTS_MD_BYTES:+ raise ValueError("Memory is limited to 32 KiB.")+ path = global_agents_md_path()+ # Replacing a link would cut it from the file the user keeps elsewhere.+ if path.is_symlink():+ raise ValueError(f"{_label(path)} is a link; edit the file it points to instead.")+ if not data:+ path.unlink(missing_ok = True)+ return ""+ # Retirement-aware: a late save must not recreate a deleted account's workspace.+ ensure_dir(path.parent)+ # Atomic, so a chat sending meanwhile reads the old notes or the new ones, never half of them.+ fd, tmp = tempfile.mkstemp(dir = path.parent, prefix = ".AGENTS.md.", suffix = ".tmp")+ try:+ with os.fdopen(fd, "wb") as handle:+ handle.write(data)+ os.replace(tmp, path)+ except BaseException:+ Path(tmp).unlink(missing_ok = True)+ raise+ return data.decode("utf-8")++def _sources(project: Optional[dict]) -> list[tuple[tuple[Path, ...], Optional[Path]]]:# Studio's own file for every account: another tool's ~/.claude or ~/.codex rules would change existing chats.- sources = [((workspace_root() / "AGENTS.md",), None)]+ sources = [((global_agents_md_path(),), None)] if memory_enabled() else []# Host project folders are single-user only (see tools._get_project_workdir).if (not projectdiff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex a05d70b05dd..89fa48efaf1 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -4113,6 +4113,20 @@ class CurrentDatePromptResponse(BaseModel):default_enabled: bool = DEFAULT_CURRENT_DATE_PROMPT_ENABLED+class ChatMemoryPayload(BaseModel):+ enabled: Optional[StrictBool] = None+ text: Optional[StrictStr] = None+++class ChatMemoryResponse(BaseModel):+ enabled: bool+ text: str+ path: str+ max_bytes: int+ # UNSLOTH_STUDIO_AGENTS_MD=0 keeps every AGENTS.md out of chats, whatever the switch says.+ locked_by_environment: bool++class RemoteAccessAutoStartPayload(BaseModel):enabled: StrictBool@@ -4451,6 +4465,56 @@ def update_current_date_prompt(return CurrentDatePromptResponse(enabled = enabled)+def _chat_memory_response() -> ChatMemoryResponse:+ from core import agents_md+ return ChatMemoryResponse(+ enabled = agents_md.memory_enabled(),+ text = agents_md.read_memory(),+ path = agents_md._label(agents_md.global_agents_md_path()),+ max_bytes = agents_md.MAX_AGENTS_MD_BYTES,+ locked_by_environment = not agents_md.agents_md_enabled(),+ )+++@_account_settings_router.get("/chat-memory", response_model = ChatMemoryResponse)+def get_chat_memory(current_subject: str = Depends(get_current_subject)) -> ChatMemoryResponse:+ return _chat_memory_response()+++@_account_settings_router.put("/chat-memory", response_model = ChatMemoryResponse)+def update_chat_memory(+ payload: ChatMemoryPayload,+ current_subject: str = Depends(get_current_subject),+ # Text here reaches every chat's system prompt: a remote key must not be able to plant it.+ _ui_session: None = Depends(_require_ui_session),+) -> ChatMemoryResponse:+ """Edit the notes every chat reads (the account's global AGENTS.md) and whether chats read them."""+ from core import agents_md+ from utils.paths.storage_roots import RetiredAccountError++ try:+ if payload.text is not None:+ agents_md.write_memory(payload.text)+ if payload.enabled is not None:+ agents_md.set_memory_enabled(payload.enabled)+ except (ValueError, OSError, RetiredAccountError) as exc:+ raise log_and_http_error(+ exc,+ 400 if isinstance(exc, ValueError) else 500,+ # Our own ValueError messages name what to change; the rest may carry a host path.+ str(exc) if isinstance(exc, ValueError) else "Could not save memory.",+ event = "settings.update_chat_memory_failed",+ log = logger,+ ) from exc+ logger.info(+ "settings.chat_memory_updated subject=%s text=%s enabled=%s",+ current_subject,+ payload.text is not None,+ payload.enabled,+ )+ return _chat_memory_response()++def _require_ui_session_for_keyless(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:"""Only a signed-in UI session may change who needs a key. An sk-unsloth key must not be able to switchauthentication off for the whole install, and a keyless caller must not be able to widen its own scope;diff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.pyindex 64999ceb73d..81314707451 100644--- a/studio/backend/tests/test_account_chat_settings.py+++ b/studio/backend/tests/test_account_chat_settings.py@@ -406,6 +406,7 @@ def test_every_owner_setting_rejects_managed_accounts(client, method, path):("/personalization", {"profile": {"displayName": "Alice"}}),("/chat-preferences", {"show_model_disclaimer": True}),("/current-date-prompt", {"enabled": False}),+ ("/chat-memory", {"enabled": False}),],)def test_personal_settings_do_not_change_owner_rows(client, path, body):@@ -754,3 +755,20 @@ def test_research_cleanup_reaches_the_account_keyed_supervisor():bob_event = run_as(BOB, supervisor._cancel_event, "same")run_as(ALICE, chat_history._cancel_research_runs, request, ["same"])assert alice_event.is_set() and not bob_event.is_set()+++def test_chat_memory_is_per_account(client):+ from utils.paths import studio_root++ saved = client.put("/settings/chat-memory", json = {"text": "Alice uses uv.", "enabled": False})+ assert saved.status_code == 200, saved.text+ assert (studio_root() / "accounts" / ALICE.account_id / "AGENTS.md").read_text(+ encoding = "utf-8"+ ) == "Alice uses uv.\n"+ assert not (studio_root() / "AGENTS.md").exists()+ owner = client.get("/settings/chat-memory", headers = {"x-test-account": OWNER.username}).json()+ assert owner["text"] == "" and owner["enabled"] is True+ bob = client.get("/settings/chat-memory", headers = {"x-test-account": "bob"}).json()+ assert bob["text"] == "" and bob["enabled"] is True+ alice = client.get("/settings/chat-memory").json()+ assert alice["text"] == "Alice uses uv.\n" and alice["enabled"] is Falsediff --git a/studio/backend/tests/test_agents_md.py b/studio/backend/tests/test_agents_md.pyindex 9130e8ec732..cb33401b0fd 100644--- a/studio/backend/tests/test_agents_md.py+++ b/studio/backend/tests/test_agents_md.py@@ -154,3 +154,121 @@ def test_sandbox_outside_the_project_is_not_read(home):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()diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex e66a13b2c72..3c00de86658 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -342,8 +342,11 @@ export const BUDGET = {// (6,862,706 -> 6,863,047 B raw, 2,066,422 -> 2,066,532 B transfer against 2aeeceb07e, one machine and build,// 96 chunks). Raised by that.// Floating panels remembering their dropped spot (#14355) add 701 B raw / 211 B transfer. Raised by that.- transferBytes: 2_071_210,- rawBytes: 6_877_790,+ // The Settings > Chat memory editor (#14357) keeps its strings in the eager English locale and the AGENTS.md+ // cache counter in the chat adapter (the section itself is lazy): +989 B raw / +364 B transfer over main+ // (6,863,532 -> 6,864,521 B raw, 2,066,692 -> 2,067,056 B transfer at e08466e82, 97 chunks). Raised by that.+ transferBytes: 2_071_574,+ rawBytes: 6_878_779,};// 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/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex dcefe04d93a..55bfaa6721b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -415,6 +415,7 @@ import {} from "./chat-api";import {type AgentsMdRecord,+ agentsMdEditCount,composeChatInstructions,EMPTY_AGENTS_MD,} from "../utils/agents-md";@@ -2471,19 +2472,20 @@ async function resolveProjectInstructions(projectId: string | null): Promise<strconst AGENTS_MD_TTL_MS = 2_000;const agentsMdByProject = new Map<string,- { at: number; value: Promise<AgentsMdRecord> }+ { at: number; edits: number; value: Promise<AgentsMdRecord> }>();/** The AGENTS.md text for a request; a failed read sends what it would without the file. */function resolveAgentsMd(projectId: string | null): Promise<AgentsMdRecord> {const key = projectId ?? "";const now = Date.now();+ const edits = agentsMdEditCount();const hit = agentsMdByProject.get(key);- if (hit && now - hit.at < AGENTS_MD_TTL_MS) {+ if (hit && hit.edits === edits && now - hit.at < AGENTS_MD_TTL_MS) {return hit.value;}const value = getChatAgentsMd(projectId).catch(() => EMPTY_AGENTS_MD);- agentsMdByProject.set(key, { at: now, value });+ agentsMdByProject.set(key, { at: now, edits, value });return value;}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 20e9a911125..51e3f3c8d22 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -67,6 +67,8 @@ export {} from "./stores/chat-runtime-store";export { openFolderAsProject, useOpeningFolder } from "./utils/open-folder-as-project";export { requestReplyFinishedPermission } from "./utils/reply-finished-notification";+export { forgetAgentsMd } from "./utils/agents-md";+export { refreshContextUsage } from "./utils/refresh-context-usage";export {hydrateModelDisclaimerPreference,refreshModelDisclaimerPreference,diff --git a/studio/frontend/src/features/chat/utils/agents-md.ts b/studio/frontend/src/features/chat/utils/agents-md.tsindex bc4e4ce0bc4..47112b28602 100644--- a/studio/frontend/src/features/chat/utils/agents-md.ts+++ b/studio/frontend/src/features/chat/utils/agents-md.ts@@ -5,6 +5,17 @@ export type AgentsMdRecord = { text: string };export const EMPTY_AGENTS_MD: AgentsMdRecord = { text: "" };+let agentsMdEdits = 0;++/** Bumped when Settings saves memory, so a cached read from before the save is not sent. */+export function forgetAgentsMd(): void {+ agentsMdEdits += 1;+}++export function agentsMdEditCount(): number {+ return agentsMdEdits;+}+/** System prompt for one request. AGENTS.md first, so project instructions and the typed system prompt* have the last word; with no AGENTS.md this is byte-identical to the prompt before AGENTS.md support. */export function composeChatInstructions(parts: {diff --git a/studio/frontend/src/features/settings/api/chat-memory.ts b/studio/frontend/src/features/settings/api/chat-memory.tsnew file mode 100644index 00000000000..2063398aa27--- /dev/null+++ b/studio/frontend/src/features/settings/api/chat-memory.ts@@ -0,0 +1,58 @@+// 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 { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++export type ChatMemorySettings = {+ enabled: boolean;+ text: string;+ path: string;+ maxBytes: number;+ lockedByEnvironment: boolean;+};++type ApiChatMemorySettings = {+ enabled: boolean;+ text: string;+ path: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ max_bytes: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ locked_by_environment: boolean;+};++function fromApi(settings: ApiChatMemorySettings): ChatMemorySettings {+ return {+ enabled: settings.enabled,+ text: settings.text,+ path: settings.path,+ maxBytes: settings.max_bytes,+ lockedByEnvironment: settings.locked_by_environment,+ };+}++export async function loadChatMemory(+ fallbackMessage: string,+): Promise<ChatMemorySettings> {+ const res = await authFetch("/api/settings/chat-memory");+ if (!res.ok) {+ throw new Error(await readFastApiError(res, fallbackMessage));+ }+ return fromApi(await res.json());+}++export async function updateChatMemory(+ patch: { enabled?: boolean; text?: string },+ fallbackMessage: string,+): Promise<ChatMemorySettings> {+ const res = await authFetch("/api/settings/chat-memory", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (!res.ok) {+ throw new Error(await readFastApiError(res, fallbackMessage));+ }+ return fromApi(await res.json());+}diff --git a/studio/frontend/src/features/settings/components/chat-memory-section.tsx b/studio/frontend/src/features/settings/components/chat-memory-section.tsxnew file mode 100644index 00000000000..7c2c87648ad--- /dev/null+++ b/studio/frontend/src/features/settings/components/chat-memory-section.tsx@@ -0,0 +1,165 @@+// 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 { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { forgetAgentsMd, refreshContextUsage } from "@/features/chat";+import { useT } from "@/i18n";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import { useEffect, useId, useState } from "react";+import {+ type ChatMemorySettings,+ loadChatMemory,+ updateChatMemory,+} from "../api/chat-memory";+import { chatMemoryBytes, normaliseChatMemory } from "../lib/chat-memory-size";+import { SettingsRow } from "./settings-row";+import { SettingsSection } from "./settings-section";++export function ChatMemorySection() {+ const t = useT();+ const editorId = useId();+ const [settings, setSettings] = useState<ChatMemorySettings | null>(null);+ const [draft, setDraft] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ let cancelled = false;+ void loadChatMemory(t("settings.chat.memory.loadError"))+ .then((loaded) => {+ if (cancelled) return;+ setSettings(loaded);+ setDraft(loaded.text);+ setError(null);+ })+ .catch((loadError) => {+ if (cancelled) return;+ setError(+ loadError instanceof Error+ ? loadError.message+ : t("settings.chat.memory.loadError"),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [t]);++ const save = async (patch: { enabled?: boolean; text?: string }) => {+ setSaving(true);+ setError(null);+ try {+ const saved = await updateChatMemory(+ patch,+ t("settings.chat.memory.saveError"),+ );+ setSettings(saved);+ const submitted = patch.text;+ if (submitted !== undefined) {+ // Keep anything typed while the save was in flight.+ setDraft((current) =>+ normaliseChatMemory(current) === normaliseChatMemory(submitted)+ ? saved.text+ : current,+ );+ toast.success(t("settings.chat.memory.saved"));+ }+ forgetAgentsMd();+ void refreshContextUsage({ invalidate: true });+ } catch (saveError) {+ setError(+ saveError instanceof Error+ ? saveError.message+ : t("settings.chat.memory.saveError"),+ );+ } finally {+ setSaving(false);+ }+ };++ const bytes = chatMemoryBytes(draft);+ const maxBytes = settings?.maxBytes ?? 32 * 1024;+ const tooLarge = bytes > maxBytes;+ const dirty =+ settings !== null &&+ normaliseChatMemory(draft) !== normaliseChatMemory(settings.text);++ return (+ <SettingsSection+ title={t("settings.chat.memory.title")}+ description={t("settings.chat.memory.description")}+ >+ <SettingsRow+ label={t("settings.chat.memory.enable")}+ description={+ settings?.lockedByEnvironment+ ? t("settings.chat.memory.locked")+ : t("settings.chat.memory.enableDescription")+ }+ >+ <Switch+ aria-label={t("settings.chat.memory.enable")}+ checked={+ (settings?.enabled ?? false) && !settings?.lockedByEnvironment+ }+ disabled={!settings || saving || settings.lockedByEnvironment}+ onCheckedChange={(enabled) => void save({ enabled })}+ />+ </SettingsRow>+ <div className="flex flex-col gap-2 pb-3">+ <label htmlFor={editorId} className="sr-only">+ {t("settings.chat.memory.editor")}+ </label>+ <Textarea+ id={editorId}+ fieldSizing="fixed"+ rows={6}+ className="max-h-[calc(320px*var(--ui-space-scale,1))] resize-y font-mono text-xs md:text-xs"+ placeholder={t("settings.chat.memory.placeholder")}+ value={draft}+ disabled={!settings}+ aria-invalid={tooLarge || undefined}+ onChange={(event) => setDraft(event.target.value)}+ />+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">+ <span className="min-w-0 text-xs text-muted-foreground">+ {settings+ ? t("settings.chat.memory.hint", { path: settings.path })+ : null}+ </span>+ <div className="flex items-center gap-3">+ <span+ className={cn(+ "text-xs tabular-nums",+ tooLarge ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {t("settings.chat.memory.size", {+ used: (bytes / 1024).toLocaleString(undefined, {+ maximumFractionDigits: 1,+ }),+ max: Math.round(maxBytes / 1024).toLocaleString(),+ })}+ </span>+ <Button+ variant="outline"+ className="px-3.5"+ disabled={!dirty || tooLarge || saving}+ onClick={() => void save({ text: draft })}+ >+ {t("settings.chat.memory.save")}+ </Button>+ </div>+ </div>+ {error ? (+ <span role="alert" className="text-right text-xs text-destructive">+ {error}+ </span>+ ) : null}+ </div>+ </SettingsSection>+ );+}diff --git a/studio/frontend/src/features/settings/lib/chat-memory-size.ts b/studio/frontend/src/features/settings/lib/chat-memory-size.tsnew file mode 100644index 00000000000..72a0819b03c--- /dev/null+++ b/studio/frontend/src/features/settings/lib/chat-memory-size.ts@@ -0,0 +1,12 @@+// 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 function normaliseChatMemory(text: string): string {+ return text.replace(/\r\n/g, "\n").trim();+}++/** UTF-8 size as the backend saves it, so the editor refuses what the save would. */+export function chatMemoryBytes(text: string): number {+ const body = normaliseChatMemory(text);+ return body ? new TextEncoder().encode(`${body}\n`).length : 0;+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 490422314f8..114ca816d13 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -128,6 +128,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.chat.modelSelection.title","settings.chat.modelSelection.fitOnDeviceOnly","settings.chat.currentDate.label",+ "settings.chat.memory.title",+ "settings.chat.memory.enable","settings.general.autoTitleNewChats","settings.chat.projectAttachments","settings.chat.rememberParamsPerModel",@@ -453,6 +455,8 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<"settings.resources.modelMemory.mediaIdleUnloadKeywords","settings.general.modelAutoSwitch.keepKv":"settings.general.modelAutoSwitch.keepKvKeywords",+ "settings.chat.memory.title": "settings.chat.memory.keywords",+ "settings.chat.memory.enable": "settings.chat.memory.keywords","settings.chat.autoCompact": "settings.chat.autoCompactKeywords","settings.chat.keepRunningWhenTabClosed":"settings.chat.keepRunningWhenTabClosedKeywords",diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex a5a0cf137c1..8c78b9e30e1 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -1,6 +1,7 @@// 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 { LazyImportBoundary } from "@/components/lazy-import-boundary";import { SegmentedPill } from "@/components/segmented-control";import { Button } from "@/components/ui/button";import {@@ -45,7 +46,7 @@ import { HugeiconsIcon } from "@hugeicons/react";import { CursorInWindowIcon } from "@/lib/browser-use-icon";import { useNavigate } from "@tanstack/react-router";import { Columns2Icon } from "lucide-react";-import { useEffect, useId, useState } from "react";+import { Suspense, lazy, useEffect, useId, useState } from "react";import type { ReactNode } from "react";import {type CurrentDatePromptSettings,@@ -65,6 +66,13 @@ import { ComposerSettings } from "../components/composer-settings";import { SettingsSection } from "../components/settings-section";import { useSettingsDialogStore } from "../stores/settings-dialog-store";+// Off the startup bundle: the settings chunk loads eagerly, this section only when the Chat tab opens.+const ChatMemorySection = lazy(() =>+ import("../components/chat-memory-section").then((module) => ({+ default: module.ChatMemorySection,+ })),+);+// Adjustable "+" menu items shown in settings; the list shows them in the user's order. Icons mirror// the ones used in the composer + menu itself.const PLUS_MENU_ICON_CLASS = "size-[calc(18px*var(--ui-space-scale,1))]";@@ -671,6 +679,12 @@ export function ChatTab() {</SettingsRow></SettingsSection>+ <LazyImportBoundary fallback={null}>+ <Suspense fallback={null}>+ <ChatMemorySection />+ </Suspense>+ </LazyImportBoundary>+<SettingsSection title={t("settings.chat.groups.display.title")}><SettingsRowlabel={t("settings.chat.webSearch.images")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex c55342f5eb9..9815300a83f 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2763,6 +2763,22 @@ export const ar = {visibilityDescription:"كيفية فتح التفكير. لا يزال بإمكانك توسيع أو طي أي كتلة بنفسك.",},+ memory: {+ title: "الذاكرة",+ description: "ملاحظات تقرؤها كل محادثة، مع أي نموذج، محليًا أو سحابيًا. تقرأ محادثات المشروع أيضًا ملف AGENTS.md الخاص به.",+ enable: "استخدام الذاكرة في المحادثات",+ enableDescription: "إرسال هذه الملاحظات مع كل محادثة.",+ locked: "معطّلة في هذا التثبيت بواسطة UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "ملاحظات الذاكرة",+ placeholder: "مثال:\n- أكتب بلغة Python وأستخدم uv.\n- اجعل الإجابات قصيرة.",+ hint: "تُحفظ في {path}. يمكنك أيضًا تعديل هذا الملف في أي محرر نصوص.",+ size: "{used} / {max} كيلوبايت",+ save: "حفظ",+ saved: "تم حفظ الذاكرة",+ loadError: "تعذّر تحميل الذاكرة.",+ saveError: "تعذّر حفظ الذاكرة.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md الذاكرة تذكر تخصيص ملف شخصي ملاحظات",+ },currentDate: {label: "إخبار النموذج بتاريخ اليوم",description:diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 1104036f29b..e84f8947ab3 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2804,6 +2804,22 @@ export const de = {visibilityDescription:"Wie das Denken geöffnet wird. Einzelne Blöcke lassen sich weiterhin selbst aus- und einklappen.",},+ memory: {+ title: "Gedächtnis",+ description: "Notizen, die jeder Chat liest, für jedes Modell, lokal oder in der Cloud. Chats in einem Projekt lesen zusätzlich dessen AGENTS.md.",+ enable: "Gedächtnis in Chats verwenden",+ enableDescription: "Diese Notizen mit jedem Chat senden.",+ locked: "Für diese Installation durch UNSLOTH_STUDIO_AGENTS_MD deaktiviert.",+ editor: "Gedächtnisnotizen",+ placeholder: "Zum Beispiel:\n- Ich schreibe Python und nutze uv.\n- Antworte kurz.",+ hint: "Gespeichert in {path}. Du kannst diese Datei auch in jedem Texteditor bearbeiten.",+ size: "{used} / {max} KB",+ save: "Speichern",+ saved: "Gedächtnis gespeichert",+ loadError: "Gedächtnis konnte nicht geladen werden.",+ saveError: "Gedächtnis konnte nicht gespeichert werden.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md gedächtnis erinnern merken personalisierung profil notizen",+ },currentDate: {label: "Dem Modell das heutige Datum mitteilen",description:diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 9c03cb646e0..b1e587333d9 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2822,6 +2822,22 @@ export const en = {visibilityDescription:"How reasoning opens. You can still expand or collapse any block yourself.",},+ memory: {+ title: "Memory",+ description: "Notes every chat reads, for every model, local or cloud. Chats in a project also read that project's AGENTS.md.",+ enable: "Use memory in chats",+ enableDescription: "Send these notes with every chat.",+ locked: "Turned off for this install by UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Memory notes",+ placeholder: "For example:\n- I write Python and use uv.\n- Keep answers short.",+ hint: "Saved to {path}. You can also edit that file in any text editor.",+ size: "{used} / {max} KB",+ save: "Save",+ saved: "Memory saved",+ loadError: "Failed to load memory.",+ saveError: "Failed to save memory.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md",+ },currentDate: {label: "Tell the model today's date",description:diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 8c6be3caa31..87a07482903 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2795,6 +2795,22 @@ export const es = {visibilityDescription:"Cómo se abre el razonamiento. Puedes expandir o contraer cualquier bloque por tu cuenta.",},+ memory: {+ title: "Memoria",+ description: "Notas que lee cada chat, con cualquier modelo, local o en la nube. Los chats de un proyecto también leen el AGENTS.md de ese proyecto.",+ enable: "Usar memoria en los chats",+ enableDescription: "Enviar estas notas con cada chat.",+ locked: "Desactivado en esta instalación por UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Notas de memoria",+ placeholder: "Por ejemplo:\n- Escribo Python y uso uv.\n- Responde de forma breve.",+ hint: "Se guarda en {path}. También puedes editar ese archivo con cualquier editor de texto.",+ size: "{used} / {max} KB",+ save: "Guardar",+ saved: "Memoria guardada",+ loadError: "No se pudo cargar la memoria.",+ saveError: "No se pudo guardar la memoria.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md memoria recordar personalización perfil notas",+ },currentDate: {label: "Indicar al modelo la fecha de hoy",description:diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex d186f4a531d..dd8bd3ed65a 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2801,6 +2801,22 @@ export const fr = {visibilityDescription:"Comment la réflexion s’ouvre. Vous pouvez toujours déplier ou replier un bloc vous-même.",},+ memory: {+ title: "Mémoire",+ description: "Des notes lues par chaque discussion, avec n'importe quel modèle, local ou cloud. Les discussions d'un projet lisent aussi le AGENTS.md de ce projet.",+ enable: "Utiliser la mémoire dans les discussions",+ enableDescription: "Envoyer ces notes avec chaque discussion.",+ locked: "Désactivé pour cette installation par UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Notes de mémoire",+ placeholder: "Par exemple :\n- J'écris du Python et j'utilise uv.\n- Réponds brièvement.",+ hint: "Enregistré dans {path}. Vous pouvez aussi modifier ce fichier dans n'importe quel éditeur de texte.",+ size: "{used} / {max} Ko",+ save: "Enregistrer",+ saved: "Mémoire enregistrée",+ loadError: "Impossible de charger la mémoire.",+ saveError: "Impossible d'enregistrer la mémoire.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md mémoire souvenir personnalisation profil notes",+ },currentDate: {label: "Indiquer la date du jour au modèle",description:diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 72b7632510a..5d11ebe876b 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -2880,6 +2880,22 @@ export const he = {visibilityDescription:"כיצד תהליך החשיבה נפתח. עדיין תוכל להרחיב או לכווץ כל מקטע בעצמך.",},+ memory: {+ title: "זיכרון",+ description: "הערות שכל צ'אט קורא, בכל מודל, מקומי או בענן. צ'אטים בפרויקט קוראים גם את קובץ AGENTS.md של הפרויקט.",+ enable: "שימוש בזיכרון בצ'אטים",+ enableDescription: "שליחת ההערות האלה עם כל צ'אט.",+ locked: "כבוי בהתקנה זו על ידי UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "הערות זיכרון",+ placeholder: "לדוגמה:\n- אני כותב ב-Python ומשתמש ב-uv.\n- תשובות קצרות.",+ hint: "נשמר ב-{path}. אפשר גם לערוך את הקובץ בכל עורך טקסט.",+ size: "{used} / {max} KB",+ save: "שמירה",+ saved: "הזיכרון נשמר",+ loadError: "טעינת הזיכרון נכשלה.",+ saveError: "שמירת הזיכרון נכשלה.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md זיכרון לזכור התאמה אישית פרופיל הערות",+ },currentDate: {label: "ספק למודל את התאריך של היום",description:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex a7e14b0f788..e1d157bfa24 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2772,6 +2772,22 @@ export const hi = {visibilityDescription:"रीज़निंग कैसे खुलती है। आप किसी भी ब्लॉक को खुद विस्तृत या संक्षिप्त कर सकते हैं।",},+ memory: {+ title: "मेमोरी",+ description: "ऐसे नोट्स जिन्हें हर चैट पढ़ती है, हर मॉडल के लिए, लोकल या क्लाउड। किसी प्रोजेक्ट की चैट उस प्रोजेक्ट की AGENTS.md भी पढ़ती हैं।",+ enable: "चैट में मेमोरी का उपयोग करें",+ enableDescription: "ये नोट्स हर चैट के साथ भेजें।",+ locked: "UNSLOTH_STUDIO_AGENTS_MD ने इस इंस्टॉल के लिए इसे बंद कर दिया है।",+ editor: "मेमोरी नोट्स",+ placeholder: "उदाहरण:\n- मैं Python लिखता हूँ और uv का उपयोग करता हूँ।\n- जवाब छोटे रखें।",+ hint: "{path} में सेव होता है। आप इस फ़ाइल को किसी भी टेक्स्ट एडिटर में भी बदल सकते हैं।",+ size: "{used} / {max} KB",+ save: "सेव करें",+ saved: "मेमोरी सेव हो गई",+ loadError: "मेमोरी लोड नहीं हो सकी।",+ saveError: "मेमोरी सेव नहीं हो सकी।",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md मेमोरी याद पर्सनलाइज़ेशन प्रोफ़ाइल नोट्स",+ },currentDate: {label: "मॉडल को आज की तारीख बताएँ",description:diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 4f528c93292..47a39598bc7 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2709,6 +2709,22 @@ export const it = {visibilityDescription:"Come si apre il ragionamento. Puoi comunque espandere o comprimere ogni blocco a mano.",},+ memory: {+ title: "Memoria",+ description: "Note lette da ogni chat, con qualsiasi modello, locale o cloud. Le chat di un progetto leggono anche l'AGENTS.md del progetto.",+ enable: "Usa la memoria nelle chat",+ enableDescription: "Invia queste note con ogni chat.",+ locked: "Disattivata per questa installazione da UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Note di memoria",+ placeholder: "Per esempio:\n- Scrivo in Python e uso uv.\n- Rispondi in modo breve.",+ hint: "Salvato in {path}. Puoi modificare quel file anche con qualsiasi editor di testo.",+ size: "{used} / {max} KB",+ save: "Salva",+ saved: "Memoria salvata",+ loadError: "Impossibile caricare la memoria.",+ saveError: "Impossibile salvare la memoria.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md memoria ricorda personalizzazione profilo note",+ },currentDate: {label: "Comunica al modello la data di oggi",description:diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 55848dca1e8..16c0563573e 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2745,6 +2745,22 @@ export const ja = {visibilityDescription:"思考の開き方。個々のブロックは手動で展開・折りたたみできます。",},+ memory: {+ title: "メモリー",+ description: "すべてのチャットが読み込むメモです。ローカルでもクラウドでも、どのモデルでも使われます。プロジェクト内のチャットは、そのプロジェクトの AGENTS.md も読み込みます。",+ enable: "チャットでメモリーを使う",+ enableDescription: "このメモをすべてのチャットに送信します。",+ locked: "UNSLOTH_STUDIO_AGENTS_MD により、このインストールでは無効になっています。",+ editor: "メモリーのメモ",+ placeholder: "例:\n- Python を書いていて uv を使っています。\n- 簡潔に答えてください。",+ hint: "{path} に保存されます。このファイルは任意のテキストエディタでも編集できます。",+ size: "{used} / {max} KB",+ save: "保存",+ saved: "メモリーを保存しました",+ loadError: "メモリーを読み込めませんでした。",+ saveError: "メモリーを保存できませんでした。",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md メモリー 記憶 覚える パーソナライズ プロフィール メモ",+ },currentDate: {label: "今日の日付をモデルに伝える",description:diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 67503acbcc5..98469db2484 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2754,6 +2754,22 @@ export const ko = {visibilityDescription:"사고 과정이 열리는 방식. 각 블록은 직접 펼치거나 접을 수 있습니다.",},+ memory: {+ title: "메모리",+ description: "모든 채팅이 읽는 메모로, 로컬이든 클라우드든 모든 모델에 적용됩니다. 프로젝트의 채팅은 해당 프로젝트의 AGENTS.md도 읽습니다.",+ enable: "채팅에서 메모리 사용",+ enableDescription: "이 메모를 모든 채팅과 함께 보냅니다.",+ locked: "UNSLOTH_STUDIO_AGENTS_MD로 이 설치에서 꺼져 있습니다.",+ editor: "메모리 메모",+ placeholder: "예:\n- Python을 쓰고 uv를 사용합니다.\n- 답변은 짧게 해 주세요.",+ hint: "{path}에 저장됩니다. 이 파일은 어떤 텍스트 편집기에서도 편집할 수 있습니다.",+ size: "{used} / {max} KB",+ save: "저장",+ saved: "메모리를 저장했습니다",+ loadError: "메모리를 불러오지 못했습니다.",+ saveError: "메모리를 저장하지 못했습니다.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md 메모리 기억 개인화 프로필 메모",+ },currentDate: {label: "모델에 오늘 날짜 알려주기",description:diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex d1ee2da9e80..eb73dca40b1 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2782,6 +2782,22 @@ export const ptBR = {visibilityDescription:"Como o raciocínio abre. Você ainda pode expandir ou recolher qualquer bloco.",},+ memory: {+ title: "Memória",+ description: "Notas que todo chat lê, com qualquer modelo, local ou na nuvem. Chats de um projeto também leem o AGENTS.md desse projeto.",+ enable: "Usar memória nos chats",+ enableDescription: "Enviar estas notas com cada chat.",+ locked: "Desativado nesta instalação por UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Notas de memória",+ placeholder: "Por exemplo:\n- Eu programo em Python e uso uv.\n- Responda de forma curta.",+ hint: "Salvo em {path}. Você também pode editar esse arquivo em qualquer editor de texto.",+ size: "{used} / {max} KB",+ save: "Salvar",+ saved: "Memória salva",+ loadError: "Falha ao carregar a memória.",+ saveError: "Falha ao salvar a memória.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md memória lembrar personalização perfil notas",+ },currentDate: {label: "Informar a data de hoje ao modelo",description:diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 215ba636b7b..d6ca27ed11f 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2780,6 +2780,22 @@ export const ru = {visibilityDescription:"Как открываются размышления. Любой блок по-прежнему можно развернуть или свернуть вручную.",},+ memory: {+ title: "Память",+ description: "Заметки, которые читает каждый чат, для любой модели, локальной или облачной. Чаты в проекте также читают AGENTS.md этого проекта.",+ enable: "Использовать память в чатах",+ enableDescription: "Отправлять эти заметки в каждом чате.",+ locked: "Отключено для этой установки через UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Заметки памяти",+ placeholder: "Например:\n- Я пишу на Python и использую uv.\n- Отвечай кратко.",+ hint: "Сохраняется в {path}. Этот файл можно редактировать и в любом текстовом редакторе.",+ size: "{used} / {max} КБ",+ save: "Сохранить",+ saved: "Память сохранена",+ loadError: "Не удалось загрузить память.",+ saveError: "Не удалось сохранить память.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md память запомнить персонализация профиль заметки",+ },currentDate: {label: "Сообщать модели сегодняшнюю дату",description:diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex d593fce2f1a..7f06269074e 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -2964,6 +2964,22 @@ export const sv = {visibilityDescription:"Hur resonemang öppnas. Du kan fortfarande fälla ut eller ihop valfritt block själv.",},+ memory: {+ title: "Minne",+ description: "Anteckningar som varje chatt läser, för alla modeller, lokala eller i molnet. Chattar i ett projekt läser också projektets AGENTS.md.",+ enable: "Använd minne i chattar",+ enableDescription: "Skicka de här anteckningarna med varje chatt.",+ locked: "Avstängt för den här installationen av UNSLOTH_STUDIO_AGENTS_MD.",+ editor: "Minnesanteckningar",+ placeholder: "Till exempel:\n- Jag skriver Python och använder uv.\n- Svara kort.",+ hint: "Sparas i {path}. Du kan också redigera filen i valfri textredigerare.",+ size: "{used} / {max} KB",+ save: "Spara",+ saved: "Minnet sparat",+ loadError: "Det gick inte att läsa in minnet.",+ saveError: "Det gick inte att spara minnet.",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md minne komma ihåg anpassning profil anteckningar",+ },currentDate: {label: "Berätta dagens datum för modellen",description:diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 11e2870ec2d..653ef524e53 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2720,6 +2720,22 @@ export const zhCN = {visibilityDescription:"思考过程如何展开。你仍可自行展开或折叠任意区块。",},+ memory: {+ title: "记忆",+ description: "每个对话都会读取的笔记,适用于所有本地或云端模型。项目中的对话还会读取该项目的 AGENTS.md。",+ enable: "在对话中使用记忆",+ enableDescription: "在每个对话中发送这些笔记。",+ locked: "已被 UNSLOTH_STUDIO_AGENTS_MD 在此安装中关闭。",+ editor: "记忆笔记",+ placeholder: "例如:\n- 我用 Python 编程,使用 uv。\n- 回答尽量简短。",+ hint: "保存在 {path}。你也可以用任意文本编辑器编辑该文件。",+ size: "{used} / {max} KB",+ save: "保存",+ saved: "记忆已保存",+ loadError: "无法加载记忆。",+ saveError: "无法保存记忆。",+ keywords: "memory remember personalization personalisation profile preferences notes facts custom instructions about me agents.md claude.md 记忆 记住 个性化 个人资料 笔记",+ },currentDate: {label: "告诉模型今天的日期",description:diff --git a/studio/frontend/tests/chat-memory-settings.test.ts b/studio/frontend/tests/chat-memory-settings.test.tsnew file mode 100644index 00000000000..4050b5eb3e0--- /dev/null+++ b/studio/frontend/tests/chat-memory-settings.test.ts@@ -0,0 +1,51 @@+// 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 test from "node:test";++import { chatMemoryBytes } from "../src/features/settings/lib/chat-memory-size.ts";+import {+ agentsMdEditCount,+ forgetAgentsMd,+} from "../src/features/chat/utils/agents-md.ts";+import { createSettingsSearchIndex } from "../src/features/settings/settings-search.ts";+import { readSrcAsync } from "./helpers/kit.ts";++const chatTab = await readSrcAsync("features/settings/tabs/chat-tab.tsx");+const section = await readSrcAsync(+ "features/settings/components/chat-memory-section.tsx",+);+const adapter = await readSrcAsync("features/chat/api/chat-adapter.ts");++test("memory size is counted the way the backend saves it", () => {+ assert.equal(chatMemoryBytes(""), 0);+ assert.equal(chatMemoryBytes(" \n\n "), 0);+ assert.equal(chatMemoryBytes(" a\r\nb \n\n"), "a\nb\n".length);+ assert.equal(chatMemoryBytes("é"), 3);+});++test("the Chat tab shows the memory section and search finds it", () => {+ assert.match(chatTab, /<ChatMemorySection \/>/);+ assert.match(chatTab, /lazy\(\(\) =>\s*import\("..\/components\/chat-memory-section"\)/);+ const index = createSettingsSearchIndex({+ desktop: false,+ closeToTray: false,+ menuBarIcon: false,+ });+ assert.ok(index.chat.includes("settings.chat.memory.title"));+});++test("a saved edit is not hidden by the AGENTS.md read cache", () => {+ const before = agentsMdEditCount();+ forgetAgentsMd();+ assert.equal(agentsMdEditCount(), before + 1);+ assert.match(section, /forgetAgentsMd\(\);/);+ assert.match(adapter, /hit\.edits === edits/);+});++test("the memory switch and editor have accessible names", () => {+ assert.match(section, /aria-label=\{t\("settings\.chat\.memory\.enable"\)\}/);+ assert.match(section, /htmlFor=\{editorId\}/);+ assert.match(section, /role="alert"/);+});