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: manage chat history with projects (#5725)
Lee Jacksone0ff6a1404e9
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex eecb84ca271..0f5dbfa2374 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -421,6 +421,35 @@ _workdirs: dict[str, str] = {}# Non-matching session_ids collapse to ``_invalid`` to block cross-session escapes._SESSION_ID_RE = re.compile(r"\A[A-Za-z0-9_\-]{1,64}\Z")+_PROJECT_SESSION_PREFIX = "project-"+++def _get_project_workdir(session_id: str) -> str | None:+ if not session_id.startswith(_PROJECT_SESSION_PREFIX):+ return None+ project_id = session_id[len(_PROJECT_SESSION_PREFIX) :]+ if not project_id or not _SESSION_ID_RE.match(project_id):+ return None+ try:+ from storage.studio_db import ensure_chat_project_workspace++ project = ensure_chat_project_workspace(project_id)+ except Exception:+ logger.warning(+ "Failed to resolve project sandbox for %s", session_id, exc_info = True+ )+ return None+ if not project:+ return None+ root_path = project.get("rootPath")+ sandbox_path = project.get("sandboxPath")+ if not root_path or not sandbox_path:+ return None+ root_real = os.path.realpath(root_path)+ sandbox_real = os.path.realpath(sandbox_path)+ if sandbox_real != root_real and not sandbox_real.startswith(root_real + os.sep):+ return None+ return sandbox_realdef _get_workdir(session_id: str | None = None) -> str:@@ -430,7 +459,14 @@ def _get_workdir(session_id: str | None = None) -> str:if key not in _workdirs or not os.path.isdir(_workdirs[key]):home = os.path.expanduser("~")sandbox_root = os.path.join(home, "studio_sandbox")- if session_id and _SESSION_ID_RE.match(session_id):+ project_workdir = (+ _get_project_workdir(session_id)+ if session_id and _SESSION_ID_RE.match(session_id)+ else None+ )+ if project_workdir:+ workdir = project_workdir+ elif session_id and _SESSION_ID_RE.match(session_id):workdir = os.path.join(sandbox_root, session_id)if not os.path.realpath(workdir).startswith(os.path.realpath(sandbox_root) + os.sep@@ -453,6 +489,10 @@ def _get_workdir(session_id: str | None = None) -> str:return _workdirs[key]+def get_sandbox_workdir(session_id: str | None = None) -> str:+ return _get_workdir(session_id)++WEB_SEARCH_TOOL = {"type": "function","function": {diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex e64e5ca5c74..8e240962338 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -17,15 +17,21 @@ from storage.studio_db import (clear_chat_history,count_chat_threads,delete_chat_threads,+ delete_chat_project,+ ensure_chat_project_workspace,+ get_chat_project,get_chat_thread,get_chat_message,+ list_chat_projects,list_chat_legacy_imports,list_chat_settings,list_chat_messages,list_chat_messages_for_threads,list_chat_threads,sync_chat_messages,+ update_chat_project,update_chat_thread,+ upsert_chat_project,upsert_chat_legacy_imports,upsert_chat_message,upsert_chat_settings_merge,@@ -41,6 +47,7 @@ class ChatThread(BaseModel):modelType: Literal["base", "lora", "model1", "model2"]modelId: str = ""pairId: Optional[str] = None+ projectId: Optional[str] = Nonearchived: bool = FalsecreatedAt: intopenaiCodeExecContainerId: Optional[str] = None@@ -52,6 +59,7 @@ class ChatThreadPatch(BaseModel):modelType: Optional[Literal["base", "lora", "model1", "model2"]] = NonemodelId: Optional[str] = NonepairId: Optional[str] = None+ projectId: Optional[str] = Nonearchived: Optional[bool] = NonecreatedAt: Optional[int] = NoneopenaiCodeExecContainerId: Optional[str] = None@@ -69,10 +77,33 @@ class ChatMessage(BaseModel):createdAt: int+class ChatProject(BaseModel):+ id: str+ name: str+ instructions: str = ""+ rootPath: Optional[str] = None+ sandboxPath: Optional[str] = None+ archived: bool = False+ createdAt: int+ updatedAt: int+++class ChatProjectPatch(BaseModel):+ name: Optional[str] = None+ instructions: Optional[str] = None+ archived: Optional[bool] = None+ createdAt: Optional[int] = None+ updatedAt: Optional[int] = None++class ChatThreadListResponse(BaseModel):threads: list[ChatThread]+class ChatProjectListResponse(BaseModel):+ projects: list[ChatProject]++class ChatMessageListResponse(BaseModel):messages: list[ChatMessage]@@ -94,6 +125,7 @@ class ChatExportResponse(BaseModel):exportedAt: strversion: intthreadCount: int+ projects: list[ChatProject] = Field(default_factory = list)threads: list[ChatThread]messages: list[ChatMessage]@@ -177,12 +209,14 @@ class ChatImportLedgerRecordResponse(BaseModel):async def list_threads(model_type: Optional[str] = Query(None),pair_id: Optional[str] = Query(None),+ project_id: Optional[str] = Query(None),include_archived: bool = Query(True),current_subject: str = Depends(get_current_subject),):threads = list_chat_threads(model_type = model_type,pair_id = pair_id,+ project_id = project_id,include_archived = include_archived,)return ChatThreadListResponse(threads = [ChatThread(**t) for t in threads])@@ -193,6 +227,11 @@ async def save_thread(payload: ChatThread,current_subject: str = Depends(get_current_subject),):+ if payload.projectId and get_chat_project(payload.projectId) is None:+ raise HTTPException(+ status_code = 404,+ detail = f"Project {payload.projectId} not found",+ )return ChatThread(**upsert_chat_thread(payload.model_dump()))@@ -217,6 +256,11 @@ async def patch_thread(for field in ("title", "modelType", "modelId", "archived", "createdAt"):if field in patch and patch[field] is None:raise HTTPException(status_code = 400, detail = f"{field} cannot be null")+ if patch.get("projectId") and get_chat_project(patch["projectId"]) is None:+ raise HTTPException(+ status_code = 404,+ detail = f"Project {patch['projectId']} not found",+ )thread = update_chat_thread(thread_id,patch,@@ -235,6 +279,77 @@ async def delete_threads(return {"status": "deleted"}[email protected]("/projects", response_model = ChatProjectListResponse)+async def list_projects(+ include_archived: bool = Query(False),+ current_subject: str = Depends(get_current_subject),+):+ return ChatProjectListResponse(+ projects = [+ ChatProject(**(ensure_chat_project_workspace(project["id"]) or project))+ for project in list_chat_projects(include_archived = include_archived)+ ]+ )++[email protected]("/projects", response_model = ChatProject)+async def save_project(+ payload: ChatProject,+ current_subject: str = Depends(get_current_subject),+):+ return ChatProject(**upsert_chat_project(payload.model_dump()))++[email protected]("/projects/{project_id}", response_model = ChatProject)+async def get_project(+ project_id: str,+ current_subject: str = Depends(get_current_subject),+):+ project = ensure_chat_project_workspace(project_id)+ if project is None:+ raise HTTPException(+ status_code = 404,+ detail = f"Project {project_id} not found",+ )+ return ChatProject(**project)++[email protected]("/projects/{project_id}", response_model = ChatProject)+async def patch_project(+ project_id: str,+ payload: ChatProjectPatch,+ current_subject: str = Depends(get_current_subject),+):+ patch = payload.model_dump(exclude_unset = True)+ for field in ("name", "archived", "createdAt", "updatedAt"):+ if field in patch and patch[field] is None:+ raise HTTPException(status_code = 400, detail = f"{field} cannot be null")+ project = update_chat_project(project_id, patch)+ if project is not None:+ project = ensure_chat_project_workspace(project_id)+ if project is None:+ raise HTTPException(+ status_code = 404,+ detail = f"Project {project_id} not found",+ )+ return ChatProject(**project)++[email protected]("/projects/{project_id}", response_model = ChatProject)+async def delete_project(+ project_id: str,+ delete_files: bool = Query(False),+ current_subject: str = Depends(get_current_subject),+):+ project = delete_chat_project(project_id, delete_files = delete_files)+ if project is None:+ raise HTTPException(+ status_code = 404,+ detail = f"Project {project_id} not found",+ )+ return ChatProject(**project)++@router.get("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)async def get_thread_messages(thread_id: str,@@ -389,11 +504,13 @@ async def export_history(current_subject: str = Depends(get_current_subject)):from datetime import datetime, timezonethreads = list_chat_threads(include_archived = True)+ projects = list_chat_projects(include_archived = True)messages = list_chat_messages_for_threads([thread["id"] for thread in threads])return ChatExportResponse(exportedAt = datetime.now(timezone.utc).isoformat(),version = 1,threadCount = len(threads),+ projects = [ChatProject(**project) for project in projects],threads = [ChatThread(**thread) for thread in threads],messages = [ChatMessage(**message) for message in messages],)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex fbe8cf6a923..2964a0801f3 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3837,16 +3837,11 @@ async def serve_sandbox_file()# ── Path containment check ──────────────────────────────────- home = os.path.expanduser("~")- sandbox_root = os.path.realpath(os.path.join(home, "studio_sandbox"))- safe_session = os.path.basename(session_id.replace("..", ""))- if not safe_session:- raise HTTPException(status_code = 404, detail = "Not found")+ from core.inference.tools import get_sandbox_workdir- file_path = os.path.realpath(- os.path.join(sandbox_root, safe_session, safe_filename)- )- if not file_path.startswith(sandbox_root + os.sep):+ sandbox_dir = os.path.realpath(get_sandbox_workdir(session_id))+ file_path = os.path.realpath(os.path.join(sandbox_dir, safe_filename))+ if file_path != sandbox_dir and not file_path.startswith(sandbox_dir + os.sep):raise HTTPException(status_code = status.HTTP_403_FORBIDDEN,detail = "Access denied",diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex de89b6cbd29..0887eb9ceb6 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -14,15 +14,18 @@ import jsonimport loggingimport osimport platform+import re+import shutilimport sqlite3import threadingfrom datetime import datetime, timezone+from pathlib import Pathlogger = logging.getLogger(__name__)from typing import Any, Iterable, Optional-from utils.paths import studio_db_path, ensure_dir+from utils.paths import project_workspaces_root, studio_db_path, ensure_dirdef _denied_path_prefixes() -> list[str]:@@ -55,6 +58,77 @@ def _denied_path_prefixes() -> list[str]:_schema_lock = threading.Lock()_schema_ready = False_SQLITE_IN_CHUNK_SIZE = 900+_PROJECT_WORKSPACE_SUBDIRS = ("sandbox",)+++def _project_slug(name: str) -> str:+ slug = re.sub(r"[^A-Za-z0-9._-]+", "-", name.strip()).strip(".-_")+ return slug[:48] or "project"+++def _default_project_root(project: dict) -> str:+ project_id = str(project["id"])+ suffix = re.sub(r"[^A-Za-z0-9_-]+", "-", project_id)[:8].strip("-_") or "project"+ folder_name = f"{_project_slug(str(project.get('name') or 'Project'))}-{suffix}"+ return str(project_workspaces_root() / folder_name)+++def _ensure_project_workspace(root_path: str) -> str:+ root = Path(root_path).expanduser()+ root_resolved = ensure_dir(root).resolve()+ for subdir in _PROJECT_WORKSPACE_SUBDIRS:+ ensure_dir(root_resolved / subdir)+ return str(root_resolved)+++def _delete_project_workspace(project: dict) -> None:+ root_path = project.get("rootPath")+ if not root_path:+ return+ root = Path(root_path).expanduser()+ try:+ root_resolved = root.resolve(strict = False)+ except (OSError, RuntimeError, ValueError):+ logger.warning(+ "Skipping project workspace delete for invalid path %r", root_path+ )+ return++ project_id = str(project["id"])+ suffix = re.sub(r"[^A-Za-z0-9_-]+", "-", project_id)[:8].strip("-_") or "project"+ if not root_resolved.name.endswith(f"-{suffix}"):+ logger.warning(+ "Skipping project workspace delete for unexpected project path %s",+ root_resolved,+ )+ return+ if root_resolved.parent == root_resolved or root_resolved == Path.home().resolve():+ logger.warning(+ "Skipping project workspace delete for unsafe project path %s",+ root_resolved,+ )+ return+ check = (+ os.path.normcase(str(root_resolved))+ if platform.system() == "Windows"+ else str(root_resolved)+ )+ for prefix in _denied_path_prefixes():+ if check == prefix or check.startswith(prefix + os.sep):+ logger.warning(+ "Skipping project workspace delete under denied path %s",+ root_resolved,+ )+ return+ if not root_resolved.exists():+ return+ if root_resolved.is_symlink() or not root_resolved.is_dir():+ logger.warning(+ "Skipping project workspace delete for non-directory path %s",+ root_resolved,+ )+ return+ shutil.rmtree(root_resolved)def _ensure_schema(conn: sqlite3.Connection) -> None:@@ -119,6 +193,27 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)""")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS chat_projects (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ instructions TEXT,+ root_path TEXT,+ archived INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )+ """+ )+ chat_project_cols = {+ row[1] for row in conn.execute("PRAGMA table_info(chat_projects)").fetchall()+ }+ if "root_path" not in chat_project_cols:+ conn.execute("ALTER TABLE chat_projects ADD COLUMN root_path TEXT")+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_chat_projects_archived_updated_at ON chat_projects(archived, updated_at)"+ )conn.execute("""CREATE TABLE IF NOT EXISTS chat_threads (@@ -127,16 +222,20 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:model_type TEXT NOT NULL,model_id TEXT,pair_id TEXT,+ project_id TEXT,archived INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL,openai_code_exec_container_id TEXT,- anthropic_code_exec_container_id TEXT+ anthropic_code_exec_container_id TEXT,+ FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE)""")chat_thread_cols = {row[1] for row in conn.execute("PRAGMA table_info(chat_threads)").fetchall()}+ if "project_id" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN project_id TEXT")if "openai_code_exec_container_id" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN openai_code_exec_container_id TEXT"@@ -165,6 +264,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_threads_pair_id ON chat_threads(pair_id)")+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_chat_threads_project_id ON chat_threads(project_id)"+ )conn.execute("CREATE INDEX IF NOT EXISTS idx_chat_messages_thread_id_created_at ON chat_messages(thread_id, created_at)")@@ -681,6 +783,7 @@ def _chat_thread_from_row(row: sqlite3.Row) -> dict:"modelType": data["model_type"],"modelId": data.get("model_id") or "","pairId": data.get("pair_id") or None,+ "projectId": data.get("project_id") or None,"archived": bool(data["archived"]),"createdAt": data["created_at"],"openaiCodeExecContainerId": data.get("openai_code_exec_container_id"),@@ -688,6 +791,21 @@ def _chat_thread_from_row(row: sqlite3.Row) -> dict:}+def _chat_project_from_row(row: sqlite3.Row) -> dict:+ data = dict(row)+ root_path = data.get("root_path")+ return {+ "id": data["id"],+ "name": data["name"],+ "instructions": data.get("instructions") or "",+ "rootPath": root_path or None,+ "sandboxPath": os.path.join(root_path, "sandbox") if root_path else None,+ "archived": bool(data["archived"]),+ "createdAt": data["created_at"],+ "updatedAt": data["updated_at"],+ }++def _chat_message_from_row(row: sqlite3.Row) -> dict:data = dict(row)message = {@@ -713,13 +831,14 @@ def upsert_chat_thread(thread: dict) -> dict:conn.execute("""INSERT INTO chat_threads- (id, title, model_type, model_id, pair_id, archived, created_at, openai_code_exec_container_id, anthropic_code_exec_container_id)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ (id, title, model_type, model_id, pair_id, project_id, archived, created_at, openai_code_exec_container_id, anthropic_code_exec_container_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETtitle = excluded.title,model_type = excluded.model_type,model_id = excluded.model_id,pair_id = excluded.pair_id,+ project_id = excluded.project_id,archived = excluded.archived,created_at = excluded.created_at,openai_code_exec_container_id = excluded.openai_code_exec_container_id,@@ -731,6 +850,7 @@ def upsert_chat_thread(thread: dict) -> dict:thread["modelType"],thread.get("modelId") or "",thread.get("pairId"),+ thread.get("projectId"),1 if thread.get("archived") else 0,int(thread["createdAt"]),thread.get("openaiCodeExecContainerId"),@@ -749,6 +869,7 @@ def update_chat_thread(id: str, patch: dict) -> Optional[dict]:"modelType": ("model_type", patch.get("modelType")),"modelId": ("model_id", patch.get("modelId")),"pairId": ("pair_id", patch.get("pairId")),+ "projectId": ("project_id", patch.get("projectId")),"archived": ("archived", 1 if patch.get("archived") else 0),"createdAt": ("created_at", patch.get("createdAt")),"openaiCodeExecContainerId": (@@ -794,6 +915,7 @@ def get_chat_thread(id: str) -> Optional[dict]:def list_chat_threads(model_type: str | None = None,pair_id: str | None = None,+ project_id: str | None = None,include_archived: bool = True,) -> list[dict]:clauses = []@@ -804,6 +926,9 @@ def list_chat_threads(if pair_id is not None:clauses.append("pair_id = ?")values.append(pair_id)+ if project_id is not None:+ clauses.append("project_id = ?")+ values.append(project_id)if not include_archived:clauses.append("archived = 0")where = f"WHERE {' AND '.join(clauses)}" if clauses else ""@@ -846,6 +971,136 @@ def count_chat_threads() -> int:conn.close()+def upsert_chat_project(project: dict) -> dict:+ existing = get_chat_project(project["id"])+ root_path = existing.get("rootPath") if existing else None+ if not root_path:+ root_path = _default_project_root(project)+ root_path = _ensure_project_workspace(root_path)+ conn = get_connection()+ try:+ conn.execute(+ """+ INSERT INTO chat_projects+ (id, name, instructions, root_path, archived, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ name = excluded.name,+ instructions = excluded.instructions,+ root_path = COALESCE(chat_projects.root_path, excluded.root_path),+ archived = excluded.archived,+ created_at = excluded.created_at,+ updated_at = excluded.updated_at+ """,+ (+ project["id"],+ project["name"],+ project.get("instructions") or "",+ root_path,+ 1 if project.get("archived") else 0,+ int(project["createdAt"]),+ int(project["updatedAt"]),+ ),+ )+ conn.commit()+ return get_chat_project(project["id"]) or project+ finally:+ conn.close()+++def update_chat_project(id: str, patch: dict) -> Optional[dict]:+ allowed = {+ "name": ("name", patch.get("name")),+ "instructions": ("instructions", patch.get("instructions")),+ "archived": ("archived", 1 if patch.get("archived") else 0),+ "createdAt": ("created_at", patch.get("createdAt")),+ "updatedAt": ("updated_at", patch.get("updatedAt")),+ }+ assignments = []+ values = []+ for key, (column, value) in allowed.items():+ if key in patch:+ assignments.append(f"{column} = ?")+ values.append(value)+ if not assignments:+ return get_chat_project(id)++ conn = get_connection()+ try:+ conn.execute(+ f"UPDATE chat_projects SET {', '.join(assignments)} WHERE id = ?",+ (*values, id),+ )+ conn.commit()+ row = conn.execute("SELECT * FROM chat_projects WHERE id = ?", (id,)).fetchone()+ return _chat_project_from_row(row) if row is not None else None+ finally:+ conn.close()+++def ensure_chat_project_workspace(id: str) -> Optional[dict]:+ project = get_chat_project(id)+ if project is None:+ return None+ root_path = project.get("rootPath") or _default_project_root(project)+ root_path = _ensure_project_workspace(root_path)+ if project.get("rootPath") == root_path:+ return project+ conn = get_connection()+ try:+ conn.execute(+ "UPDATE chat_projects SET root_path = ? WHERE id = ?",+ (root_path, id),+ )+ conn.commit()+ finally:+ conn.close()+ return get_chat_project(id)+++def get_chat_project(id: str) -> Optional[dict]:+ conn = get_connection()+ try:+ row = conn.execute("SELECT * FROM chat_projects WHERE id = ?", (id,)).fetchone()+ return _chat_project_from_row(row) if row is not None else None+ finally:+ conn.close()+++def list_chat_projects(include_archived: bool = False) -> list[dict]:+ conn = get_connection()+ try:+ where = "" if include_archived else "WHERE archived = 0"+ rows = conn.execute(+ f"SELECT * FROM chat_projects {where} ORDER BY updated_at DESC"+ ).fetchall()+ return [_chat_project_from_row(row) for row in rows]+ finally:+ conn.close()+++def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:+ conn = get_connection()+ try:+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute("SELECT * FROM chat_projects WHERE id = ?", (id,)).fetchone()+ if row is None:+ conn.rollback()+ return None+ project = _chat_project_from_row(row)+ conn.execute("DELETE FROM chat_threads WHERE project_id = ?", (id,))+ conn.execute("DELETE FROM chat_projects WHERE id = ?", (id,))+ conn.commit()+ if delete_files:+ _delete_project_workspace(project)+ return project+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++class ChatMessageConflictError(RuntimeError):"""Raised when a chat message id already belongs to another thread."""diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 123dbf1b961..e88cac3276b 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -1,18 +1,49 @@# 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 platform+import shutilimport threading+import uuid+from pathlib import Pathimport pytestfrom storage import studio_db-def _reset_studio_db(tmp_path, monkeypatch):+def _reset_studio_db(tmp_path, monkeypatch, projects_home = None):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv(+ "UNSLOTH_STUDIO_PROJECTS_HOME",+ str(projects_home if projects_home is not None else tmp_path / "Projects"),+ )monkeypatch.setattr(studio_db, "_schema_ready", False)+def workspace_projects_home(tmp_path):+ """Projects root outside the platform delete denylist.++ tmp_path resolves under /private/tmp on macOS, which the workspace+ delete guard refuses by design. Linux/Windows tmp is not denied and is+ used as-is; only the denied case falls back to a home subdir.+ """+ candidate = tmp_path / "Projects"+ resolved = str(candidate.resolve())+ check = os.path.normcase(resolved) if platform.system() == "Windows" else resolved+ denied = studio_db._denied_path_prefixes()+ if any(check == p or check.startswith(p + os.sep) for p in denied):+ candidate = Path.home() / ".unsloth-studio-tests" / uuid.uuid4().hex+ candidate.mkdir(parents = True, exist_ok = True)+ try:+ yield candidate+ finally:+ if ".unsloth-studio-tests" in candidate.parts:+ shutil.rmtree(candidate, ignore_errors = True)++def _thread(thread_id: str = "thread-1") -> dict:return {"id": thread_id,@@ -41,6 +72,17 @@ def _message(}+def _project(project_id: str = "project-1") -> dict:+ return {+ "id": project_id,+ "name": "Research",+ "instructions": "Use terse answers.",+ "archived": False,+ "createdAt": 1_700_000_000_000,+ "updatedAt": 1_700_000_000_000,+ }++def test_sync_chat_messages_upserts_without_pruning(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)studio_db.upsert_chat_thread(_thread())@@ -63,6 +105,53 @@ def test_sync_chat_messages_upserts_without_pruning(tmp_path, monkeypatch):assert by_id["msg-2"]["content"] == [{"type": "text", "text": "updated text"}]+def test_chat_projects_delete_cascades_threads_and_messages(+ tmp_path,+ monkeypatch,+):+ _reset_studio_db(tmp_path, monkeypatch)+ project = studio_db.upsert_chat_project(_project())+ assert project["rootPath"].startswith(str(tmp_path / "Projects"))+ assert (tmp_path / "Projects" / "Research-project").exists()+ assert (tmp_path / "Projects" / "Research-project" / "sandbox").is_dir()+ assert not (tmp_path / "Projects" / "Research-project" / "chats").exists()+ assert not (tmp_path / "Projects" / "Research-project" / "files").exists()+ assert not (tmp_path / "Projects" / "Research-project" / "exports").exists()+ studio_db.upsert_chat_thread({**_thread(), "projectId": "project-1"})+ studio_db.upsert_chat_message(_message("msg-1", 1, "delete with project"))++ [thread] = studio_db.list_chat_threads(project_id = "project-1")+ assert thread["projectId"] == "project-1"++ deleted = studio_db.delete_chat_project("project-1")++ assert deleted is not None+ assert deleted["id"] == "project-1"+ assert studio_db.get_chat_project("project-1") is None+ assert studio_db.list_chat_threads(project_id = "project-1") == []+ assert studio_db.get_chat_thread("thread-1") is None+ assert studio_db.list_chat_messages("thread-1") == []+ assert (tmp_path / "Projects" / "Research-project").exists()+++def test_chat_project_delete_files_removes_workspace(+ tmp_path, monkeypatch, workspace_projects_home+):+ _reset_studio_db(tmp_path, monkeypatch, projects_home = workspace_projects_home)+ project = studio_db.upsert_chat_project(_project())+ # Derive root from the created project so it tracks the projects home.+ root = Path(project["rootPath"])+ marker = root / "sandbox" / "marker.txt"+ marker.write_text("created by code execution", encoding = "utf-8")++ deleted = studio_db.delete_chat_project(project["id"], delete_files = True)++ assert deleted is not None+ assert deleted["rootPath"] == project["rootPath"]+ assert not root.exists()+ assert studio_db.get_chat_project(project["id"]) is None++def test_sync_chat_messages_prunes_when_requested(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)studio_db.upsert_chat_thread(_thread())diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.pyindex 92191dccdd7..eba7a9de6cd 100644--- a/studio/backend/utils/paths/__init__.py+++ b/studio/backend/utils/paths/__init__.py@@ -25,6 +25,8 @@ from .storage_roots import (auth_root,auth_db_path,studio_db_path,+ documents_root,+ project_workspaces_root,tmp_root,seed_uploads_root,unstructured_seed_cache_root,@@ -44,6 +46,10 @@ from .storage_roots import (resolve_dataset_path,)+# Re-export shim: name-load the project-path helpers so the import-hoist+# safety net sees them used here, not just listed in __all__ as strings.+_REEXPORTED = (documents_root, project_workspaces_root)+__all__ = ["normalize_path","is_local_path",@@ -62,6 +68,8 @@ __all__ = ["auth_root","auth_db_path","studio_db_path",+ "documents_root",+ "project_workspaces_root","tmp_root","seed_uploads_root","unstructured_seed_cache_root",diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.pyindex 763d18bf3e1..6319452ed20 100644--- a/studio/backend/utils/paths/storage_roots.py+++ b/studio/backend/utils/paths/storage_roots.py@@ -96,6 +96,38 @@ def studio_db_path() -> Path:return studio_root() / "studio.db"+def _xdg_user_dir(key: str) -> Path | None:+ config = Path.home() / ".config" / "user-dirs.dirs"+ try:+ lines = config.read_text(encoding = "utf-8").splitlines()+ except OSError:+ return None+ prefix = f"{key}="+ for line in lines:+ line = line.strip()+ if not line.startswith(prefix):+ continue+ value = line[len(prefix) :].strip().strip('"')+ if not value:+ return None+ return Path(value.replace("$HOME", str(Path.home()))).expanduser()+ return None+++def documents_root() -> Path:+ override = (os.environ.get("UNSLOTH_STUDIO_DOCUMENTS_HOME") or "").strip()+ if override:+ return Path(override).expanduser()+ return _xdg_user_dir("XDG_DOCUMENTS_DIR") or (Path.home() / "Documents")+++def project_workspaces_root() -> Path:+ override = (os.environ.get("UNSLOTH_STUDIO_PROJECTS_HOME") or "").strip()+ if override:+ return Path(override).expanduser()+ return documents_root() / "Unsloth Studio" / "Projects"++def tmp_root() -> Path:return Path(tempfile.gettempdir()) / "unsloth-studio"diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.jsonindex 80f5d0a7015..4afee8a916e 100644--- a/studio/frontend/package-lock.json+++ b/studio/frontend/package-lock.json@@ -13229,9 +13229,9 @@}},"node_modules/react-is": {- "version": "19.2.5",- "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.5.tgz",- "integrity": "sha512-Dn0t8IQhCmeIT3wu+Apm1/YVsJXsGWi6k4sPdnBIdqMVtHtv0IGi6dcpNpNkNac0zB2uUAqNX3MHzN8c+z2rwQ==",+ "version": "19.2.6",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.6.tgz",+ "integrity": "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw==","license": "MIT","peer": true},diff --git a/studio/frontend/package.json b/studio/frontend/package.jsonindex b43e1748893..66b821d6c79 100644--- a/studio/frontend/package.json+++ b/studio/frontend/package.json@@ -88,8 +88,8 @@"@eslint/js": "^9.39.1","@types/canvas-confetti": "^1.9.0","@types/js-yaml": "^4.0.9",- "@types/node-forge": "^1.3.14","@types/node": "^25.5.2",+ "@types/node-forge": "^1.3.14","@types/react": "^19.2.5","@types/react-dom": "^19.2.3","@vitejs/plugin-react": "^6.0.1",diff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsxindex f0a417638d9..a0ca1e8cdb6 100644--- a/studio/frontend/src/app/router.tsx+++ b/studio/frontend/src/app/router.tsx@@ -13,6 +13,7 @@ import { Route as gridTestRoute } from "./routes/grid-test";import { Route as indexRoute } from "./routes/index";import { Route as loginRoute } from "./routes/login";import { Route as onboardingRoute } from "./routes/onboarding";+import { Route as projectsRoute } from "./routes/projects";import { Route as changePasswordRoute } from "./routes/change-password";import { Route as settingsRoute } from "./routes/settings";import { Route as studioRoute } from "./routes/studio";@@ -26,6 +27,7 @@ const routeTree = rootRoute.addChildren([settingsRoute,studioRoute,chatRoute,+ projectsRoute,exportRoute,dataRecipesRoute,dataRecipeRoute,diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 57ed233d51b..da74a9e8a71 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -6,6 +6,7 @@ import { Navbar } from "@/components/navbar";import { fetchDeviceType, usePlatformStore } from "@/config/env";import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";import { SettingsDialog, useSettingsDialogStore } from "@/features/settings";+import { useChatRuntimeStore } from "@/features/chat";import { useTrainingUnloadGuard } from "@/features/training";import { useSidebarPin } from "@/hooks/use-sidebar-pin";import { useT, type TranslationKey } from "@/i18n";@@ -40,6 +41,7 @@ function RouteFallback() {const CHAT_ONLY_ALLOWED = new Set(["/","/chat",+ "/projects","/login","/signup","/change-password",@@ -110,6 +112,13 @@ function RootLayout() {return () => window.removeEventListener("keydown", handler);}, []);+ useEffect(() => {+ if (isChatRoute) return;+ const chatRuntime = useChatRuntimeStore.getState();+ chatRuntime.setActiveProjectId(null);+ chatRuntime.setActiveThreadId(null);+ }, [isChatRoute]);+return (<AppProvider><SettingsDialog />diff --git a/studio/frontend/src/app/routes/chat.tsx b/studio/frontend/src/app/routes/chat.tsxindex 98c73aa7e02..a5514cdee18 100644--- a/studio/frontend/src/app/routes/chat.tsx+++ b/studio/frontend/src/app/routes/chat.tsx@@ -10,6 +10,7 @@ export type ChatSearch = {thread?: string;compare?: string;new?: string;+ project?: string;};export const Route = createRoute({@@ -21,6 +22,7 @@ export const Route = createRoute({thread: typeof search.thread === "string" ? search.thread : undefined,compare: typeof search.compare === "string" ? search.compare : undefined,new: typeof search.new === "string" ? search.new : undefined,+ project: typeof search.project === "string" ? search.project : undefined,}),component: ChatPage,});diff --git a/studio/frontend/src/app/routes/projects.tsx b/studio/frontend/src/app/routes/projects.tsxnew file mode 100644index 00000000000..c63b1d58382--- /dev/null+++ b/studio/frontend/src/app/routes/projects.tsx@@ -0,0 +1,21 @@+// 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 { createRoute } from "@tanstack/react-router";+import { lazy } from "react";+import { requireAuth } from "../auth-guards";+import { Route as rootRoute } from "./__root";++const ProjectsPage = lazy(() =>+ import("@/features/chat/projects-page").then((m) => ({+ default: m.ProjectsPage,+ })),+);++export const Route = createRoute({+ getParentRoute: () => rootRoute,+ path: "/projects",+ staticData: { title: "Projects" },+ beforeLoad: () => requireAuth(),+ component: ProjectsPage,+});diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 4e4a6130cdf..16292bd6e49 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -26,6 +26,9 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuShortcut,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import {@@ -38,6 +41,7 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";import { useAnimatedThemeToggle } from "@/components/ui/animated-theme-toggler";import { cn } from "@/lib/utils";import {@@ -47,9 +51,12 @@ import {Delete02Icon,DownloadSquare01Icon,Edit03Icon,+ FolderAddIcon,+ Folder01Icon,Globe02Icon,HelpCircleIcon,Logout05Icon,+ MoreVerticalIcon,Search01Icon,PowerIcon,PencilEdit02Icon,@@ -68,11 +75,17 @@ import { ChevronDown, ChevronsUpDown, MoreHorizontalIcon, Moon, Sun } from "luciimport { Link, useNavigate, useRouterState } from "@tanstack/react-router";import {ChatSearchDialog,+ createChatProject,+ deleteChatProject,deleteChatItem,+ moveChatItemToProject,renameChatItem,+ renameChatProject,useChatRuntimeStore,+ useChatProjects,useChatSearchStore,useChatSidebarItems,+ type ProjectRecord,type SidebarItem,} from "@/features/chat";import { useSettingsDialogStore } from "@/features/settings";@@ -90,7 +103,7 @@ import {useTrainingRuntimeStore,} from "@/features/training";import type { TrainingRunSummary } from "@/features/training";-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { toast } from "@/lib/toast";import { ShutdownDialog } from "@/components/shutdown-dialog";import { translate, useT, type TranslationKey } from "@/i18n";@@ -185,7 +198,7 @@ function NavItem({active: boolean;disabled?: boolean;onClick: () => void;- children?: React.ReactNode;+ children?: ReactNode;dataTour?: string;}) {return (@@ -197,7 +210,7 @@ function NavItem({onClick={onClick}isActive={active}data-tour={dataTour}- className="sidebar-nav-btn h-[35px] rounded-[10px] gap-[8.5px] px-2.5 font-medium group-data-[collapsible=icon]:!w-[32px] group-data-[collapsible=icon]:!rounded-[10px] group-data-[collapsible=icon]:mx-auto"+ className="sidebar-nav-btn h-[33px] rounded-[10px] gap-[8.5px] px-2.5 font-medium group-data-[collapsible=icon]:!w-[32px] group-data-[collapsible=icon]:!rounded-[10px] group-data-[collapsible=icon]:mx-auto"><HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-icon! shrink-0 group-hover/menu-button:animate-icon-pop" /><span className="text-[14.5px] leading-[19px] tracking-nav">{label}</span>@@ -231,22 +244,53 @@ export function AppSidebar() {const isChatRoute = pathname.startsWith("/chat");const isStudioRoute = pathname === "/studio" || pathname.startsWith("/studio/");+ const [chatOpen, setChatOpen] = useState(true);+ const [trainOpen, setTrainOpen] = useState(true);+ const [runsOpen, setRunsOpen] = useState(true);++ useEffect(() => {+ if (!isChatRoute) return;+ queueMicrotask(() => setChatOpen(true));+ }, [isChatRoute]);+ useEffect(() => {+ if (!isStudioRoute) return;+ queueMicrotask(() => setRunsOpen(true));+ }, [isStudioRoute]);const scrollRef = useRef<HTMLDivElement | null>(null);const [scrolled, setScrolled] = useState(false);- useEffect(() => {- const el = scrollRef.current;- if (!el) return;- const handler = () => setScrolled(el.scrollTop > 0);- handler();- el.addEventListener("scroll", handler, { passive: true });- return () => el.removeEventListener("scroll", handler);- }, []);+ // Bottom fade hides at the very bottom (and for short, non-scrolling lists)+ // so the last row isn't washed out - Gemini-style.+ const [canScrollDown, setCanScrollDown] = useState(false);+ // Driven only from onScroll + a content-change effect below. Deliberately NO+ // ResizeObserver: its callback-driven setState created a render loop (React+ // #185). Both setters bail out when unchanged, so neither path can loop.+ const syncScrollState = (el: HTMLDivElement) => {+ const nextScrolled = el.scrollTop > 0;+ setScrolled((prev) => (prev === nextScrolled ? prev : nextScrolled));+ const nextCanScrollDown =+ el.scrollHeight - el.scrollTop - el.clientHeight > 1;+ setCanScrollDown((prev) =>+ prev === nextCanScrollDown ? prev : nextCanScrollDown,+ );+ };const isRecipesRoute = pathname.startsWith("/data-recipes");const { displayTitle, avatarDataUrl } = useEffectiveProfile();- const { items: chatItems } = useChatSidebarItems();+ const { projects } = useChatProjects();+ const activeProjectId = isChatRoute+ ? ((search.project as string | undefined) ?? null)+ : null;+ const { items: allChatItems } = useChatSidebarItems({+ enabled: !isStudioRoute,+ requireMessages: false,+ });+ const recentChatItems = useMemo(+ () => allChatItems.filter((item) => !item.projectId),+ [allChatItems],+ );+ const chatItems = allChatItems;const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);const setActiveThreadId = useChatRuntimeStore((s) => s.setActiveThreadId);const activeThreadId = isChatRoute@@ -261,33 +305,87 @@ export function AppSidebar() {!chatOnly && isStudioRoute,);const activeJobId = useTrainingRuntimeStore((s) => s.jobId);+ const currentRunViewActive = useTrainingRuntimeStore((s) => s.currentRunViewActive);const selectedHistoryRunId = useTrainingRuntimeStore((s) => s.selectedHistoryRunId);const setSelectedHistoryRunId = useTrainingRuntimeStore((s) => s.setSelectedHistoryRunId);+ // Recompute the bottom-fade state on mount and whenever the list height can+ // change (items load, sections collapse/expand, route switches the visible+ // list) - onScroll never fires for short, non-scrolling lists. Guarded+ // setState below means this can't loop even if a dep is a fresh reference.+ useEffect(() => {+ const el = scrollRef.current;+ if (!el) return;+ const next = el.scrollHeight - el.scrollTop - el.clientHeight > 1;+ setCanScrollDown((prev) => (prev === next ? prev : next));+ }, [+ recentChatItems.length,+ runItems.length,+ projects.length,+ chatOpen,+ trainOpen,+ runsOpen,+ isStudioRoute,+ ]);+const chatDisabled = isTrainingRunning;+ function chatSearchForProject(projectId: string | null) {+ if (projectId) {+ return { project: projectId };+ }+ return {+ new: createNavigationNonce(),+ };+ }++ function openNewChat(projectId = activeProjectId) {+ if (chatDisabled) return;+ setActiveThreadId(null);+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ navigate({ to: "/chat", search: chatSearchForProject(projectId) });+ closeMobileIfOpen();+ }++ function openProject(projectId: string) {+ if (chatDisabled) return;+ setActiveThreadId(null);+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ navigate({ to: "/chat", search: { project: projectId } });+ closeMobileIfOpen();+ }+async function handleDeleteThread(item: Parameters<typeof deleteChatItem>[0]) {await deleteChatItem(item, activeThreadId, (view) => {navigate({to: "/chat",- search: { new: view.newThreadNonce },+ search: item.projectId+ ? { project: item.projectId }+ : { new: view.newThreadNonce },});});}type RenameTarget =| { kind: "chat"; item: SidebarItem; current: string }+ | { kind: "project"; project: ProjectRecord; current: string }| { kind: "run"; run: TrainingRunSummary; current: string };const [renamingTarget, setRenamingTarget] = useState<RenameTarget | null>(null,);const [renameDraft, setRenameDraft] = useState("");+ const [creatingProject, setCreatingProject] = useState(false);+ const [projectNameDraft, setProjectNameDraft] = useState("");+ const [projectCreateMoveTarget, setProjectCreateMoveTarget] =+ useState<SidebarItem | null>(null);const renameTrimmed = renameDraft.trim();const nextRunDisplayName = renameTrimmed.length > 0 ? renameTrimmed : null;const renameDirty =renamingTarget !== null &&(renamingTarget.kind === "chat"? renameTrimmed.length > 0 && renameTrimmed !== renamingTarget.current+ : renamingTarget.kind === "project"+ ? renameTrimmed.length > 0 && renameTrimmed !== renamingTarget.current: renameTrimmed.length > 0? renameTrimmed !== renamingTarget.current: renamingTarget.run.display_name != null);@@ -315,6 +413,16 @@ export function AppSidebar() {}return;}+ if (target.kind === "project") {+ try {+ await renameChatProject(target.project.id, renameTrimmed);+ } catch (err) {+ toast.error("Failed to rename project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ return;+ }try {const updated = await renameTrainingRun(target.run.id, nextRunDisplayName);emitTrainingRunUpdated(updated);@@ -327,13 +435,23 @@ export function AppSidebar() {type DeleteTarget =| { kind: "chat"; item: SidebarItem }+ | { kind: "project"; project: ProjectRecord }| { kind: "run"; run: TrainingRunSummary };const [confirmingDelete, setConfirmingDelete] =useState<DeleteTarget | null>(null);+ const [deleteProjectFiles, setDeleteProjectFiles] = useState(false);++ useEffect(() => {+ if (confirmingDelete?.kind !== "project") {+ setDeleteProjectFiles(false);+ }+ }, [confirmingDelete]);async function commitDelete() {const target = confirmingDelete;if (!target) return;+ const shouldDeleteProjectFiles =+ target.kind === "project" && deleteProjectFiles;setConfirmingDelete(null);if (target.kind === "chat") {try {@@ -345,6 +463,22 @@ export function AppSidebar() {}return;}+ if (target.kind === "project") {+ try {+ await deleteChatProject(target.project.id, {+ deleteFiles: shouldDeleteProjectFiles,+ });+ if (activeProjectId === target.project.id) {+ useChatRuntimeStore.getState().setActiveProjectId(null);+ navigate({ to: "/chat", search: { new: createNavigationNonce() } });+ }+ } catch (err) {+ toast.error("Failed to delete project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ return;+ }if (target.run.status === "running") {toast.error(t("shell.toast.cannotDeleteRunningRun"));return;@@ -362,6 +496,168 @@ export function AppSidebar() {}}+ async function commitCreateProject() {+ const name = projectNameDraft.trim();+ if (!name) return;+ const moveTarget = projectCreateMoveTarget;+ try {+ const project = await createChatProject(name);+ if (moveTarget) {+ await moveChatItemToProject(moveTarget, project.id);+ if (activeThreadId === moveTarget.id) {+ useChatRuntimeStore.getState().setActiveProjectId(project.id);+ }+ }+ setCreatingProject(false);+ setProjectNameDraft("");+ setProjectCreateMoveTarget(null);+ if (moveTarget) {+ return;+ } else {+ openProject(project.id);+ }+ } catch (err) {+ toast.error(moveTarget ? "Failed to create and move chat" : "Failed to create project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ async function moveChatToProject(item: SidebarItem, projectId: string | null) {+ if (item.projectId === projectId) return;+ try {+ await moveChatItemToProject(item, projectId);+ if (activeThreadId === item.id) {+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ }+ } catch (err) {+ toast.error("Failed to move chat", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ function renderChatSidebarItem(+ item: SidebarItem,+ variant: "project" | "recent",+ ) {+ const itemClass =+ variant === "project"+ ? "group/project-chat-item relative"+ : "group/recent-item relative";+ const actionClass =+ variant === "project"+ ? "sidebar-row-action group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"+ : "sidebar-row-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto";+ const buttonClass = cn(+ "sidebar-nav-btn h-[33px] cursor-pointer rounded-[10px] pr-4 text-[14.5px] leading-[19px] tracking-nav font-medium",+ variant === "project" ? "pl-[37px]" : "pl-2.5",+ variant === "project"+ ? "group-hover/project-chat-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-8"+ : "group-hover/recent-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8",+ );++ return (+ <SidebarMenuItem key={item.id} className={itemClass}>+ <SidebarMenuButton+ data-testid="recent-thread"+ data-thread-type={item.type}+ data-thread-id={item.id}+ isActive={activeThreadId === item.id}+ className={buttonClass}+ onClick={() => {+ navigate({+ to: "/chat",+ search:+ item.type === "single"+ ? {+ thread: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ }+ : {+ compare: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ },+ });+ closeMobileIfOpen();+ }}+ >+ <span className="truncate">{item.title}</span>+ </SidebarMenuButton>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ onClick={(e) => e.stopPropagation()}+ aria-label="Chat options"+ className={actionClass}+ >+ <span className="sidebar-row-action-glyph">+ <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />+ </span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="bottom"+ align="end"+ sideOffset={4}+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-[14px] border-0"+ >+ <DropdownMenuItem onSelect={() => openRenameChat(item)}>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Rename</span>+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Move to project</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={8}+ alignOffset={-4}+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-56 py-2 font-heading rounded-[14px] border-0"+ >+ <DropdownMenuItem+ onSelect={() => {+ setProjectCreateMoveTarget(item);+ setProjectNameDraft("");+ setCreatingProject(true);+ }}+ >+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />+ <span>New project</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={!item.projectId}+ onSelect={() => void moveChatToProject(item, null)}+ >+ <span>Recents</span>+ </DropdownMenuItem>+ {projects.map((project) => (+ <DropdownMenuItem+ key={project.id}+ disabled={item.projectId === project.id}+ onSelect={() => void moveChatToProject(item, project.id)}+ >+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{project.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirmingDelete({ kind: "chat", item })}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuItem>+ );+ }+return (<><Sidebar@@ -369,7 +665,7 @@ export function AppSidebar() {variant="sidebar"className="font-heading group-data-[collapsible=icon]:[&_[data-sidebar=sidebar]]:bg-white dark:group-data-[collapsible=icon]:[&_[data-sidebar=sidebar]]:bg-background">- <SidebarHeader className="pl-[17px] pr-3 pt-[12px] pb-[8px] group-data-[collapsible=icon]:px-0">+ <SidebarHeader className="pl-[17px] pr-3 pt-[14px] pb-[8px] group-data-[collapsible=icon]:px-0">{/* Expanded: compact logo + close toggle */}<div className="flex items-center justify-between gap-[8.5px] group-data-[collapsible=icon]:hidden"><Link@@ -377,12 +673,7 @@ export function AppSidebar() {onClick={(event) => {event.preventDefault();if (chatDisabled) return;- setActiveThreadId(null);- closeMobileIfOpen();- void navigate({- to: "/chat",- search: { new: createNavigationNonce() },- });+ openNewChat(null);}}className="flex items-center gap-[6px] select-none"aria-label={t("shell.aria.home")}@@ -392,7 +683,7 @@ export function AppSidebar() {alt="Unsloth"className="h-[34px] w-[34px] rounded-full object-cover"/>- <span className="font-heading text-[21px] font-semibold tracking-[-0.01em] dark:tracking-[0.02em] leading-none text-black dark:text-white">+ <span className="font-heading text-[21px] font-semibold tracking-[0em] dark:tracking-[0.02em] leading-none text-black dark:text-white">unsloth</span><span className="nav-badge ml-0.5 inline-flex items-center justify-center rounded-full border border-nav-beta-border px-[5px] pt-[3px] pb-[2px] text-[8px] font-medium leading-none tracking-[0.04em] text-nav-fg-muted antialiased subpixel-antialiased shadow-[0_1px_2px_rgba(0,0,0,0.06)] dark:shadow-[0_1px_2px_rgba(0,0,0,0.35)]">@@ -405,7 +696,7 @@ export function AppSidebar() {<buttontype="button"onClick={togglePinned}- className="inline-flex h-[35px] w-[32px] items-center justify-center rounded-[10px] text-nav-icon-idle dark:text-nav-fg-muted transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ className="inline-flex h-[33px] w-[32px] cursor-pointer items-center justify-center rounded-[10px] text-nav-icon-idle dark:text-nav-fg-muted transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"aria-label={t("shell.aria.closeSidebar")}><HugeiconsIcon icon={LayoutAlignLeftIcon} strokeWidth={1.75} className="size-icon" />@@ -424,13 +715,13 @@ export function AppSidebar() {{/* Collapsed: panel icon doubles as expand trigger */}{!isMobile && (- <div className="hidden group-data-[collapsible=icon]:flex h-[35px] items-center justify-center w-full">+ <div className="hidden group-data-[collapsible=icon]:flex h-[33px] items-center justify-center w-full"><Tooltip><TooltipPrimitive.Trigger asChild><buttontype="button"onClick={togglePinned}- className="inline-flex h-[35px] w-[32px] items-center justify-center rounded-[10px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ className="inline-flex h-[33px] w-[32px] cursor-pointer items-center justify-center rounded-[10px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"aria-label={t("shell.aria.openSidebar")}><HugeiconsIcon icon={LayoutAlignLeftIcon} strokeWidth={1.75} className="size-icon" />@@ -448,31 +739,37 @@ export function AppSidebar() {)}</SidebarHeader>- <SidebarGroup className="group-data-[collapsible=icon]:px-0 px-2 pt-[9px] pb-[8px] shrink-0">+ <SidebarGroup className="group-data-[collapsible=icon]:px-0 px-2 pt-[9px] pb-px shrink-0"><SidebarGroupContent><SidebarMenu><NavItemicon={PencilEdit02Icon}label={t("shell.navigation.newChat")}- active={false}+ active={+ isChatRoute &&+ !search.thread &&+ !search.compare &&+ !search.project+ }disabled={chatDisabled}- onClick={() => {- if (chatDisabled) return;- setActiveThreadId(null);- navigate({ to: "/chat", search: { new: createNavigationNonce() } });- closeMobileIfOpen();- }}+ onClick={() => openNewChat(null)}/><NavItemicon={ColumnInsertIcon}label={t("shell.navigation.compare")}- active={!!search.compare && !chatItems.some((i) => i.id === search.compare)}+ active={+ !!search.compare &&+ !chatItems.some((i) => i.id === search.compare)+ }disabled={chatDisabled}dataTour="chat-compare"onClick={() => {if (chatDisabled) return;setActiveThreadId(null);- navigate({ to: "/chat", search: { compare: createNavigationNonce() } });+ navigate({+ to: "/chat",+ search: { compare: createNavigationNonce() },+ });closeMobileIfOpen();}}/>@@ -480,9 +777,10 @@ export function AppSidebar() {icon={Search01Icon}label={t("shell.navigation.search")}active={false}- disabled={chatDisabled}onClick={() => {- if (chatDisabled) return;+ // Search is read-only over chat history and never runs+ // inference, so it stays available while training (unlike+ // New chat, which is gated on `chatDisabled`).useChatSearchStore.getState().open();closeMobileIfOpen();}}@@ -491,140 +789,127 @@ export function AppSidebar() {</SidebarGroupContent></SidebarGroup>- <SidebarGroup data-tour="navbar" className="group-data-[collapsible=icon]:px-0 px-2 pt-[9px] pb-[20px] shrink-0">- <SidebarGroupContent>- <SidebarMenu>- <NavItem- icon={TestTubeOutlineIcon}- label={t("shell.navigation.train")}- active={pathname === "/studio" || pathname.startsWith("/studio/")}- disabled={chatOnly}- onClick={() => {- if (chatOnly) return;- navigate({ to: "/studio" });- closeMobileIfOpen();- }}- />-- <NavItem- icon={ChefHatIcon}- label={t("shell.navigation.recipes")}- active={isRecipesRoute}- onClick={() => {- navigate({ to: "/data-recipes" });- closeMobileIfOpen();- }}- />-- <NavItem- icon={DownloadSquare01Icon}- label={t("shell.navigation.export")}- active={pathname === "/export" || pathname.startsWith("/export/")}- disabled={chatOnly}- onClick={() => {- if (chatOnly) return;- navigate({ to: "/export" });- closeMobileIfOpen();- }}- />- </SidebarMenu>- </SidebarGroupContent>- </SidebarGroup>+ <SidebarContent+ ref={scrollRef}+ onScroll={(e) => syncScrollState(e.currentTarget)}+ className={cn(+ // pb-2 keeps the last row's rounded highlight clear of the+ // overflow clip edge so its bottom corners aren't shaved off.+ "sidebar-scroll-fade gap-0 overflow-y-auto overscroll-contain min-h-0 pb-2",+ scrolled && "is-scrolled",+ )}+ >+ <SidebarGroup className="group-data-[collapsible=icon]:px-0 px-2 py-0 shrink-0">+ <SidebarGroupContent>+ <SidebarMenu>+ <NavItem+ icon={Folder01Icon}+ label="Projects"+ active={+ pathname === "/projects" || pathname.startsWith("/projects/")+ }+ onClick={() => {+ navigate({ to: "/projects" });+ closeMobileIfOpen();+ }}+ />+ </SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup>- <SidebarContent ref={scrollRef} className="gap-0 overflow-y-auto overscroll-contain min-h-0">- {!isStudioRoute && chatItems.length > 0 && (- <Collapsible- key={isChatRoute ? "chat-route" : "non-chat-route"}- defaultOpen- asChild- >- <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">- <SidebarGroupLabel className={cn("sidebar-sticky-label", scrolled && "is-scrolled")} asChild>- <CollapsibleTrigger className="cursor-pointer flex w-full items-center justify-between">- {t("shell.navigation.recents")}- <ChevronDown className="size-3.5 transition-transform duration-200 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg]" />+ <Collapsible open={trainOpen} onOpenChange={setTrainOpen} asChild>+ <SidebarGroup data-tour="navbar" className="group-data-[collapsible=icon]:hidden px-0 py-0">+ <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following", scrolled && "is-scrolled")} asChild>+ <CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">+ {t("shell.navigation.train")}+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg]" /></CollapsibleTrigger></SidebarGroupLabel><CollapsibleContent>- <SidebarGroupContent className="px-2">- <SidebarMenu>- {chatItems.map((item) => (- <SidebarMenuItem key={item.id} className="group/recent-item relative">- <SidebarMenuButton- data-testid="recent-thread"- data-thread-type={item.type}- data-thread-id={item.id}- isActive={activeThreadId === item.id}- className="sidebar-nav-btn h-[32px] rounded-[10px] pl-2.5 pr-2.5 group-hover/recent-item:pr-10 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-10 text-[14.5px] leading-[19px] tracking-nav font-medium"- onClick={() => {- navigate({- to: "/chat",- search:- item.type === "single"- ? { thread: item.id }- : { compare: item.id },- });- closeMobileIfOpen();- }}- >- <span className="truncate">{item.title}</span>- </SidebarMenuButton>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- onClick={(e) => e.stopPropagation()}- aria-label={t("shell.aria.chatOptions")}- className="sidebar-row-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"- >- <span className="sidebar-row-action-glyph">- <MoreHorizontalIcon strokeWidth={1.75} className="size-icon" />- </span>- </button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- sideOffset={4}- className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-[14px] border-0"- >- <DropdownMenuItem onSelect={() => openRenameChat(item)}>- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.rename")}</span>- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onSelect={() => setConfirmingDelete({ kind: "chat", item })}- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.delete")}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>- ))}- </SidebarMenu>- </SidebarGroupContent>+ <SidebarGroupContent className="px-2">+ <SidebarMenu>+ <NavItem+ icon={TestTubeOutlineIcon}+ label={t("shell.navigation.train")}+ active={pathname === "/studio" || pathname.startsWith("/studio/")}+ disabled={chatOnly}+ onClick={() => {+ if (chatOnly) return;+ navigate({ to: "/studio" });+ closeMobileIfOpen();+ }}+ />+ <NavItem+ icon={ChefHatIcon}+ label={t("shell.navigation.recipes")}+ active={isRecipesRoute}+ onClick={() => {+ navigate({ to: "/data-recipes" });+ closeMobileIfOpen();+ }}+ />+ <NavItem+ icon={DownloadSquare01Icon}+ label={t("shell.navigation.export")}+ active={pathname === "/export" || pathname.startsWith("/export/")}+ disabled={chatOnly}+ onClick={() => {+ if (chatOnly) return;+ navigate({ to: "/export" });+ closeMobileIfOpen();+ }}+ />+ </SidebarMenu>+ </SidebarGroupContent></CollapsibleContent></SidebarGroup>+ </Collapsible>++ {!isStudioRoute && (+ <Collapsible open={chatOpen} onOpenChange={setChatOpen} asChild>+ <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">+ <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following", scrolled && "is-scrolled")} asChild>+ <CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">+ {t("shell.navigation.recents")}+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg]" />+ </CollapsibleTrigger>+ </SidebarGroupLabel>+ <CollapsibleContent>+ <SidebarGroupContent className="px-2">+ <SidebarMenu>+ {recentChatItems.map((item) =>+ renderChatSidebarItem(item, "recent"),+ )}+ </SidebarMenu>+ </SidebarGroupContent>+ </CollapsibleContent>+ </SidebarGroup></Collapsible>)}{isStudioRoute && runItems.length > 0 && !chatOnly && (- <Collapsible key="studio-runs-route" defaultOpen asChild>+ <Collapsible open={runsOpen} onOpenChange={setRunsOpen} asChild><SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">- <SidebarGroupLabel className={cn("sidebar-sticky-label", scrolled && "is-scrolled")} asChild>- <CollapsibleTrigger className="cursor-pointer flex w-full items-center justify-between">+ <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following", scrolled && "is-scrolled")} asChild>+ <CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">{t("shell.navigation.recents")}- <ChevronDown className="size-3.5 transition-transform duration-200 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg]" />+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg]" /></CollapsibleTrigger></SidebarGroupLabel><CollapsibleContent><SidebarGroupContent className="px-2"><SidebarMenu>{runItems.map((run) => {+ // An explicit sidebar selection wins. Otherwise highlight+ // the active job only while the "Current Run" tab is the+ // view - that covers a live run (it auto-switches there) and+ // a just-finished/errored run you're still viewing, while+ // keeping the Configure tab unhighlighted even though+ // `activeJobId` stays pinned to the last job.const isActiveRun =- selectedHistoryRunId === run.id || activeJobId === run.id;+ selectedHistoryRunId != null+ ? run.id === selectedHistoryRunId+ : currentRunViewActive && run.id === activeJobId;return (<SidebarMenuItemkey={run.id}@@ -703,7 +988,18 @@ export function AppSidebar() {)}</SidebarContent>- <SidebarFooter className="border-t border-sidebar-border group-data-[collapsible=icon]:border-transparent group-data-[collapsible=icon]:px-0">+ <SidebarFooter className="relative group-data-[collapsible=icon]:px-0">+ {/* Fade above the profile box, shown only while there's more list below+ the fold; at the very bottom (or for short lists) it fades out so the+ last row shows fully (Gemini-style). `right-2` keeps it clear of the+ 8px scrollbar gutter so the scrollbar isn't faded out. */}+ <div+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute left-0 right-2 bottom-full h-10 bg-gradient-to-t from-[var(--sidebar)] to-transparent transition-opacity duration-200",+ canScrollDown ? "opacity-100" : "opacity-0",+ )}+ /><SidebarMenu><SidebarMenuItem><DropdownMenu>@@ -711,14 +1007,14 @@ export function AppSidebar() {<SidebarMenuButtonsize="lg"aria-label={t("shell.accountMenu", { name: displayTitle })}- className="sidebar-nav-btn !h-[50px] gap-[8px] px-2 py-[9px] rounded-[10px]"+ className="sidebar-nav-btn !h-[40px] gap-[8px] px-2 py-[5px] rounded-[10px]"><div className="shrink-0"><UserAvatarname={displayTitle}imageUrl={avatarDataUrl}size="sm"- className="!size-8"+ className="!size-[30px]"/></div><div className="flex flex-col gap-0.5 leading-tight group-data-[collapsible=icon]:hidden">@@ -818,7 +1114,10 @@ export function AppSidebar() {<Dialogopen={confirmingDelete !== null}onOpenChange={(open) => {- if (!open) setConfirmingDelete(null);+ if (!open) {+ setConfirmingDelete(null);+ setDeleteProjectFiles(false);+ }}}><DialogContent className="menu-flat-destructive corner-squircle border border-border/60 bg-background/98 shadow-none sm:max-w-md">@@ -826,7 +1125,9 @@ export function AppSidebar() {<DialogTitle>{confirmingDelete?.kind === "run"? t("shell.dialog.deleteRun.title")- : t("shell.dialog.deleteChat.title")}+ : confirmingDelete?.kind === "project"+ ? "Delete project"+ : t("shell.dialog.deleteChat.title")}</DialogTitle><DialogDescription>{confirmingDelete?.kind === "run" ? (@@ -842,9 +1143,37 @@ export function AppSidebar() {"shell.dialog.deleteChat.description",confirmingDelete.item.title,)+ ) : confirmingDelete?.kind === "project" ? (+ <>+ Delete{" "}+ <span className="font-medium text-foreground">+ "{confirmingDelete.project.name}"+ </span>+ ? Its chats will be permanently deleted.+ </>) : null}</DialogDescription></DialogHeader>+ {confirmingDelete?.kind === "project" ? (+ <div className="flex items-start justify-between gap-4 rounded-md border border-border/60 bg-muted/35 px-3 py-2.5">+ <label htmlFor="delete-project-files" className="min-w-0 space-y-1">+ <span className="block text-sm font-medium text-foreground">+ Delete files and sandbox folder+ </span>+ <span className="block break-words text-xs leading-5 text-muted-foreground">+ {confirmingDelete.project.rootPath+ ? confirmingDelete.project.rootPath+ : "The project workspace folder will be removed from disk."}+ </span>+ </label>+ <Switch+ id="delete-project-files"+ checked={deleteProjectFiles}+ onCheckedChange={setDeleteProjectFiles}+ aria-label="Delete project files and sandbox folder"+ />+ </div>+ ) : null}<DialogFooter className="flex-wrap gap-2 sm:justify-end"><Buttontype="button"@@ -858,7 +1187,9 @@ export function AppSidebar() {variant="destructive"onClick={() => void commitDelete()}>- {t("common.delete")}+ {confirmingDelete?.kind === "project" && deleteProjectFiles+ ? "Delete all"+ : t("common.delete")}</Button></DialogFooter></DialogContent>@@ -874,7 +1205,9 @@ export function AppSidebar() {<DialogTitle>{renamingTarget?.kind === "run"? t("shell.dialog.renameRun.title")- : t("shell.dialog.renameChat.title")}+ : renamingTarget?.kind === "project"+ ? "Rename project"+ : t("shell.dialog.renameChat.title")}</DialogTitle></DialogHeader><Input@@ -891,12 +1224,16 @@ export function AppSidebar() {placeholder={renamingTarget?.kind === "run"? t("shell.dialog.renameRun.placeholder")- : t("shell.dialog.renameChat.placeholder")+ : renamingTarget?.kind === "project"+ ? "Project name"+ : t("shell.dialog.renameChat.placeholder")}aria-label={renamingTarget?.kind === "run"? t("shell.dialog.renameRun.placeholder")- : t("shell.dialog.renameChat.placeholder")+ : renamingTarget?.kind === "project"+ ? "Project name"+ : t("shell.dialog.renameChat.placeholder")}className="focus-visible:border-input focus-visible:ring-0"/>@@ -918,6 +1255,58 @@ export function AppSidebar() {</DialogFooter></DialogContent></Dialog>+ <Dialog+ open={creatingProject}+ onOpenChange={(open) => {+ setCreatingProject(open);+ if (!open) {+ setProjectNameDraft("");+ setProjectCreateMoveTarget(null);+ }+ }}+ >+ <DialogContent className="corner-squircle border border-border/60 bg-background/98 shadow-none sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {projectCreateMoveTarget ? "Move to new project" : "New project"}+ </DialogTitle>+ </DialogHeader>+ <Input+ value={projectNameDraft}+ onChange={(event) => setProjectNameDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ void commitCreateProject();+ }+ }}+ autoFocus+ maxLength={120}+ placeholder="Project name"+ aria-label="Project name"+ className="focus-visible:border-input focus-visible:ring-0"+ />+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">+ <Button+ type="button"+ variant="ghost"+ onClick={() => {+ setCreatingProject(false);+ setProjectCreateMoveTarget(null);+ }}+ >+ Cancel+ </Button>+ <Button+ type="button"+ onClick={() => void commitCreateProject()}+ disabled={!projectNameDraft.trim()}+ >+ Create+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></>);}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex b7e0f35d35d..b323996072e 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -374,7 +374,7 @@ const ThreadWelcome: FC<{<div className="aui-thread-welcome-message flex w-full flex-col justify-center gap-6 px-4"><div className="flex flex-col items-center gap-2 text-center"><img src={currentEmojiSrc} alt="Sloth mascot" className="size-20" />- <h1 className="aui-thread-welcome-message-inner fade-in slide-in-from-bottom-1 animate-in font-heading font-semibold text-2xl tracking-[-0.02em] duration-200">+ <h1 className="aui-thread-welcome-message-inner fade-in slide-in-from-bottom-1 animate-in font-heading font-semibold text-2xl tracking-[0em] duration-200">Chat with your model</h1><p className="aui-thread-welcome-message-inner fade-in slide-in-from-bottom-1 -mt-1 animate-in font-heading font-normal text-muted-foreground text-sm delay-75 duration-200">@@ -388,14 +388,30 @@ const ThreadWelcome: FC<{);};+export const ProjectComposer: FC<{+ disabled?: boolean;+ placeholder?: string;+}> = ({ disabled, placeholder }) => {+ return (+ <GeneratedImageOverlayProvider>+ <ComposerAnimated disabled={disabled} placeholder={placeholder} />+ </GeneratedImageOverlayProvider>+ );+};+const ComposerAnimated: FC<{disabled?: boolean;+ placeholder?: string;threadId?: string | null;-}> = ({ disabled, threadId }) => {+}> = ({ disabled, placeholder, threadId }) => {return (<div className="relative mx-auto min-w-0 w-full max-w-(--thread-max-width)"><div className="relative z-10 w-full">- <Composer disabled={disabled} threadId={threadId} />+ <Composer+ disabled={disabled}+ placeholder={placeholder}+ threadId={threadId}+ /></div></div>);@@ -427,8 +443,9 @@ const PendingAudioChip: FC = () => {const Composer: FC<{disabled?: boolean;+ placeholder?: string;threadId?: string | null;-}> = ({ disabled, threadId }) => {+}> = ({ disabled, placeholder = "Send a message...", threadId }) => {const aui = useAui();const { overlay, closeOverlay } = useGeneratedImageOverlay();const setImageToolsEnabled = useChatRuntimeStore(@@ -529,9 +546,7 @@ const Composer: FC<{<PendingAudioChip /><ToolStatusDisplay /><ComposerPrimitive.Input- placeholder={- overlay ? "Type your edits for your image" : "Send a message..."- }+ placeholder={overlay ? "Type your edits for your image" : placeholder}className="aui-composer-input composer-input"minRows={1}maxRows={12}@@ -975,8 +990,8 @@ const PreserveThinkingToggle: FC = () => {disabled? "cursor-not-allowed opacity-40": preserveThinking- ? "text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"- : "hover:bg-primary/10 dark:hover:bg-white/[0.08]",+ ? "cursor-pointer text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"+ : "cursor-pointer hover:bg-primary/10 dark:hover:bg-white/[0.08]",)}aria-label={preserveThinking ? "Disable preserve think" : "Enable preserve think"diff --git a/studio/frontend/src/components/ui/dropdown-menu.tsx b/studio/frontend/src/components/ui/dropdown-menu.tsxindex e2f1c5fc6de..9102e5c9456 100644--- a/studio/frontend/src/components/ui/dropdown-menu.tsx+++ b/studio/frontend/src/components/ui/dropdown-menu.tsx@@ -78,7 +78,7 @@ function DropdownMenuItem({data-inset={inset}data-variant={variant}className={cn(- "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-lg px-3 py-2 text-sm [&_svg:not([class*='size-'])]:size-4 group/dropdown-menu-item relative flex cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",+ "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-lg px-3 py-2 text-sm [&_svg:not([class*='size-'])]:size-4 group/dropdown-menu-item relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",className,)}{...props}@@ -96,7 +96,7 @@ function DropdownMenuCheckboxItem({<DropdownMenuPrimitive.CheckboxItemdata-slot="dropdown-menu-checkbox-item"className={cn(- "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-lg py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",+ "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-lg py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",className,)}checked={checked}@@ -135,7 +135,7 @@ function DropdownMenuRadioItem({<DropdownMenuPrimitive.RadioItemdata-slot="dropdown-menu-radio-item"className={cn(- "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-lg py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",+ "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-lg py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",className,)}{...props}@@ -221,7 +221,7 @@ function DropdownMenuSubTrigger({data-slot="dropdown-menu-sub-trigger"data-inset={inset}className={cn(- "focus:bg-accent focus:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2 rounded-lg px-3 py-2 text-sm [&_svg:not([class*='size-'])]:size-4 flex cursor-default items-center outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",+ "focus:bg-accent focus:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2 rounded-lg px-3 py-2 text-sm [&_svg:not([class*='size-'])]:size-4 flex cursor-pointer items-center outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0",className,)}{...props}diff --git a/studio/frontend/src/components/ui/sidebar.tsx b/studio/frontend/src/components/ui/sidebar.tsxindex 6be77d01b98..b3bae96ce76 100644--- a/studio/frontend/src/components/ui/sidebar.tsx+++ b/studio/frontend/src/components/ui/sidebar.tsx@@ -30,7 +30,7 @@ import { LayoutAlignLeftIcon } from "@hugeicons/core-free-icons"const noop = () => {}-const SIDEBAR_WIDTH = "16rem"+const SIDEBAR_WIDTH = "17.5rem"const SIDEBAR_WIDTH_ICON = "3rem"const SIDEBAR_KEYBOARD_SHORTCUT = "b"@@ -472,7 +472,7 @@ function SidebarGroupLabel({data-slot="sidebar-group-label"data-sidebar="group-label"className={cn(- "text-[#94a3b8] dark:text-[#666] ring-sidebar-ring h-auto pt-3 pb-2 px-4 rounded-md text-[10px] font-semibold uppercase tracking-[0.08em] group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-3 flex shrink-0 items-center outline-hidden [&>svg]:shrink-0",+ "text-[#94a3b8] dark:text-[#666] ring-sidebar-ring h-auto pt-3 pb-2 px-4 rounded-md text-[10px] font-semibold uppercase tracking-[0em] group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-3 flex shrink-0 items-center outline-hidden [&>svg]:shrink-0",className)}{...props}diff --git a/studio/frontend/src/components/ui/terminal.tsx b/studio/frontend/src/components/ui/terminal.tsxindex 9c8da233262..e7a05bd1aaa 100644--- a/studio/frontend/src/components/ui/terminal.tsx+++ b/studio/frontend/src/components/ui/terminal.tsx@@ -17,12 +17,20 @@ type TerminalProps = {className?: stringsequence?: booleanstartOnView?: boolean+ /**+ * Render every line in its final state immediately, skipping the typing /+ * fade-in animations. Used when the terminal re-mounts for a run whose intro+ * already played (e.g. navigating away from the training page and back), so+ * the logs don't visually "restart" while the run itself keeps going.+ */+ instant?: boolean}type InternalLineProps = {__isActive?: boolean__onDone?: () => void__sequence?: boolean+ __instant?: boolean}function useStartOnView(enabled: boolean): {@@ -65,15 +73,18 @@ export function Terminal({className,sequence = true,startOnView = true,+ instant = false,}: TerminalProps): ReactElement {const { ref, started } = useStartOnView(startOnView)const childElements = Children.toArray(children).filter(isValidElement)const [activeIndex, setActiveIndex] = useState(0)- const visibleIndex = sequence- ? started- ? activeIndex- : -1- : Number.MAX_SAFE_INTEGER+ const visibleIndex = instant+ ? Number.MAX_SAFE_INTEGER+ : sequence+ ? started+ ? activeIndex+ : -1+ : Number.MAX_SAFE_INTEGERfunction handleLineDone(index: number): void {if (!sequence) {@@ -99,7 +110,8 @@ export function Terminal({{childElements.map((child, index) =>cloneElement(child, {__sequence: sequence,- __isActive: !sequence || visibleIndex >= index,+ __isActive: instant || !sequence || visibleIndex >= index,+ __instant: instant,__onDone: () => handleLineDone(index),key: child.key ?? index,} as InternalLineProps)@@ -122,11 +134,12 @@ export function AnimatedSpan({startOnView = false,__isActive,__sequence,+ __instant,__onDone,}: AnimatedSpanProps): ReactElement {const { ref, started } = useStartOnView(startOnView)- const [visible, setVisible] = useState(false)- const doneRef = useRef(false)+ const [visible, setVisible] = useState(Boolean(__instant))+ const doneRef = useRef(Boolean(__instant))const onDoneRef = useRef(__onDone)const shouldStart = __sequence ? __isActive : started@@ -180,11 +193,12 @@ export function TypingAnimation({startOnView = true,__isActive,__sequence,+ __instant,__onDone,}: TypingAnimationProps): ReactElement {const { ref, started } = useStartOnView(startOnView)- const [typed, setTyped] = useState("")- const doneRef = useRef(false)+ const [typed, setTyped] = useState(__instant ? children : "")+ const doneRef = useRef(Boolean(__instant))const onDoneRef = useRef(__onDone)const shouldStart = __sequence ? __isActive : starteddiff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex fc77fecaeb0..1fcbe7ff70c 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -47,6 +47,7 @@ import type {import type { ChatModelSummary } from "../types/runtime";import {getStoredChatThread,+ getStoredChatProject,listStoredChatThreads,updateStoredChatThread,} from "../utils/chat-history-storage";@@ -866,6 +867,45 @@ async function resolveUseAdapter(}}+async function resolveProjectInstructions(+ threadId: string | undefined,+): Promise<string> {+ const projectId = await resolveProjectId(threadId);+ if (!projectId) {+ return "";+ }++ const project = await getStoredChatProject(projectId).catch(() => null);+ if (!project || project.archived) {+ return "";+ }+ return project.instructions?.trim() ?? "";+}++async function resolveProjectId(+ threadId: string | undefined,+): Promise<string | null> {+ let projectId: string | null | undefined;+ if (threadId) {+ const thread = await getStoredChatThread(threadId).catch(() => null);+ projectId = thread?.projectId ?? null;+ }+ if (!projectId) {+ projectId = useChatRuntimeStore.getState().activeProjectId;+ }+ if (!projectId) {+ return null;+ }+ return projectId;+}++async function resolveSandboxSessionId(+ threadId: string | undefined,+): Promise<string | undefined> {+ const projectId = await resolveProjectId(threadId);+ return projectId ? `project-${projectId}` : threadId;+}+/** Wait for an in-progress model load to finish (polls store every 500ms). */function waitForModelReady(abortSignal?: AbortSignal): Promise<void> {return new Promise((resolve, reject) => {@@ -1202,6 +1242,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {// the user switches chats while waiting for model load / auto-load.const resolvedThreadId =(unstable_threadId ?? runtime.activeThreadId) || undefined;+ const sandboxSessionId = await resolveSandboxSessionId(resolvedThreadId);const resolvedThreadKey = resolvedThreadId ?? null;const pendingImageEditReferenceForRun = runtime.pendingImageEditReference;const selectedImageEditReference =@@ -1442,10 +1483,20 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {const safeSystemPrompt =typeof params.systemPrompt === "string" ? params.systemPrompt : "";- if (safeSystemPrompt.trim()) {+ const projectInstructions =+ await resolveProjectInstructions(resolvedThreadId);+ const combinedSystemPrompt = [+ projectInstructions+ ? `<project_instructions>\n${projectInstructions}\n</project_instructions>`+ : "",+ safeSystemPrompt.trim(),+ ]+ .filter(Boolean)+ .join("\n\n");+ if (combinedSystemPrompt) {outboundMessages.unshift({role: "system",- content: safeSystemPrompt.trim(),+ content: combinedSystemPrompt,});}let disabledToolGuard: string | null = null;@@ -1762,7 +1813,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {// /inference/cancel explicitly on abort.const onAbortCancel = () => {const body: Record<string, string> = { cancel_id: cancelId };- if (resolvedThreadId) body.session_id = resolvedThreadId;+ if (sandboxSessionId) body.session_id = sandboxSessionId;// Plain fetch, not authFetch: authFetch redirects to login on// 401, which would kick the user out mid-stop.const token = getAuthToken();@@ -2077,7 +2128,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {image_base64: imageBase64,audio_base64: audioBase64,cancel_id: cancelId,- ...(resolvedThreadId ? { session_id: resolvedThreadId } : {}),+ ...(sandboxSessionId ? { session_id: sandboxSessionId } : {}),...(useAdapter === undefined ? {} : { use_adapter: useAdapter }),...(supportsReasoning? reasoningStyle === "reasoning_effort"@@ -2272,7 +2323,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {const text = rawResult.slice(0, imgIdx);// Fall back to "_default" to match the backend sandbox directory// used when no session_id is provided (see tools.py _get_workdir).- const sessionId = resolvedThreadId || "_default";+ const sessionId = sandboxSessionId || "_default";try {const images = JSON.parse(rawResult.slice(imgIdx + imgMarker.length),diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 81303d93119..85b3be7dea1 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -3,7 +3,12 @@import { authFetch } from "@/features/auth";import { formatFastApiDetail } from "@/lib/format-fastapi-error";-import type { MessageRecord, ModelType, ThreadRecord } from "../types";+import type {+ MessageRecord,+ ModelType,+ ProjectRecord,+ ThreadRecord,+} from "../types";import type {AudioGenerationResponse,GgufVariantsResponse,@@ -287,12 +292,14 @@ export async function listChatThreads(args: {modelType?: ModelType;pairId?: string;+ projectId?: string | null;includeArchived?: boolean;} = {},): Promise<ThreadRecord[]> {const params = new URLSearchParams();if (args.modelType) params.set("model_type", args.modelType);if (args.pairId) params.set("pair_id", args.pairId);+ if (args.projectId) params.set("project_id", args.projectId);if (args.includeArchived !== undefined) {params.set("include_archived", String(args.includeArchived));}@@ -353,6 +360,74 @@ export async function deleteChatThreads(threadIds: string[]): Promise<void> {notifyChatHistoryUpdated();}+export async function listChatProjects(+ args: { includeArchived?: boolean } = {},+): Promise<ProjectRecord[]> {+ const params = new URLSearchParams();+ if (args.includeArchived !== undefined) {+ params.set("include_archived", String(args.includeArchived));+ }+ const qs = params.toString();+ const response = await authFetch(`/api/chat/projects${qs ? `?${qs}` : ""}`);+ const data = await parseJsonOrThrow<{ projects: ProjectRecord[] }>(response);+ return data.projects;+}++export async function getChatProject(+ projectId: string,+): Promise<ProjectRecord | null> {+ const response = await authFetch(+ `/api/chat/projects/${encodeURIComponent(projectId)}`,+ );+ if (response.status === 404) return null;+ return parseJsonOrThrow<ProjectRecord>(response);+}++export async function saveChatProject(+ project: ProjectRecord,+): Promise<ProjectRecord> {+ const response = await authFetch("/api/chat/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(project),+ });+ const saved = await parseJsonOrThrow<ProjectRecord>(response);+ notifyChatHistoryUpdated();+ return saved;+}++export async function updateChatProject(+ projectId: string,+ patch: Partial<ProjectRecord>,+): Promise<ProjectRecord> {+ const response = await authFetch(+ `/api/chat/projects/${encodeURIComponent(projectId)}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ },+ );+ const project = await parseJsonOrThrow<ProjectRecord>(response);+ notifyChatHistoryUpdated();+ return project;+}++export async function deleteChatProject(+ projectId: string,+ args: { deleteFiles?: boolean } = {},+): Promise<void> {+ const params = new URLSearchParams();+ if (args.deleteFiles) params.set("delete_files", "true");+ const qs = params.toString();+ const response = await authFetch(+ `/api/chat/projects/${encodeURIComponent(projectId)}${qs ? `?${qs}` : ""}`,+ { method: "DELETE" },+ );+ await parseJsonOrThrow<ProjectRecord>(response);+ notifyChatHistoryUpdated();+}+export async function listChatMessages(threadId: string,): Promise<MessageRecord[]> {@@ -464,6 +539,7 @@ export async function buildBackendChatExport(): Promise<{exportedAt: string;version: number;threadCount: number;+ projects?: ProjectRecord[];threads: ThreadRecord[];messages: MessageRecord[];}> {diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex f727b3dfd32..d793b7697bd 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -9,13 +9,14 @@ import {type ModelOption,ModelSelector,} from "@/components/assistant-ui/model-selector";-import { Thread } from "@/components/assistant-ui/thread";+import { ProjectComposer, Thread } from "@/components/assistant-ui/thread";import {ResizableHandle,ResizablePanel,ResizablePanelGroup,} from "@/components/ui/resizable";import { useSidebar } from "@/components/ui/sidebar";+import { Button } from "@/components/ui/button";import { Tooltip, TooltipContent } from "@/components/ui/tooltip";import {NativeModelChip,@@ -29,12 +30,17 @@ import {import { GuidedTour, useGuidedTourController } from "@/features/tour";import { isTauri } from "@/lib/api-base";import { cn } from "@/lib/utils";-import { CustomizeIcon } from "@hugeicons/core-free-icons";+import {+ Folder02Icon,+ FolderAddIcon,+ LayoutAlignRightIcon,+} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { useNavigate, useSearch } from "@tanstack/react-router";+import { useNavigate, useRouterState, useSearch } from "@tanstack/react-router";import { Tooltip as TooltipPrimitive } from "radix-ui";import type { PanelImperativeHandle } from "react-resizable-panels";import {+ type CSSProperties,type ReactElement,memo,useCallback,@@ -49,12 +55,18 @@ import { ChatSettingsPanel } from "./chat-settings-sheet";import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";import { ContextUsageBar } from "./components/context-usage-bar";import { ModelLoadInlineStatus } from "./components/model-load-status";+import { ProjectSwitcher } from "./components/project-switcher";import {buildExternalModelId,isExternalModelId,parseExternalModelId,} from "./external-providers";import { useChatModelRuntime } from "./hooks/use-chat-model-runtime";+import { useChatProjects } from "./hooks/use-chat-projects";+import {+ type SidebarItem,+ useChatSidebarItems,+} from "./hooks/use-chat-sidebar-items";import {clearTrainingCompareHandoff,getTrainingCompareHandoff,@@ -181,12 +193,14 @@ const ARTIFACT_SURFACE_POP_DELAY_MS = 150;const SingleContent = memo(function SingleContent({threadId,newThreadNonce,+ projectId,artifact,artifactSurface,onCloseArtifact,}: {threadId?: string;newThreadNonce?: string;+ projectId?: string | null;artifact?: ChatArtifact | null;artifactSurface: ChatArtifactSurface;onCloseArtifact: () => void;@@ -272,6 +286,8 @@ const SingleContent = memo(function SingleContent({modelType="base"initialThreadId={threadId}newThreadNonce={newThreadNonce}+ projectId={projectId}+ listThreads={false}><ResizablePanelGrouporientation="horizontal"@@ -365,6 +381,7 @@ function useIsLoraCompare(): boolean {const CompareContent = memo(function CompareContent({pairId,+ projectId,models,loraModels,externalModels,@@ -373,6 +390,7 @@ const CompareContent = memo(function CompareContent({deleteDisabled,}: {pairId: string;+ projectId?: string | null;models: ModelOption[];loraModels: LoraModelOption[];externalModels: ExternalModelOption[];@@ -383,10 +401,11 @@ const CompareContent = memo(function CompareContent({const isLoraCompare = useIsLoraCompare();return isLoraCompare ? (- <LoraCompareContent pairId={pairId} />+ <LoraCompareContent pairId={pairId} projectId={projectId} />) : (<GeneralCompareContentpairId={pairId}+ projectId={projectId}models={models}loraModels={loraModels}externalModels={externalModels}@@ -411,6 +430,7 @@ const CompareContent = memo(function CompareContent({function ComparePane({modelType,pairId,+ projectId,initialThreadId,handleName,header,@@ -418,6 +438,7 @@ function ComparePane({}: {modelType: "base" | "lora" | "model1" | "model2";pairId: string;+ projectId?: string | null;initialThreadId: string | undefined;handleName: string;header: ReactElement;@@ -435,6 +456,7 @@ function ComparePane({<ChatRuntimeProvidermodelType={modelType}pairId={pairId}+ projectId={projectId}initialThreadId={initialThreadId}syncActiveThreadId={false}>@@ -490,7 +512,8 @@ function CompareShell({/** Fast path: same model, adapter on/off, simultaneous generation. */const LoraCompareContent = memo(function LoraCompareContent({pairId,-}: { pairId: string }): ReactElement {+ projectId,+}: { pairId: string; projectId?: string | null }): ReactElement {const handlesRef = useRef<Record<string, CompareHandle>>({});const [baseThreadId, setBaseThreadId] = useState<string>();const [loraThreadId, setLoraThreadId] = useState<string>();@@ -522,6 +545,7 @@ const LoraCompareContent = memo(function LoraCompareContent({<ComparePanemodelType="base"pairId={pairId}+ projectId={projectId}initialThreadId={baseThreadId}handleName="base"header={@@ -535,6 +559,7 @@ const LoraCompareContent = memo(function LoraCompareContent({<ComparePanemodelType="lora"pairId={pairId}+ projectId={projectId}initialThreadId={loraThreadId}handleName="lora"borderClassName="border-t border-border/60 md:border-t-0 md:border-l"@@ -607,6 +632,7 @@ function GeneralCompareHeader({/** General path: any two models, sequential load → generate. */const GeneralCompareContent = memo(function GeneralCompareContent({pairId,+ projectId,models,loraModels,externalModels,@@ -615,6 +641,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({deleteDisabled,}: {pairId: string;+ projectId?: string | null;models: ModelOption[];loraModels: LoraModelOption[];externalModels: ExternalModelOption[];@@ -692,6 +719,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({<ComparePanemodelType="model1"pairId={pairId}+ projectId={projectId}initialThreadId={model1ThreadId}handleName="model1"header={@@ -717,6 +745,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({<ComparePanemodelType="model2"pairId={pairId}+ projectId={projectId}initialThreadId={model2ThreadId}handleName="model2"borderClassName="border-t border-sidebar-border md:border-t-0 md:border-l"@@ -745,9 +774,248 @@ const GeneralCompareContent = memo(function GeneralCompareContent({);});+function formatProjectChatDate(timestamp: number): string {+ return new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ }).format(new Date(timestamp));+}++function extractMessageText(content: MessageRecord["content"]): string {+ if (typeof content === "string") {+ return content;+ }+ if (!Array.isArray(content)) {+ return "";+ }+ return content+ .map((part) => {+ if (part.type === "text") {+ return part.text;+ }+ if (part.type === "image") {+ return "Image";+ }+ if (part.type === "audio") {+ return "Audio";+ }+ return "";+ })+ .filter(Boolean)+ .join(" ");+}++function ProjectLanding({+ projectId,+ projectName,+ items,+}: {+ projectId: string;+ projectName: string;+ items: SidebarItem[];+}): ReactElement {+ const navigate = useNavigate();+ const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);+ const initialActiveThreadRef = useRef<string | null>(null);+ const [projectTab, setProjectTab] = useState<"chats" | "sources">("chats");+ const [pendingNewThreadId, setPendingNewThreadId] = useState<string | null>(+ null,+ );+ const [newThreadNonce, setNewThreadNonce] = useState(() =>+ crypto.randomUUID(),+ );+ const [previews, setPreviews] = useState<+ Record<string, { snippet: string; date: string }>+ >({});++ useEffect(() => {+ initialActiveThreadRef.current =+ useChatRuntimeStore.getState().activeThreadId;+ useChatRuntimeStore.getState().setActiveThreadId(null);+ useChatRuntimeStore.getState().setContextUsage(null);+ setPendingNewThreadId(null);+ setNewThreadNonce(crypto.randomUUID());+ }, [projectId]);++ useEffect(() => {+ if (!activeThreadId) {+ setPendingNewThreadId(null);+ return;+ }+ if (activeThreadId === initialActiveThreadRef.current) {+ return;+ }+ setPendingNewThreadId(activeThreadId);+ }, [activeThreadId]);++ useEffect(() => {+ let cancelled = false;++ async function loadPreviews(): Promise<void> {+ const entries = await Promise.all(+ items.map(async (item) => {+ if (item.type !== "single") {+ return [+ item.id,+ {+ snippet: "Compare chat",+ date: formatProjectChatDate(item.createdAt),+ },+ ] as const;+ }+ const messages = await listStoredChatMessages(item.id).catch(() => []);+ const firstUserMessage =+ messages.find((message) => message.role === "user") ?? messages[0];+ return [+ item.id,+ {+ snippet: firstUserMessage+ ? extractMessageText(firstUserMessage.content)+ : "",+ date: formatProjectChatDate(item.createdAt),+ },+ ] as const;+ }),+ );+ if (!cancelled) {+ setPreviews(Object.fromEntries(entries));+ }+ }++ void loadPreviews();+ return () => {+ cancelled = true;+ };+ }, [items]);++ return (+ <ChatRuntimeProvider+ key={projectId}+ projectId={projectId}+ newThreadNonce={newThreadNonce}+ listThreads={false}+ >+ {pendingNewThreadId ? (+ <div className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">+ <Thread hideWelcome={true} targetThreadId={pendingNewThreadId} />+ </div>+ ) : (+ <div+ className="flex min-h-0 min-w-0 flex-1 basis-0 overflow-y-auto px-5"+ style={+ {+ ["--thread-max-width" as string]: "48rem",+ } as CSSProperties+ }+ >+ <div className="mx-auto flex w-full max-w-[48rem] flex-col pt-[120px] pb-14">+ <div className="mb-12 flex items-center gap-3">+ <HugeiconsIcon+ icon={Folder02Icon}+ strokeWidth={1.75}+ className="size-9 shrink-0 text-foreground"+ />+ <h1 className="truncate font-sans text-[30px] font-medium leading-tight tracking-normal text-foreground">+ {projectName}+ </h1>+ </div>++ <ProjectComposer+ disabled={Boolean(pendingNewThreadId)}+ placeholder={`New chat in ${projectName}`}+ />++ <div className="mt-9 flex items-center gap-2">+ <button+ type="button"+ onClick={() => setProjectTab("chats")}+ data-active={projectTab === "chats"}+ className="h-10 rounded-full border px-5 text-[14px] font-semibold transition-colors data-[active=true]:border-border data-[active=true]:bg-muted data-[active=true]:text-foreground data-[active=false]:border-transparent data-[active=false]:text-muted-foreground data-[active=false]:hover:bg-nav-surface-hover"+ >+ Chats+ </button>+ <button+ type="button"+ onClick={() => setProjectTab("sources")}+ data-active={projectTab === "sources"}+ className="h-10 rounded-full border px-5 text-[14px] font-semibold transition-colors data-[active=true]:border-border data-[active=true]:bg-muted data-[active=true]:text-foreground data-[active=false]:border-transparent data-[active=false]:text-muted-foreground data-[active=false]:hover:bg-nav-surface-hover"+ >+ Sources+ </button>+ </div>++ {projectTab === "sources" ? (+ <div className="mt-8 flex flex-col items-center justify-center gap-3 rounded-[16px] border border-dashed border-border/70 bg-muted/30 px-6 py-16 text-center">+ <span className="flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">+ <HugeiconsIcon+ icon={FolderAddIcon}+ strokeWidth={1.75}+ className="size-6"+ />+ </span>+ <div className="space-y-1">+ <p className="text-[15px] font-semibold text-foreground">+ Give this project context+ </p>+ <p className="max-w-sm text-sm text-muted-foreground">+ Upload PDFs, documents, or other text. The model can+ reference them in every chat in this project.+ </p>+ </div>+ <Button type="button" className="mt-1" disabled>+ Add sources+ </Button>+ <p className="text-[11px] text-muted-foreground">Coming soon</p>+ </div>+ ) : (+ <div className="mt-8 flex flex-col gap-1">+ {items.map((item) => {+ const preview = previews[item.id];+ return (+ <button+ key={`${item.type}:${item.id}`}+ type="button"+ onClick={() => {+ navigate({+ to: "/chat",+ search:+ item.type === "single"+ ? { thread: item.id, project: projectId }+ : { compare: item.id, project: projectId },+ });+ }}+ className="group flex min-h-[58px] w-full items-center gap-4 rounded-[10px] px-4 py-2 text-left transition-colors hover:bg-nav-surface-hover"+ >+ <div className="min-w-0 flex-1">+ <div className="truncate text-[15px] font-semibold leading-5 text-foreground">+ {item.title}+ </div>+ {preview?.snippet ? (+ <div className="mt-0.5 truncate text-[14px] leading-5 text-muted-foreground">+ {preview.snippet}+ </div>+ ) : null}+ </div>+ <span className="shrink-0 text-[14px] text-muted-foreground">+ {preview?.date ?? formatProjectChatDate(item.createdAt)}+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>+ )}+ </ChatRuntimeProvider>+ );+}+export function ChatPage(): ReactElement {const search = useSearch({ from: "/chat" });const navigate = useNavigate();+ const pathname = useRouterState({ select: (s) => s.location.pathname });+ const isCurrentChatRoute = pathname.startsWith("/chat");const settingsOpen = useChatRuntimeStore((s) => s.settingsPanelOpen);const setSettingsOpen = useChatRuntimeStore((s) => s.setSettingsPanelOpen);@@ -779,7 +1047,9 @@ export function ChatPage(): ReactElement {});navigate({to: "/chat",- search: { new: crypto.randomUUID() },+ search: search.project+ ? { project: search.project }+ : { new: crypto.randomUUID() },replace: true,});})@@ -813,6 +1083,30 @@ export function ChatPage(): ReactElement {const clearCheckpoint = useChatRuntimeStore((state) => state.clearCheckpoint);const resetArtifacts = useChatArtifactsStore((state) => state.resetArtifacts);const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);+ const [currentProjectId, setCurrentProjectId] = useState<string | null>(+ search.project ?? null,+ );+ const { projects, isLoading: projectsLoading } = useChatProjects();+ const currentProject = currentProjectId+ ? (projects.find((project) => project.id === currentProjectId) ?? null)+ : null;+ const { items: currentProjectItems } = useChatSidebarItems({+ projectId: currentProjectId ?? "__no_project_selected__",+ });+ const currentChatTitle = activeThreadId+ ? currentProjectItems.find((item) => item.id === activeThreadId)?.title+ : undefined;+ const openProjectLanding = useCallback(+ (projectId: string) => {+ useChatRuntimeStore.getState().setActiveThreadId(null);+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ navigate({ to: "/chat", search: { project: projectId } });+ },+ [navigate],+ );+ const openProjectsList = useCallback(() => {+ navigate({ to: "/projects" });+ }, [navigate]);const persistedActiveThreadId = isAssistantLocalThreadId(activeThreadId)? null: activeThreadId;@@ -1053,25 +1347,94 @@ export function ChatPage(): ReactElement {return Boolean(inferenceParams.checkpoint) && !isExternalModel;}, [inferenceParams.checkpoint, isExternalModel]);+ useEffect(() => {+ let canceled = false;++ async function resolveProjectId(): Promise<void> {+ if (search.project) {+ setCurrentProjectId(search.project);+ useChatRuntimeStore.getState().setActiveProjectId(search.project);+ return;+ }++ if (search.thread) {+ const thread = await getStoredChatThread(search.thread).catch(() => null);+ if (!canceled) {+ const projectId = thread?.projectId ?? null;+ setCurrentProjectId(projectId);+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ }+ return;+ }++ if (search.compare) {+ const threads = await listStoredChatThreads({+ pairId: search.compare,+ includeArchived: true,+ }).catch(() => []);+ if (!canceled) {+ const projectId = threads[0]?.projectId ?? null;+ setCurrentProjectId(projectId);+ useChatRuntimeStore.getState().setActiveProjectId(projectId);+ }+ return;+ }++ setCurrentProjectId(null);+ useChatRuntimeStore.getState().setActiveProjectId(null);+ }++ void resolveProjectId();+ return () => {+ canceled = true;+ };+ }, [search.compare, search.project, search.thread]);+// Derive view from URL search paramsconst view = useMemo<ChatView>(() => {if (search.compare) {return {mode: "compare",pairId: search.compare,+ projectId: currentProjectId,};}if (search.thread) {- return { mode: "single", threadId: search.thread };- }- if (persistedActiveThreadId) {- return { mode: "single", threadId: persistedActiveThreadId };+ return {+ mode: "single",+ threadId: search.thread,+ projectId: currentProjectId,+ };}if (search.new) {- return { mode: "single", newThreadNonce: search.new };+ return {+ mode: "single",+ newThreadNonce: search.new,+ projectId: currentProjectId,+ };+ }+ if (search.project) {+ return {+ mode: "project",+ projectId: search.project,+ };+ }+ if (persistedActiveThreadId) {+ return {+ mode: "single",+ threadId: persistedActiveThreadId,+ projectId: currentProjectId,+ };}- return { mode: "single" };- }, [search.thread, search.compare, search.new, persistedActiveThreadId]);+ return { mode: "single", projectId: currentProjectId };+ }, [+ search.thread,+ search.compare,+ search.new,+ search.project,+ persistedActiveThreadId,+ currentProjectId,+ ]);const selectedArtifact = useSelectedChatArtifact();const artifactSurface = useChatArtifactsStore((state) => state.surface);@@ -1081,7 +1444,9 @@ export function ChatPage(): ReactElement {const artifactViewKey =view.mode === "single"? `single:${view.threadId ?? view.newThreadNonce ?? "new"}`- : `compare:${view.pairId}`;+ : view.mode === "compare"+ ? `compare:${view.pairId}`+ : `project:${view.projectId}`;useEffect(() => {clearAutoOpenedArtifacts();@@ -1410,8 +1775,14 @@ export function ChatPage(): ReactElement {viewBeforeCompareRef.current = { ...search };useChatRuntimeStore.getState().setActiveThreadId(null);useChatRuntimeStore.getState().setContextUsage(null);- navigate({ to: "/chat", search: { compare: crypto.randomUUID() } });- }, [navigate, search]);+ navigate({+ to: "/chat",+ search: {+ compare: crypto.randomUUID(),+ ...(currentProjectId ? { project: currentProjectId } : {}),+ },+ });+ }, [currentProjectId, navigate, search]);const exitCompare = useCallback(() => {const saved = viewBeforeCompareRef.current;@@ -1703,11 +2074,25 @@ export function ChatPage(): ReactElement {(view.mode === "compare" || artifactSurface === "overlay"),);+ if (!isCurrentChatRoute) {+ return (+ <div className="flex min-h-0 min-w-0 flex-1 basis-0 bg-background" />+ );+ }+return (<div className="flex min-h-0 min-w-0 flex-1 basis-0 bg-background overflow-hidden"><GuidedTour {...tour.tourProps} /><div className="relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"><NativeModelDropOverlay state={nativeModelDropState} />+ {/* Bottom fade under the top bar so messages dissolve as they scroll+ beneath it (Gemini / unsloth-sidebar style), instead of a hard cut. */}+ {view.mode !== "compare" && (+ <div+ aria-hidden+ className="pointer-events-none absolute left-0 right-[10px] top-[48px] z-20 h-6 bg-gradient-to-b from-background to-transparent"+ />+ )}<divclassName={cn("absolute top-0 left-0 right-[10px] z-30 flex h-[48px] shrink-0 items-start pt-[11px] pr-2 bg-background",@@ -1739,6 +2124,30 @@ export function ChatPage(): ReactElement {className="max-w-[62vw] !pr-3 sm:max-w-none !h-[34px]"/>)}+ {view.mode !== "compare" && currentProjectId && (+ <nav+ aria-label="Project location"+ className="flex h-[34px] min-w-0 items-center gap-1.5 self-center text-[13.5px] tracking-nav text-muted-foreground"+ >+ <ProjectSwitcher+ currentProject={currentProject}+ projects={projects}+ isLoading={projectsLoading}+ onSelectProject={openProjectLanding}+ onViewAllProjects={openProjectsList}+ />+ {currentProject && activeThreadId ? (+ <>+ <span className="shrink-0" aria-hidden>+ /+ </span>+ <span className="min-w-0 truncate">+ {currentChatTitle ?? "New chat"}+ </span>+ </>+ ) : null}+ </nav>+ )}{pendingNativeModelIntent && view.mode !== "compare" ? (<NativeModelChipintent={pendingNativeModelIntent}@@ -1796,12 +2205,12 @@ export function ChatPage(): ReactElement {<buttontype="button"onClick={() => setSettingsOpen(true)}- className="flex h-[34px] w-[34px] items-center justify-center rounded-[12px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- aria-label="Open configuration"+ className="flex h-[34px] w-[34px] translate-x-[2px] cursor-pointer items-center justify-center rounded-[12px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label="Open run settings"data-tour="chat-settings"><HugeiconsIcon- icon={CustomizeIcon}+ icon={LayoutAlignRightIcon}strokeWidth={1.75}className="size-icon"/>@@ -1812,18 +2221,26 @@ export function ChatPage(): ReactElement {sideOffset={6}className="tooltip-compact">- Open configuration+ Open run settings</TooltipContent></Tooltip>)}</div></div>- {view.mode === "single" ? (+ {view.mode === "project" ? (+ <ProjectLanding+ key={view.projectId}+ projectId={view.projectId}+ projectName={currentProject?.name ?? "Project"}+ items={currentProjectItems}+ />+ ) : view.mode === "single" ? (<SingleContentkey={view.threadId ?? view.newThreadNonce ?? "single"}threadId={view.threadId}newThreadNonce={view.newThreadNonce}+ projectId={view.projectId}artifact={selectedArtifact}artifactSurface={artifactSurface}onCloseArtifact={closeArtifactSurface}@@ -1832,6 +2249,7 @@ export function ChatPage(): ReactElement {<CompareContentkey={view.pairId}pairId={view.pairId}+ projectId={view.projectId}models={models}loraModels={loraModels}externalModels={externalModels}diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex a6e42d18fc8..90c2185db3a 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -58,7 +58,7 @@ import {LayoutAlignRightIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { ChevronDown } from "lucide-react";+import { ChevronDown, ExternalLink } from "lucide-react";import { Tooltip as TooltipPrimitive } from "radix-ui";import { Fragment, type ReactNode } from "react";import { useEffect, useMemo, useRef, useState } from "react";@@ -324,11 +324,19 @@ function saveCollapsibleOpen(label: string, open: boolean) {function CollapsibleSection({label,+ labelHref,children,defaultOpen = false,first = false,}: {label: string;+ /**+ * When set, the label text becomes an external link (e.g. to the feature's+ * GitHub PR) instead of part of the collapse toggle. The chevron still+ * toggles open/close, so we render the two as siblings rather than nesting+ * an <a> inside the <button> (invalid HTML).+ */+ labelHref?: string;children?: ReactNode;defaultOpen?: boolean;first?: boolean;@@ -338,6 +346,17 @@ function CollapsibleSection({return Object.hasOwn(saved, label) ? saved[label] : defaultOpen;});+ const toggle = () => {+ const next = !open;+ setOpen(next);+ saveCollapsibleOpen(label, next);+ };++ const headerClasses = cn(+ "flex w-full items-center justify-between text-[12px] font-medium normal-case tracking-[0.04em] text-nav-fg-muted transition-colors focus-visible:outline-none focus-visible:ring-0",+ first ? "pt-4 pb-5" : "py-5",+ );+return (<divclassName={cn(@@ -345,25 +364,42 @@ function CollapsibleSection({"border-t border-black/[0.13] dark:border-white/[0.09]",)}>- <button- type="button"- onClick={() => {- const next = !open;- setOpen(next);- saveCollapsibleOpen(label, next);- }}- className={cn(- "flex w-full cursor-pointer items-center justify-between text-[12px] font-medium normal-case tracking-[0.04em] text-nav-fg-muted transition-colors hover:text-nav-fg focus-visible:outline-none focus-visible:ring-0",- first ? "pt-4 pb-5" : "py-5",- )}- >- <span className="leading-none">{label}</span>- <span className="flex shrink-0 items-center leading-none">- <ChevronDown- className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}- />- </span>- </button>+ {labelHref ? (+ <div className={headerClasses}>+ <a+ href={labelHref}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex cursor-pointer items-center gap-1 leading-none transition-colors hover:text-nav-fg"+ >+ <span>{label}</span>+ <ExternalLink className="size-3" />+ </a>+ <button+ type="button"+ onClick={toggle}+ aria-label={open ? `Collapse ${label}` : `Expand ${label}`}+ className="flex shrink-0 cursor-pointer items-center leading-none transition-colors hover:text-nav-fg"+ >+ <ChevronDown+ className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}+ />+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={toggle}+ className={cn("cursor-pointer hover:text-nav-fg", headerClasses)}+ >+ <span className="leading-none">{label}</span>+ <span className="flex shrink-0 items-center leading-none">+ <ChevronDown+ className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}+ />+ </span>+ </button>+ )}{open && <div className="pb-7">{children}</div>}</div>);@@ -683,26 +719,31 @@ export function ChatSettingsPanel({}}, [open]);+ const settingsScrollRef = useRef<HTMLDivElement>(null);+const settingsContent = (<>- <div className="aui-thread-viewport relative h-full overflow-y-auto">- <div className="sticky top-0 z-10 flex h-[48px] items-start gap-2 bg-panel-surface pl-[18px] pr-[14px] pt-[11px]">+ <div+ ref={settingsScrollRef}+ className="relative h-full overflow-y-auto"+ >+ <div className="sticky top-0 z-10 flex h-[48px] items-start gap-2 bg-panel-surface pl-[18px] pr-[16px] pt-[11px]">{isMobile ? (- <span className="flex h-[34px] flex-1 items-center text-[15px] font-semibold tracking-[-0.01em] dark:tracking-[0.015em] text-nav-fg">- Configuration+ <span className="flex h-[34px] flex-1 items-center text-[15px] font-semibold tracking-[0em] dark:tracking-[0.015em] text-nav-fg">+ Run settings</span>) : (<>- <span className="flex h-[34px] flex-1 items-center text-[15px] font-semibold tracking-[-0.01em] dark:tracking-[0.015em] text-nav-fg">- Configuration+ <span className="flex h-[34px] flex-1 items-center text-[15px] font-semibold tracking-[0em] dark:tracking-[0.015em] text-nav-fg">+ Run settings</span><Tooltip><TooltipPrimitive.Trigger asChild><buttontype="button"onClick={() => onOpenChange?.(false)}- className="flex h-[34px] w-[34px] items-center justify-center rounded-[12px] text-nav-icon-idle dark:text-nav-fg-muted transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- aria-label="Close configuration"+ className="flex h-[34px] w-[34px] cursor-pointer items-center justify-center rounded-[12px] text-nav-icon-idle dark:text-nav-fg-muted transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label="Close run settings"><HugeiconsIconicon={LayoutAlignRightIcon}@@ -716,7 +757,7 @@ export function ChatSettingsPanel({sideOffset={6}className="tooltip-compact">- Close configuration+ Close run settings</TooltipContent></Tooltip></>@@ -1395,7 +1436,7 @@ export function ChatSettingsPanel({<Sheet open={open} onOpenChange={onOpenChange}><SheetContent side="right" className="w-[18rem] p-0 font-heading"><SheetHeader className="sr-only">- <SheetTitle>Configuration</SheetTitle>+ <SheetTitle>Run settings</SheetTitle><SheetDescription>Chat inference settings</SheetDescription></SheetHeader><div className="flex h-full flex-col">{settingsContent}</div>diff --git a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx b/studio/frontend/src/features/chat/components/chat-search-dialog.tsxindex eca3b4bd9ff..85480359b4e 100644--- a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx+++ b/studio/frontend/src/features/chat/components/chat-search-dialog.tsx@@ -8,7 +8,6 @@ import {CommandGroup,CommandList,} from "@/components/ui/command";-import { useTrainingRuntimeStore } from "@/features/training";import { Cancel01Icon, Message01Icon, SearchIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate } from "@tanstack/react-router";@@ -36,7 +35,6 @@ export function ChatSearchDialog() {useEffect(() => {const handler = (e: KeyboardEvent) => {if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== "k") return;- if (useTrainingRuntimeStore.getState().isTrainingRunning) return;const el = document.activeElement as HTMLElement | null;const tag = el?.tagName;if (tag === "INPUT" || tag === "TEXTAREA" || el?.isContentEditable) return;@@ -51,10 +49,10 @@ export function ChatSearchDialog() {<CommandDialogopen={isOpen}onOpenChange={setOpen}- className="shadow-border corner-squircle w-[635px] max-w-[calc(100%-2rem)] gap-0 p-0 sm:max-w-[635px]"+ className="corner-squircle top-[25%] w-[635px] max-w-[calc(100%-2rem)] gap-0 p-0 sm:max-w-[635px] border-0 ring-0 shadow-[0_10px_34px_rgba(0,0,0,0.12)] dark:border dark:border-border dark:ring-0 dark:shadow-none"overlayClassName="bg-transparent">- <Command className="rounded-none p-0">+ <Command className="rounded-4xl p-0"><div className="flex items-center gap-3 border-b border-border/40 px-4 py-3"><HugeiconsIconicon={SearchIcon}@@ -74,7 +72,7 @@ export function ChatSearchDialog() {<HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} className="size-4" /></button></div>- <CommandList className="max-h-[420px] p-1">+ <CommandList className="cmd-native-scrollbar max-h-[420px] p-1"><CommandEmpty className="py-6 text-center text-xs text-muted-foreground">{loading? "Loading…"@@ -92,12 +90,18 @@ export function ChatSearchDialog() {to: "/chat",search:item.type === "single"- ? { thread: item.id }- : { compare: item.id },+ ? {+ thread: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ }+ : {+ compare: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ },});close();}}- className="relative flex cursor-default select-none items-center gap-3 rounded-lg px-3 py-2.5 text-sm outline-hidden data-selected:bg-muted data-selected:text-foreground"+ className="relative flex cursor-pointer select-none items-center gap-3 rounded-lg px-3 py-2.5 text-sm outline-hidden data-selected:bg-muted data-selected:text-foreground"><HugeiconsIconicon={Message01Icon}diff --git a/studio/frontend/src/features/chat/components/project-switcher.tsx b/studio/frontend/src/features/chat/components/project-switcher.tsxnew file mode 100644index 00000000000..3deaf4701d9--- /dev/null+++ b/studio/frontend/src/features/chat/components/project-switcher.tsx@@ -0,0 +1,120 @@+// 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 {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ ArrowDown01Icon,+ Folder01Icon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import type { ReactElement } from "react";+import type { ProjectRecord } from "../types";++export function ProjectSwitcher({+ currentProject,+ projects,+ isLoading,+ onSelectProject,+ onViewAllProjects,+}: {+ currentProject: ProjectRecord | null;+ projects: ProjectRecord[];+ isLoading: boolean;+ onSelectProject: (projectId: string) => void;+ onViewAllProjects: () => void;+}): ReactElement {+ const showLoadingRow = isLoading && projects.length === 0;+ const showEmptyRow = !isLoading && projects.length === 0;+ const label = currentProject?.name ?? (isLoading ? "Project" : "Projects");++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <button+ type="button"+ aria-label={+ currentProject+ ? `Project: ${currentProject.name}. Switch project`+ : isLoading+ ? "Loading project"+ : "Pick a project"+ }+ className="-mx-1 flex h-[34px] shrink-0 items-center gap-2 rounded-[10px] px-1.5 transition-colors hover:bg-[#ececec] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:hover:bg-[#2d2e32]"+ >+ <HugeiconsIcon+ icon={Folder01Icon}+ strokeWidth={1.75}+ className="size-icon shrink-0 text-foreground/70"+ />+ <span className="flex min-w-0 flex-1 items-baseline">+ <span className="min-w-0 flex max-w-[150px] flex-1 items-baseline truncate font-heading text-[16px] font-medium leading-tight text-black dark:text-white">+ {label}+ </span>+ </span>+ <span className="flex size-4 shrink-0 items-center justify-center">+ <HugeiconsIcon+ icon={ArrowDown01Icon}+ strokeWidth={1.75}+ className="relative top-0.5 size-3.5 text-muted-foreground"+ aria-hidden={true}+ />+ </span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="bottom"+ align="start"+ sideOffset={6}+ className="app-user-menu menu-soft-surface ring-0 min-w-56 max-w-72 max-h-72 py-2 font-heading rounded-[14px] border-0"+ >+ {showLoadingRow ? (+ <DropdownMenuItem disabled={true} className="text-muted-foreground">+ Loading…+ </DropdownMenuItem>+ ) : null}+ {showEmptyRow ? (+ <DropdownMenuItem disabled={true} className="text-muted-foreground">+ No projects yet+ </DropdownMenuItem>+ ) : null}+ {projects.map((project) => {+ const isActive = currentProject?.id === project.id;+ return (+ <DropdownMenuItem+ key={project.id}+ onSelect={() => onSelectProject(project.id)}+ className="justify-between"+ >+ <span className="flex min-w-0 items-center gap-2">+ <HugeiconsIcon+ icon={Folder01Icon}+ strokeWidth={1.75}+ className="size-icon shrink-0 text-foreground/70"+ />+ <span className="truncate">{project.name}</span>+ </span>+ {isActive ? (+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className="size-icon shrink-0 text-foreground/80"+ />+ ) : null}+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={onViewAllProjects}>+ View all projects+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts b/studio/frontend/src/features/chat/hooks/use-chat-projects.tsnew file mode 100644index 00000000000..fe0dfa9e659--- /dev/null+++ b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts@@ -0,0 +1,97 @@+// 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 { useEffect, useState } from "react";+import { CHAT_HISTORY_UPDATED_EVENT } from "../api/chat-api";+import type { ProjectRecord } from "../types";+import {+ createStoredChatProject,+ deleteStoredChatProject,+ isExpectedBackgroundChatStorageError,+ listStoredChatProjects,+ moveStoredChatItemToProject,+ updateStoredChatProject,+} from "../utils/chat-history-storage";+import type { SidebarItem } from "./use-chat-sidebar-items";++let cachedProjects: ProjectRecord[] = [];++export function useChatProjects(): {+ projects: ProjectRecord[];+ isLoading: boolean;+ hasLoaded: boolean;+} {+ const [projects, setProjects] = useState<ProjectRecord[]>(cachedProjects);+ const [isLoading, setIsLoading] = useState(cachedProjects.length === 0);+ const [hasLoaded, setHasLoaded] = useState(cachedProjects.length > 0);++ useEffect(() => {+ let cancelled = false;++ async function load() {+ if (!cancelled) setIsLoading(true);+ try {+ const next = await listStoredChatProjects({ includeArchived: false });+ cachedProjects = next;+ if (!cancelled) setProjects(next);+ } catch (error) {+ if (isExpectedBackgroundChatStorageError(error)) {+ return;+ }+ if (!cancelled) throw error;+ } finally {+ if (!cancelled) {+ setHasLoaded(true);+ setIsLoading(false);+ }+ }+ }++ const onHistoryUpdated = () => {+ void load();+ };++ void load();+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);+ return () => {+ cancelled = true;+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);+ };+ }, []);++ return { projects, isLoading, hasLoaded };+}++export async function createChatProject(name: string): Promise<ProjectRecord> {+ return createStoredChatProject(name);+}++export async function renameChatProject(+ projectId: string,+ name: string,+): Promise<void> {+ const trimmed = name.trim();+ if (!trimmed) throw new Error("Project name is required.");+ await updateStoredChatProject(projectId, { name: trimmed });+}++export async function updateChatProjectInstructions(+ projectId: string,+ instructions: string,+): Promise<void> {+ await updateStoredChatProject(projectId, { instructions: instructions.trim() });+}++export async function deleteChatProject(+ projectId: string,+ args: { deleteFiles?: boolean } = {},+): Promise<void> {+ await deleteStoredChatProject(projectId, args);+}++export async function moveChatItemToProject(+ item: SidebarItem,+ projectId: string | null,+): Promise<void> {+ await moveStoredChatItemToProject(item, projectId);+}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts b/studio/frontend/src/features/chat/hooks/use-chat-search-index.tsindex 9fecf999864..f8e1535e049 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useEffect, useRef, useState } from "react";-import { CHAT_HISTORY_UPDATED_EVENT } from "../api/chat-api";+import { batchListChatMessages, CHAT_HISTORY_UPDATED_EVENT } from "../api/chat-api";import type { MessageRecord } from "../types";import {listStoredChatMessages,@@ -15,6 +15,7 @@ export interface ChatSearchItem {title: string;preview: string;createdAt: number;+ projectId?: string | null;}const THREAD_LIMIT = 200;@@ -68,6 +69,7 @@ async function buildIndex(): Promise<ChatSearchItem[]> {id: t.pairId,title: t.title,createdAt: t.createdAt,+ projectId: t.projectId ?? null,},threadIds: [t.id],});@@ -78,6 +80,7 @@ async function buildIndex(): Promise<ChatSearchItem[]> {id: t.id,title: t.title,createdAt: t.createdAt,+ projectId: t.projectId ?? null,},threadIds: [t.id],});@@ -87,26 +90,34 @@ async function buildIndex(): Promise<ChatSearchItem[]> {const allThreadIds = Array.from(itemThreadIds.values()).flatMap((e) => e.threadIds,);- const storedMessagesByThread = await Promise.all(- allThreadIds.map(async (threadId) => ({- threadId,- messages: await listStoredChatMessages(threadId),- })),+ let messagesByThread = await batchListChatMessages(allThreadIds).catch(+ () => new Map<string, MessageRecord[]>(),);- const messages = storedMessagesByThread.flatMap((entry) => entry.messages);- const byThreadId = new Map<string, MessageRecord[]>();- for (const m of messages) {- const arr = byThreadId.get(m.threadId);- if (arr) arr.push(m);- else byThreadId.set(m.threadId, [m]);+ // Legacy-only chats can exist before server-side history import finishes.+ // Fill just the missing ids from the legacy-aware path instead of issuing+ // one request per thread up front.+ const missingThreadIds = allThreadIds.filter(+ (threadId) => !messagesByThread.has(threadId),+ );+ if (missingThreadIds.length > 0) {+ const legacyEntries = await Promise.all(+ missingThreadIds.map(async (threadId) => [+ threadId,+ await listStoredChatMessages(threadId).catch(() => []),+ ] as const),+ );+ messagesByThread = new Map(messagesByThread);+ for (const [threadId, messages] of legacyEntries) {+ messagesByThread.set(threadId, messages);+ }}const results: ChatSearchItem[] = [];for (const { item, threadIds } of itemThreadIds.values()) {const merged: MessageRecord[] = [];for (const tid of threadIds) {- const arr = byThreadId.get(tid);+ const arr = messagesByThread.get(tid);if (arr) merged.push(...arr);}if (merged.length === 0) {@@ -141,6 +152,7 @@ export function useChatSearchIndex(enabled: boolean): {if (!enabled) {// Clear stale results so the next open doesn't flash old items.setItems([]);+ setLoading(false);return;}let cancelled = false;diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.tsindex 87a32dcd36a..54aa5d82dc0 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts@@ -24,6 +24,7 @@ export interface SidebarItem {id: string;title: string;createdAt: number;+ projectId?: string | null;}export function groupThreads(threads: ThreadRecord[]): SidebarItem[] {@@ -44,6 +45,7 @@ export function groupThreads(threads: ThreadRecord[]): SidebarItem[] {id: t.pairId,title: t.title,createdAt: t.createdAt,+ projectId: t.projectId ?? null,});} else if (!t.pairId) {items.push({@@ -51,6 +53,7 @@ export function groupThreads(threads: ThreadRecord[]): SidebarItem[] {id: t.id,title: t.title,createdAt: t.createdAt,+ projectId: t.projectId ?? null,});}}@@ -63,18 +66,32 @@ export function groupThreads(threads: ThreadRecord[]): SidebarItem[] {// discards stale responses.const SIDEBAR_REFRESH_DEBOUNCE_MS = 300;-export function useChatSidebarItems() {+export function useChatSidebarItems(options?: {+ projectId?: string | null;+ enabled?: boolean;+ requireMessages?: boolean;+}) {const [allThreads, setAllThreads] = useState<ThreadRecord[]>([]);+ const enabled = options?.enabled ?? true;+ const requireMessages = options?.requireMessages ?? true;useEffect(() => {+ if (!enabled) {+ return;+ }+let cancelled = false;let pendingTimer: ReturnType<typeof setTimeout> | null = null;let requestSeq = 0;async function doLoad(seq: number) {try {- const threads = await listStoredChatThreadsWithMessages({+ const listThreads = requireMessages+ ? listStoredChatThreadsWithMessages+ : listStoredChatThreads;+ const threads = await listThreads({includeArchived: false,+ projectId: options?.projectId,});// Discard the response if a newer request was scheduled while we// were in flight, or if the effect was torn down.@@ -107,7 +124,7 @@ export function useChatSidebarItems() {if (pendingTimer !== null) clearTimeout(pendingTimer);window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, load);};- }, []);+ }, [enabled, options?.projectId, requireMessages]);const items = groupThreads(allThreads ?? []);const canCompare = useChatRuntimeStore((s) => Boolean(s.params.checkpoint));diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 063def91aeb..ac05c8c089a 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -21,6 +21,7 @@ export { useChatSearchStore } from "./stores/chat-search-store";export { useChatModelRuntime } from "./hooks/use-chat-model-runtime";export { ChatSearchDialog } from "./components/chat-search-dialog";export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";+export type { ProjectRecord } from "./types";export { clearAllChats, countAllChats } from "./utils/clear-all-chats";export { ArtifactCard } from "./artifacts/artifact-card";export {@@ -34,3 +35,11 @@ export {useChatSidebarItems,type SidebarItem,} from "./hooks/use-chat-sidebar-items";+export {+ createChatProject,+ deleteChatProject,+ moveChatItemToProject,+ renameChatProject,+ updateChatProjectInstructions,+ useChatProjects,+} from "./hooks/use-chat-projects";diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsxnew file mode 100644index 00000000000..8c92526b63e--- /dev/null+++ b/studio/frontend/src/features/chat/projects-page.tsx@@ -0,0 +1,401 @@+// 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 {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { toast } from "@/lib/toast";+import {+ createChatProject,+ deleteChatProject,+ renameChatProject,+ useChatProjects,+ useChatRuntimeStore,+ type ProjectRecord,+} from "@/features/chat";+import {+ Delete02Icon,+ Edit03Icon,+ FolderAddIcon,+ Search01Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { MoreHorizontalIcon } from "lucide-react";+import { useNavigate } from "@tanstack/react-router";+import { useMemo, useState } from "react";++type SortMode = "activity" | "name";++function formatUpdatedAgo(ts: number): string {+ const diff = Date.now() - ts;+ if (!Number.isFinite(diff) || diff < 0) return "just now";+ const s = Math.floor(diff / 1000);+ if (s < 60) return "just now";+ const m = Math.floor(s / 60);+ if (m < 60) return `${m} minute${m === 1 ? "" : "s"} ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h} hour${h === 1 ? "" : "s"} ago`;+ const d = Math.floor(h / 24);+ if (d < 30) return `${d} day${d === 1 ? "" : "s"} ago`;+ const mo = Math.floor(d / 30);+ if (mo < 12) return `${mo} month${mo === 1 ? "" : "s"} ago`;+ const y = Math.floor(mo / 12);+ return `${y} year${y === 1 ? "" : "s"} ago`;+}++export function ProjectsPage() {+ const navigate = useNavigate();+ const { projects, hasLoaded } = useChatProjects();++ const [query, setQuery] = useState("");+ const [sortMode, setSortMode] = useState<SortMode>("activity");++ const [creating, setCreating] = useState(false);+ const [nameDraft, setNameDraft] = useState("");+ const [renaming, setRenaming] = useState<ProjectRecord | null>(null);+ const [renameDraft, setRenameDraft] = useState("");+ const [deleting, setDeleting] = useState<ProjectRecord | null>(null);++ const visibleProjects = useMemo(() => {+ const trimmed = query.trim().toLowerCase();+ const filtered = trimmed+ ? projects.filter((p) => p.name.toLowerCase().includes(trimmed))+ : projects.slice();+ filtered.sort((a, b) =>+ sortMode === "name"+ ? a.name.localeCompare(b.name)+ : b.updatedAt - a.updatedAt,+ );+ return filtered;+ }, [projects, query, sortMode]);++ function openProject(projectId: string) {+ const runtime = useChatRuntimeStore.getState();+ runtime.setActiveThreadId(null);+ runtime.setActiveProjectId(projectId);+ navigate({ to: "/chat", search: { project: projectId } });+ }++ async function commitCreate() {+ const name = nameDraft.trim();+ if (!name) return;+ try {+ const project = await createChatProject(name);+ setCreating(false);+ setNameDraft("");+ openProject(project.id);+ } catch (err) {+ toast.error("Failed to create project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ async function commitRename() {+ const target = renaming;+ const name = renameDraft.trim();+ if (!target || !name || name === target.name) {+ setRenaming(null);+ return;+ }+ setRenaming(null);+ try {+ await renameChatProject(target.id, name);+ } catch (err) {+ toast.error("Failed to rename project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ async function commitDelete() {+ const target = deleting;+ if (!target) return;+ setDeleting(null);+ try {+ await deleteChatProject(target.id);+ } catch (err) {+ toast.error("Failed to delete project", {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ return (+ <main className="mx-auto w-full max-w-7xl px-4 py-8 font-heading sm:px-6">+ <div className="flex flex-wrap items-center justify-between gap-4">+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">+ Projects+ </h1>+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-2">+ <span className="text-sm text-muted-foreground">Sort by</span>+ <Select+ value={sortMode}+ onValueChange={(v) => setSortMode(v as SortMode)}+ >+ <SelectTrigger className="h-9 w-[130px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="activity">Activity</SelectItem>+ <SelectItem value="name">Name</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <Button+ onClick={() => {+ setNameDraft("");+ setCreating(true);+ }}+ >+ New project+ </Button>+ </div>+ </div>++ <div className="relative mt-6">+ <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">+ <HugeiconsIcon icon={Search01Icon} strokeWidth={1.75} className="size-icon" />+ </span>+ <Input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search projects..."+ className="h-11 pl-10"+ aria-label="Search projects"+ />+ </div>++ {!hasLoaded ? (+ <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {Array.from({ length: 6 }).map((_, index) => (+ <div+ key={index}+ className="min-h-[160px] rounded-[14px] border border-border/70 bg-card p-5"+ >+ <Skeleton className="h-5 w-2/3 rounded-[6px]" />+ <Skeleton className="mt-3 h-4 w-full rounded-[6px]" />+ <Skeleton className="mt-2 h-4 w-4/5 rounded-[6px]" />+ <Skeleton className="mt-12 h-3 w-24 rounded-[6px]" />+ </div>+ ))}+ </div>+ ) : visibleProjects.length === 0 ? (+ <div className="mt-16 flex flex-col items-center justify-center gap-2 text-center text-muted-foreground">+ <p className="text-sm">+ {projects.length === 0+ ? "No projects yet."+ : "No projects match your search."}+ </p>+ {projects.length === 0 && (+ <Button+ variant="outline"+ className="mt-2"+ onClick={() => {+ setNameDraft("");+ setCreating(true);+ }}+ >+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />+ Create your first project+ </Button>+ )}+ </div>+ ) : (+ <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {visibleProjects.map((project) => (+ <div+ key={project.id}+ role="button"+ tabIndex={0}+ onClick={() => openProject(project.id)}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ openProject(project.id);+ }+ }}+ className="group/project-card relative flex min-h-[160px] cursor-pointer flex-col rounded-[14px] border border-border/70 bg-card p-5 text-left transition-colors hover:border-border hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <div className="flex items-start justify-between gap-2">+ <h2 className="truncate pr-2 text-[16px] font-semibold text-foreground">+ {project.name}+ </h2>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ onClick={(e) => e.stopPropagation()}+ aria-label="Project options"+ className="-mr-1 -mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-[8px] text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover/project-card:opacity-100"+ >+ <MoreHorizontalIcon strokeWidth={1.75} className="size-icon" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="bottom"+ align="end"+ sideOffset={4}+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-[14px] border-0"+ >+ <DropdownMenuItem+ onSelect={() => {+ setRenameDraft(project.name);+ setRenaming(project);+ }}+ >+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Rename</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setDeleting(project)}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ {project.instructions ? (+ <p className="mt-2 line-clamp-3 text-sm text-muted-foreground">+ {project.instructions}+ </p>+ ) : null}+ <span className="mt-auto pt-4 text-xs text-muted-foreground">+ Updated {formatUpdatedAgo(project.updatedAt)}+ </span>+ </div>+ ))}+ </div>+ )}++ {/* Create project */}+ <Dialog+ open={creating}+ onOpenChange={(open) => {+ if (!open) setCreating(false);+ }}+ >+ <DialogContent className="corner-squircle border border-border/60 bg-background/98 shadow-none sm:max-w-md">+ <DialogHeader>+ <DialogTitle>New project</DialogTitle>+ </DialogHeader>+ <Input+ value={nameDraft}+ onChange={(e) => setNameDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void commitCreate();+ }+ }}+ autoFocus+ maxLength={120}+ placeholder="Project name"+ aria-label="Project name"+ className="focus-visible:border-input focus-visible:ring-0"+ />+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">+ <Button type="button" variant="ghost" onClick={() => setCreating(false)}>+ Cancel+ </Button>+ <Button type="button" onClick={() => void commitCreate()} disabled={!nameDraft.trim()}>+ Create+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Rename project */}+ <Dialog+ open={renaming !== null}+ onOpenChange={(open) => {+ if (!open) setRenaming(null);+ }}+ >+ <DialogContent className="corner-squircle border border-border/60 bg-background/98 shadow-none sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Rename project</DialogTitle>+ </DialogHeader>+ <Input+ value={renameDraft}+ onChange={(e) => setRenameDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void commitRename();+ }+ }}+ autoFocus+ maxLength={120}+ placeholder="Project name"+ aria-label="Project name"+ className="focus-visible:border-input focus-visible:ring-0"+ />+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">+ <Button type="button" variant="ghost" onClick={() => setRenaming(null)}>+ Cancel+ </Button>+ <Button+ type="button"+ onClick={() => void commitRename()}+ disabled={!renameDraft.trim() || renameDraft.trim() === renaming?.name}+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Delete project */}+ <Dialog+ open={deleting !== null}+ onOpenChange={(open) => {+ if (!open) setDeleting(null);+ }}+ >+ <DialogContent className="menu-flat-destructive corner-squircle border border-border/60 bg-background/98 shadow-none sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Delete project</DialogTitle>+ </DialogHeader>+ <p className="text-sm text-muted-foreground">+ Are you sure you want to delete <em>{deleting?.name}</em>? Chats in this+ project will be moved back to Recents.+ </p>+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">+ <Button type="button" variant="ghost" onClick={() => setDeleting(null)}>+ Cancel+ </Button>+ <Button type="button" variant="destructive" onClick={() => void commitDelete()}>+ Delete+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </main>+ );+}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 21be5f6e3e3..32b591d8808 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -66,6 +66,7 @@ import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";import { getImageInputUnavailableReason } from "./utils/image-input-support";const pendingHistoryAppendByMessageId = new Map<string, Promise<void>>();+const pendingRunStartReadyByMessageId = new Map<string, Promise<void>>();type TitleResponse = {choices?: Array<{@@ -534,10 +535,12 @@ export async function ensureThreadRecord({threadId,modelType,pairId,+ projectId,}: {threadId: string;modelType: ModelType;pairId?: string;+ projectId?: string | null;}): Promise<void> {if (isChatThreadDeleted(threadId)) {return;@@ -556,6 +559,7 @@ export async function ensureThreadRecord({modelType,modelId: currentModelId,pairId,+ projectId: projectId ?? null,archived: false,createdAt: Date.now(),};@@ -579,6 +583,8 @@ export async function ensureThreadRecord({function createStudioDbAdapter(modelType: ModelType,pairId?: string,+ projectId?: string | null,+ listThreads = true,): unstable_RemoteThreadListAdapter {return {async fetch(remoteId: string) {@@ -594,9 +600,16 @@ function createStudioDbAdapter(},async list() {+ if (!listThreads) {+ return { threads: [] };+ }let threads: ThreadRecord[];try {- threads = await listStoredChatThreads({ modelType, pairId });+ threads = await listStoredChatThreads({+ modelType,+ pairId,+ ...(projectId !== undefined ? { projectId } : {}),+ });} catch (error) {if (!isExpectedBackgroundChatStorageError(error)) {throw error;@@ -615,7 +628,7 @@ function createStudioDbAdapter(},async initialize(threadId: string) {- await ensureThreadRecord({ threadId, modelType, pairId });+ await ensureThreadRecord({ threadId, modelType, pairId, projectId });return { remoteId: threadId, externalId: undefined };},@@ -696,7 +709,7 @@ function createStudioDbAdapter(const running = useChatRuntimeStore.getState().runningByThreadId;if (running[paired.id]) {setTimeout(() => {- void createStudioDbAdapter(modelType, pairId).generateTitle(+ void createStudioDbAdapter(modelType, pairId, projectId).generateTitle(remoteId,messages,);@@ -740,6 +753,22 @@ function trackHistoryAppend(return write;}+function trackRunStartReady(+ messageId: string,+ ready: Promise<void>,+): Promise<void> {+ pendingRunStartReadyByMessageId.set(messageId, ready);+ const cleanup = () => {+ setTimeout(() => {+ if (pendingRunStartReadyByMessageId.get(messageId) === ready) {+ pendingRunStartReadyByMessageId.delete(messageId);+ }+ }, 30_000);+ };+ ready.then(cleanup, cleanup);+ return ready;+}+async function waitForRunStartHistoryAppend(messages: Parameters<ChatModelAdapter["run"]>[0]["messages"],): Promise<void> {@@ -747,20 +776,22 @@ async function waitForRunStartHistoryAppend(if (!lastMessage || lastMessage.role !== "user") {return;}- const write = pendingHistoryAppendByMessageId.get(lastMessage.id);- if (!write) {+ const ready =+ pendingRunStartReadyByMessageId.get(lastMessage.id) ??+ pendingHistoryAppendByMessageId.get(lastMessage.id);+ if (!ready) {return;}- let didPersist = false;+ let didBecomeReady = false;try {- await write;- didPersist = true;+ await ready;+ didBecomeReady = true;} finally {if (- didPersist &&- pendingHistoryAppendByMessageId.get(lastMessage.id) === write+ didBecomeReady &&+ pendingRunStartReadyByMessageId.get(lastMessage.id) === ready) {- pendingHistoryAppendByMessageId.delete(lastMessage.id);+ pendingRunStartReadyByMessageId.delete(lastMessage.id);}}}@@ -783,7 +814,10 @@ function createPersistedRunAdapter(adapter: ChatModelAdapter): ChatModelAdapter};}-function useStudioRuntimeAdapters(): StudioRuntimeAdapters {+function useStudioRuntimeAdapters(+ modelType: ModelType,+ pairId?: string,+): StudioRuntimeAdapters {const aui = useAui();const history = useMemo<ThreadHistoryAdapter>(@@ -871,14 +905,22 @@ function useStudioRuntimeAdapters(): StudioRuntimeAdapters {},append({ parentId, message }: ExportedMessageRepositoryItem) {+ const initializeThread = aui.threadListItem().initialize();+ trackRunStartReady(message.id, initializeThread.then(() => undefined));const write = (async () => {- const { remoteId } = await aui.threadListItem().initialize();+ const { remoteId } = await initializeThread;if (isChatThreadDeleted(remoteId)) {await deleteStoredChatThreads([remoteId]);return;}// Keep single-chat runtime state in sync once a new chat is first// persisted. Compare panes intentionally do not write global activeThreadId.+ if (modelType === "base" && !pairId) {+ const store = useChatRuntimeStore.getState();+ if (store.activeThreadId !== remoteId) {+ store.setActiveThreadId(remoteId);+ }+ }const thread = await getStoredChatThread(remoteId);if (thread) {await ensureStoredChatThread(remoteId, thread);@@ -915,7 +957,7 @@ function useStudioRuntimeAdapters(): StudioRuntimeAdapters {return trackHistoryAppend(message.id, write);},}),- [aui],+ [aui, modelType, pairId],);const dictation = useMemo(@@ -947,8 +989,11 @@ function useStudioRuntimeAdapters(): StudioRuntimeAdapters {const chatAdapter = createOpenAIStreamAdapter();-function useRuntimeHook(): ReturnType<typeof useLocalRuntime> {- const adapters = useStudioRuntimeAdapters();+function useRuntimeHook(+ modelType: ModelType,+ pairId?: string,+): ReturnType<typeof useLocalRuntime> {+ const adapters = useStudioRuntimeAdapters(modelType, pairId);const persistedChatAdapter = useMemo(() => createPersistedRunAdapter(chatAdapter),[],@@ -956,6 +1001,12 @@ function useRuntimeHook(): ReturnType<typeof useLocalRuntime> {return useLocalRuntime(persistedChatAdapter, { adapters });}+function createRuntimeHook(modelType: ModelType, pairId?: string) {+ return function useConfiguredRuntimeHook(): ReturnType<typeof useLocalRuntime> {+ return useRuntimeHook(modelType, pairId);+ };+}+function ThreadAutoSwitch({threadId,syncActiveThreadId = true,@@ -1133,20 +1184,28 @@ export function ChatRuntimeProvider({children,modelType = "base",pairId,+ projectId,initialThreadId,newThreadNonce,syncActiveThreadId = true,+ listThreads = true,}: {children: ReactNode;modelType?: ModelType;pairId?: string;+ projectId?: string | null;initialThreadId?: string;newThreadNonce?: string;syncActiveThreadId?: boolean;+ listThreads?: boolean;}): ReactElement {+ const runtimeHook = useMemo(+ () => createRuntimeHook(modelType, pairId),+ [modelType, pairId],+ );const runtime = useRemoteThreadListRuntime({- runtimeHook: useRuntimeHook,- adapter: createStudioDbAdapter(modelType, pairId),+ runtimeHook,+ adapter: createStudioDbAdapter(modelType, pairId, projectId, listThreads),});const aui = useAui({});diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 772b2171176..0165a3930ed 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -1294,8 +1294,8 @@ export function SharedComposer({: reasoningDisabled? "cursor-not-allowed opacity-40": effectiveReasoningEnabled- ? "text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"- : "hover:bg-primary/10 dark:hover:bg-white/[0.08]",+ ? "cursor-pointer text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"+ : "cursor-pointer hover:bg-primary/10 dark:hover:bg-white/[0.08]",)}aria-label={thinkToggleAriaLabel({reasoningLockedOn,@@ -1324,8 +1324,8 @@ export function SharedComposer({!modelLoaded? "cursor-not-allowed opacity-40": preserveThinking- ? "text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"- : "hover:bg-primary/10 dark:hover:bg-white/[0.08]",+ ? "cursor-pointer text-primary hover:bg-primary/10 dark:hover:bg-white/[0.08]"+ : "cursor-pointer hover:bg-primary/10 dark:hover:bg-white/[0.08]",)}aria-label={preserveThinkingdiff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 5a5928d3112..ebcd1892d19 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -332,6 +332,7 @@ type ChatRuntimeStore = {chatTemplateOverride: string | null;loadedChatTemplateOverride: string | null;activeThreadId: string | null;+ activeProjectId: string | null;settingsPanelOpen: boolean;pendingAudioBase64: string | null;pendingAudioName: string | null;@@ -363,6 +364,7 @@ type ChatRuntimeStore = {setModelsError: (error: string | null) => void;setCheckpoint: (modelId: string, ggufVariant?: string | null) => void;setActiveThreadId: (threadId: string | null) => void;+ setActiveProjectId: (projectId: string | null) => void;setSettingsPanelOpen: (open: boolean) => void;clearCheckpoint: () => void;setReasoningEnabled: (@@ -662,6 +664,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({chatTemplateOverride: null,loadedChatTemplateOverride: null,activeThreadId: null,+ activeProjectId: null,settingsPanelOpen: false,pendingAudioBase64: null,pendingAudioName: null,@@ -825,6 +828,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({}),setActiveThreadId: (activeThreadId) =>set({ activeThreadId, contextUsage: null }),+ setActiveProjectId: (activeProjectId) => set({ activeProjectId }),setSettingsPanelOpen: (settingsPanelOpen) => set({ settingsPanelOpen }),clearCheckpoint: () => {// Mirror setCheckpoint's persistence behavior: dropping thediff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsxindex b15c16297e7..320668a61c0 100644--- a/studio/frontend/src/features/chat/thread-sidebar.tsx+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx@@ -42,7 +42,11 @@ export function ThreadSidebar({const { items } = useChatSidebarItems();const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);const activeId =- view.mode === "single" ? (view.threadId ?? storeThreadId) : view.pairId;+ view.mode === "single"+ ? (view.threadId ?? storeThreadId)+ : view.mode === "compare"+ ? view.pairId+ : view.projectId;function viewForItem(item: SidebarItem): ChatView {return item.type === "single"diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.tsindex d0c4e22870f..a2bd3950654 100644--- a/studio/frontend/src/features/chat/types.ts+++ b/studio/frontend/src/features/chat/types.ts@@ -4,8 +4,28 @@export type ModelType = "base" | "lora" | "model1" | "model2";export type ChatView =- | { mode: "single"; threadId?: string; newThreadNonce?: string }- | { mode: "compare"; pairId: string };+ | {+ mode: "project";+ projectId: string;+ }+ | {+ mode: "single";+ threadId?: string;+ newThreadNonce?: string;+ projectId?: string | null;+ }+ | { mode: "compare"; pairId: string; projectId?: string | null };++export interface ProjectRecord {+ id: string;+ name: string;+ instructions?: string;+ rootPath?: string | null;+ sandboxPath?: string | null;+ archived: boolean;+ createdAt: number;+ updatedAt: number;+}export interface ThreadRecord {id: string;@@ -13,6 +33,7 @@ export interface ThreadRecord {modelType: ModelType;modelId?: string;pairId?: string;+ projectId?: string | null;archived: boolean;createdAt: number;/**diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex 57b303b7af8..6dc53cf48e2 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -4,22 +4,32 @@import {buildBackendChatExport,clearBackendChats,+ deleteChatProject,deleteChatThreads,+ getChatProject,getChatMessage,getChatThread,batchListChatMessages,+ listChatProjects,listChatImportLedger,listChatMessages,listChatThreads,notifyChatHistoryUpdated,recordChatImportLedger,+ saveChatProject,saveChatMessage,saveChatThread,syncChatMessages,+ updateChatProject,updateChatThread,} from "../api/chat-api";import { db, DEXIE_DB_NAME } from "../db";-import type { MessageRecord, ModelType, ThreadRecord } from "../types";+import type {+ MessageRecord,+ ModelType,+ ProjectRecord,+ ThreadRecord,+} from "../types";import {isChatThreadDeleted,markChatThreadsDeleted,@@ -28,6 +38,7 @@ import {type ThreadListArgs = {modelType?: ModelType;pairId?: string;+ projectId?: string | null;includeArchived?: boolean;};@@ -45,6 +56,7 @@ interface ExportedChat {exportedAt: string;version: 1;threadCount: number;+ projects?: unknown[];threads: unknown[];messages: unknown[];}@@ -82,6 +94,8 @@ function matchesThreadListArgs(return (!isChatThreadDeleted(thread.id) &&(!args.pairId || thread.pairId === args.pairId) &&+ (args.projectId === undefined ||+ (thread.projectId ?? null) === args.projectId) &&(!args.modelType || thread.modelType === args.modelType) &&(args.includeArchived !== false || !thread.archived));@@ -584,6 +598,72 @@ export async function listStoredChatThreadsWithMessages(return entries.filter((e) => e.hasContent).map((e) => e.thread);}+export async function listStoredChatProjects(+ args: { includeArchived?: boolean } = {},+): Promise<ProjectRecord[]> {+ return listChatProjects(args);+}++export async function getStoredChatProject(+ projectId: string,+): Promise<ProjectRecord | null> {+ return getChatProject(projectId);+}++export async function createStoredChatProject(+ name: string,+): Promise<ProjectRecord> {+ const trimmed = name.trim();+ if (!trimmed) {+ throw new Error("Project name is required.");+ }+ const now = Date.now();+ return saveChatProject({+ id: crypto.randomUUID(),+ name: trimmed,+ instructions: "",+ archived: false,+ createdAt: now,+ updatedAt: now,+ });+}++export async function updateStoredChatProject(+ projectId: string,+ patch: Partial<ProjectRecord>,+): Promise<ProjectRecord> {+ return updateChatProject(projectId, {+ ...patch,+ updatedAt: patch.updatedAt ?? Date.now(),+ });+}++export async function deleteStoredChatProject(+ projectId: string,+ args: { deleteFiles?: boolean } = {},+): Promise<void> {+ await deleteChatProject(projectId, args);+}++export async function moveStoredChatItemToProject(+ item: { type: "single" | "compare"; id: string },+ projectId: string | null,+): Promise<void> {+ const threadIds =+ item.type === "single"+ ? [item.id]+ : (await listStoredChatThreads({+ pairId: item.id,+ includeArchived: true,+ })).map((thread) => thread.id);++ await Promise.all(+ Array.from(new Set(threadIds)).map((threadId) =>+ updateStoredChatThread(threadId, { projectId }),+ ),+ );+}+export async function saveStoredChatMessage(message: MessageRecord,): Promise<MessageRecord> {@@ -767,6 +847,7 @@ export async function buildStoredChatExport(): Promise<ExportedChat> {exportedAt: new Date().toISOString(),version: 1,threadCount: threads.length,+ projects: backend?.projects ?? [],threads,messages,};diff --git a/studio/frontend/src/features/profile/utils/avatar-initials.ts b/studio/frontend/src/features/profile/utils/avatar-initials.tsindex 926f57f3b5c..254a50719bb 100644--- a/studio/frontend/src/features/profile/utils/avatar-initials.ts+++ b/studio/frontend/src/features/profile/utils/avatar-initials.ts@@ -7,7 +7,7 @@ export function initialsFromName(name: string): string {return trimmed[0]!.toUpperCase();}-/** Default blue background for avatar fallback (readable white text). */+/** Default Unsloth-green background for avatar fallback (readable white text). */export function avatarBgStyle(): { backgroundColor: string } {- return { backgroundColor: "hsl(217 58% 48%)" };+ return { backgroundColor: "#14b789" };}diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsxindex b13ecbd1c48..53191fa3050 100644--- a/studio/frontend/src/features/studio/studio-page.tsx+++ b/studio/frontend/src/features/studio/studio-page.tsx@@ -53,6 +53,10 @@ export function StudioPage(): ReactElement {const selectedHistoryRunId = useTrainingRuntimeStore((s) => s.selectedHistoryRunId);const setSelectedHistoryRunId = useTrainingRuntimeStore((s) => s.setSelectedHistoryRunId);+ const setCurrentRunViewActive = useTrainingRuntimeStore(+ (s) => s.setCurrentRunViewActive,+ );+useEffect(() => {return () => setSelectedHistoryRunId(null);}, [setSelectedHistoryRunId]);@@ -67,6 +71,13 @@ export function StudioPage(): ReactElement {? "configure": requestedTab;+ // Mirror "Current Run" tab state into the store so the sidebar can highlight+ // the run this view refers to. Cleared on unmount (leaving the studio page).+ useEffect(() => {+ setCurrentRunViewActive(activeTab === "current-run");+ return () => setCurrentRunViewActive(false);+ }, [activeTab, setCurrentRunViewActive]);+const { setPinned } = useSidebar();const pinSidebar = useCallback(() => setPinned(true), [setPinned]);diff --git a/studio/frontend/src/features/studio/training-start-overlay.tsx b/studio/frontend/src/features/studio/training-start-overlay.tsxindex 8ecd3bb7e9f..0205394a536 100644--- a/studio/frontend/src/features/studio/training-start-overlay.tsx+++ b/studio/frontend/src/features/studio/training-start-overlay.tsx@@ -37,6 +37,12 @@ import { useT } from "@/i18n";const HF_REPO_REGEX = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;+// Tracks which jobs have already played the terminal intro animation. The+// overlay unmounts when you navigate away from the training page, so without+// this its typing/fade-in would replay on every return even though the run+// itself is still going. Module-level so it survives remounts.+const animatedJobs = new Set<string>();+function formatBytes(n: number): string {if (n <= 0) return "0 B";if (n < 1024) return `${n} B`;@@ -254,6 +260,7 @@ export function TrainingStartOverlay({const { stopTrainingRun, dismissTrainingRun } = useTrainingActions();const isStarting = useTrainingRuntimeStore((s) => s.isStarting);const phase = useTrainingRuntimeStore((s) => s.phase);+ const jobId = useTrainingRuntimeStore((s) => s.jobId);const startModelName = useTrainingRuntimeStore((s) => s.startModelName);const startDatasetName = useTrainingRuntimeStore((s) => s.startDatasetName);const startFromResume = useTrainingRuntimeStore((s) => s.startFromResume);@@ -298,6 +305,16 @@ export function TrainingStartOverlay({}}, [isStarting]);+ // Play the intro animation only the first time we mount for a given job.+ // On later remounts (e.g. leaving the training page and coming back) the+ // terminal renders its final state instantly so the logs don't restart.+ const alreadyAnimated = jobId != null && animatedJobs.has(jobId);+ useEffect(() => {+ if (jobId != null) {+ animatedJobs.add(jobId);+ }+ }, [jobId]);+return (<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center rounded-2xl bg-background/45 backdrop-blur-[1px]"><div className="pointer-events-auto relative flex w-[860px] max-w-[calc(100%-2rem)] flex-col items-center gap-4">@@ -311,7 +328,7 @@ export function TrainingStartOverlay({<Buttonvariant="ghost"size="icon"- className="absolute right-3 top-3 z-10 size-7 cursor-pointer rounded-full text-muted-foreground/60 hover:bg-destructive/10 hover:text-destructive"+ className="absolute right-3 top-3 z-10 size-7 cursor-pointer rounded-full text-muted-foreground/90 hover:bg-destructive/10 hover:text-destructive"onClick={() => setCancelDialogOpen(true)}disabled={cancelRequested}>@@ -349,6 +366,7 @@ export function TrainingStartOverlay({<TerminalclassName="w-full min-h-[390px] rounded-2xl px-7 py-6 text-left"startOnView={false}+ instant={alreadyAnimated}><TypingAnimationduration={36}diff --git a/studio/frontend/src/features/training/stores/training-runtime-store.ts b/studio/frontend/src/features/training/stores/training-runtime-store.tsindex da496be002c..f1966f03fb5 100644--- a/studio/frontend/src/features/training/stores/training-runtime-store.ts+++ b/studio/frontend/src/features/training/stores/training-runtime-store.ts@@ -46,6 +46,7 @@ const initialState: TrainingRuntimeState = {resetGeneration: 0,stopRequested: false,selectedHistoryRunId: null,+ currentRunViewActive: false,};function sortSeries(points: TrainingSeriesPoint[]): TrainingSeriesPoint[] {@@ -182,6 +183,9 @@ export const useTrainingRuntimeStore = create<TrainingRuntimeStore>()((set) => (setSelectedHistoryRunId: (selectedHistoryRunId) =>set({ selectedHistoryRunId }),+ setCurrentRunViewActive: (currentRunViewActive) =>+ set({ currentRunViewActive }),+applyStatus: (payload) =>set((state) => {const metricHistory = applyMetricHistoryFromStatus(payload);diff --git a/studio/frontend/src/features/training/types/runtime.ts b/studio/frontend/src/features/training/types/runtime.tsindex a62ef9ef262..d30c3f75c28 100644--- a/studio/frontend/src/features/training/types/runtime.ts+++ b/studio/frontend/src/features/training/types/runtime.ts@@ -105,6 +105,9 @@ export interface TrainingRuntimeState {resetGeneration: number;stopRequested: boolean;selectedHistoryRunId: string | null;+ // True while the studio "Current Run" tab is the active view, so the sidebar+ // can highlight which run row the current run refers to (the active job).+ currentRunViewActive: boolean;}export interface TrainingRuntimeActions {@@ -127,6 +130,7 @@ export interface TrainingRuntimeActions {setStartQueued: (jobId: string, message: string) => void;setRuntimeError: (message: string) => void;setSelectedHistoryRunId: (id: string | null) => void;+ setCurrentRunViewActive: (value: boolean) => void;}export type TrainingRuntimeStore = TrainingRuntimeState & TrainingRuntimeActions;diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 2f5f20252ef..c60dfc6bd76 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -14,6 +14,51 @@@custom-variant dark (&:is(.dark *));+@layer components {+ /* Sidebar scroll area (Gemini-style). The BOTTOM edge always fades so the+ last rows dissolve into the profile footer (no divider line). Once+ scrolled, the TOP edge also fades so rows dissolve as they pass under the+ pinned New Chat / Search header. */+ /* Top edge: when scrolled, rows dissolve as they pass under the pinned+ New Chat / Search header (mask — fades content to transparent). */+ .sidebar-scroll-fade.is-scrolled {+ -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 14px);+ mask-image: linear-gradient(to bottom, transparent 0, #000 14px);+ }+ /* Bottom edge: Gemini-style sticky gradient OVERLAY painted in the sidebar+ background colour, so the last rows wash into the profile footer. Uses a+ zero-height sticky anchor with an absolutely-positioned gradient so it+ never takes layout space. */+ .sidebar-bottom-fade {+ position: sticky;+ bottom: 0;+ height: 0;+ z-index: 1;+ pointer-events: none;+ }+ .sidebar-bottom-fade::after {+ content: "";+ position: absolute;+ inset-inline: 0;+ bottom: 0;+ height: 40px;+ background: linear-gradient(to top, var(--sidebar), transparent);+ }+}++@layer base {+ h1,+ h2,+ h3,+ [data-slot="dialog-title"],+ [data-slot="alert-dialog-title"] {+ font-family: "Hellix", "Space Grotesk Variable", var(--font-sans) !important;+ font-weight: 500 !important;+ }+}+++@font-face {font-family: "Hellix";src: url("/fonts/Hellix-Regular.woff") format("woff");@@ -81,13 +126,15 @@--chart-4: oklch(0.6926 0.1112 346.5775);--chart-5: oklch(0.7497 0.1003 85.0057);--radius: 1.1rem;- --sidebar: #f9faf9;+ /* Match the page background so the sidebar reads as one surface with the+ content; the faint --sidebar-border on its right edge is the separator. */+ --sidebar: oklch(1 0 0);--sidebar-foreground: oklch(0.1281 0.0179 169.2764);--sidebar-primary: #17b88b;--sidebar-primary-foreground: oklch(1 0 0);--sidebar-accent: oklch(0.96 0.0279 166.55);--sidebar-accent-foreground: oklch(0.2868 0.0649 159.9823);- --sidebar-border: oklch(0.945 0.0101 164.8536);+ --sidebar-border: oklch(0.92 0 0);--sidebar-ring: #17b88b;--destructive-foreground: oklch(1 0 0);--font-sans: "Inter Variable", ui-sans-serif, sans-serif, system-ui;@@ -120,7 +167,7 @@/* 0px 0px 0px 0px hsl(0 0% 0% / 0),*//* 0px 8px 10px 0px hsl(0 0% 0% / 0);*//*--shadow-2xl: 0px 0px 0px 0px hsl(0 0% 0% / 0);*/- --tracking-normal: -0.01em;+ --tracking-normal: 0em;/* Hex (not OKLCH) so the rendered surface matches the design mockup pixel-for-pixel. */--nav-fg: #383835;@@ -201,7 +248,8 @@--chart-3: oklch(0.7554 0.1285 197.339);--chart-4: oklch(0.7503 0.1199 346.7805);--chart-5: oklch(0.799 0.1196 84.6633);- --sidebar: #18181a;+ /* Match the page background (dark); --sidebar-border is the right-edge separator. */+ --sidebar: #1f2023;--sidebar-foreground: #ececee;--sidebar-primary: #17b88b;--sidebar-primary-foreground: oklch(1 0 0);@@ -305,8 +353,8 @@--font-mono: JetBrains Mono, monospace;--font-serif: Source Serif 4, serif;--radius: 1.1rem;- --tracking-tighter: calc(var(--tracking-normal) - 0.05em);- --tracking-tight: calc(var(--tracking-normal) - 0.025em);+ --tracking-tighter: 0em;+ --tracking-tight: 0em;--tracking-wide: calc(var(--tracking-normal) + 0.025em);--tracking-wider: calc(var(--tracking-normal) + 0.05em);--tracking-widest: calc(var(--tracking-normal) + 0.1em);@@ -438,7 +486,7 @@h5,h6 {font-family: var(--font-sans);- letter-spacing: -0.02em;+ letter-spacing: 0;}}@@ -450,15 +498,14 @@on global antialiased font-smoothing to neutralize the bloom. */.font-heading {font-family: var(--font-heading);- letter-spacing: -0.01em;+ letter-spacing: 0;}- /* Dark mode loosens tracking to offset optical bloom on dark surfaces. */.tracking-nav {- letter-spacing: 0.015em;+ letter-spacing: 0;}.dark .tracking-nav {- letter-spacing: 0.03em;+ letter-spacing: 0;}.nav-icon-btn {@@ -485,6 +532,10 @@.sidebar-nav-btn:hover,.sidebar-nav-btn[data-active="true"],.sidebar-nav-btn[data-state="open"],+ .group\/project-item:hover .sidebar-nav-btn,+ .group\/project-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,+ .group\/project-chat-item:hover .sidebar-nav-btn,+ .group\/project-chat-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,.group\/recent-item:hover .sidebar-nav-btn,.group\/recent-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,.group\/run-item:hover .sidebar-nav-btn,@@ -495,6 +546,10 @@.dark .sidebar-nav-btn:hover,.dark .sidebar-nav-btn[data-active="true"],.dark .sidebar-nav-btn[data-state="open"],+ .dark .group\/project-item:hover .sidebar-nav-btn,+ .dark .group\/project-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,+ .dark .group\/project-chat-item:hover .sidebar-nav-btn,+ .dark .group\/project-chat-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,.dark .group\/recent-item:hover .sidebar-nav-btn,.dark .group\/recent-item:has(.sidebar-row-action[data-state="open"]) .sidebar-nav-btn,.dark .group\/run-item:hover .sidebar-nav-btn,@@ -503,7 +558,7 @@}.sidebar-row-action {- @apply absolute top-0 bottom-0 right-0 inline-flex items-center justify-end pl-2 pr-1.5 opacity-0 pointer-events-none outline-none;+ @apply absolute top-0 bottom-0 right-0 inline-flex cursor-pointer items-center justify-end pl-2 pr-1.5 opacity-0 pointer-events-none outline-none;}.sidebar-row-action[data-state="open"] {@apply opacity-100 pointer-events-auto;@@ -529,12 +584,22 @@}.sidebar-sticky-label {- @apply sticky top-0 z-20 rounded-none bg-sidebar pt-0 pb-1.5 pl-[18px] pr-4 text-[13px]! font-medium normal-case tracking-[0.04em] text-nav-fg-muted focus-visible:ring-0! focus-visible:outline-none shadow-[0_-8px_0_0_var(--sidebar)] transition-shadow duration-150;- }- .sidebar-sticky-label.is-scrolled {- @apply shadow-[0_-8px_0_0_var(--sidebar),0_0.5px_0_0_var(--sidebar-border)];+ @apply rounded-none bg-sidebar pt-0 pb-[8px] pl-[18px] pr-4 text-[14.5px]! leading-[17px] font-medium normal-case focus-visible:ring-0! focus-visible:outline-none transition-shadow duration-150;+ /* Muted section-header gray, matching Gemini's "Notebooks"/"Recents".+ Lightened from #5f6368 so the label reads as a header, clearly+ lighter than the near-black nav items. */+ color: #80868b;+ letter-spacing: 0;+ }+ .sidebar-sticky-label-following {+ @apply pt-[21px];+ }+ .dark .sidebar-sticky-label {+ /* Muted gray, clearly dimmer than the near-white nav items (#ececee) so+ "Train"/"Recents" read as section headers — like Gemini's dark mode. */+ color: #9aa0a6;+ letter-spacing: 0;}-/* Neutral panel input surface — sidesteps the green cast on`--input` / `--border` (both have a small chroma at hue ~165 inlight mode). Same value drives the preset input pill, the system@@ -697,7 +762,8 @@border-color: rgb(255 255 255 / 0.12) !important;}- .app-user-menu [data-slot="dropdown-menu-item"] {+ .app-user-menu [data-slot="dropdown-menu-item"],+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"] {height: 32px;padding: 0 0.625rem !important;gap: 8.5px !important;@@ -705,28 +771,38 @@font-weight: 500;font-size: 14.5px;line-height: 19px;- letter-spacing: 0.015em;+ letter-spacing: 0;color: var(--nav-fg);}- .dark .app-user-menu [data-slot="dropdown-menu-item"] {- letter-spacing: 0.03em;+ .dark .app-user-menu [data-slot="dropdown-menu-item"],+ .dark .app-user-menu [data-slot="dropdown-menu-sub-trigger"] {+ letter-spacing: 0;}- .app-user-menu [data-slot="dropdown-menu-item"] svg {+ .app-user-menu [data-slot="dropdown-menu-item"] svg,+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"] svg {width: 19px !important;height: 19px !important;flex-shrink: 0;}- .app-user-menu [data-slot="dropdown-menu-item"]:focus {+ .app-user-menu [data-slot="dropdown-menu-item"]:focus,+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"]:focus,+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"][data-state="open"] {background-color: var(--nav-surface-hover);color: #000;}- .dark .app-user-menu [data-slot="dropdown-menu-item"]:focus {+ .dark .app-user-menu [data-slot="dropdown-menu-item"]:focus,+ .dark .app-user-menu [data-slot="dropdown-menu-sub-trigger"]:focus,+ .dark .app-user-menu [data-slot="dropdown-menu-sub-trigger"][data-state="open"] {color: #fff;}- .app-user-menu [data-slot="dropdown-menu-item"]:focus * {+ .app-user-menu [data-slot="dropdown-menu-item"]:focus *,+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"]:focus *,+ .app-user-menu [data-slot="dropdown-menu-sub-trigger"][data-state="open"] * {color: #000 !important;}- .dark .app-user-menu [data-slot="dropdown-menu-item"]:focus * {+ .dark .app-user-menu [data-slot="dropdown-menu-item"]:focus *,+ .dark .app-user-menu [data-slot="dropdown-menu-sub-trigger"]:focus *,+ .dark .app-user-menu [data-slot="dropdown-menu-sub-trigger"][data-state="open"] * {color: #fff !important;}@@ -799,7 +875,7 @@}.composer-pill-btn {- @apply flex items-center gap-1.5 rounded-full px-1.5 py-1.5 text-[13px] font-medium text-muted-foreground/70 transition-colors hover:bg-primary/10 dark:hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40;+ @apply flex cursor-pointer items-center gap-1.5 rounded-full px-1.5 py-1.5 text-[13px] font-medium text-muted-foreground/70 transition-colors hover:bg-primary/10 dark:hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40;}.composer-pill-btn[data-active="true"] {color: var(--primary);@@ -814,7 +890,7 @@}.composer-footer-note {- @apply mt-1.5 text-center text-[11px] tracking-[0.04em] text-muted-foreground;+ @apply mt-1.5 text-center text-[11px] tracking-[0em] text-muted-foreground;font-family: var(--font-sans);}@@ -1277,24 +1353,16 @@background: #23252a;}-[data-sidebar="content"] {- scrollbar-color: oklch(0.5 0 0 / 0.22) var(--sidebar);-}--.dark [data-sidebar="content"] {- scrollbar-color: oklch(0.72 0 0 / 0.25) var(--sidebar);-}--[data-sidebar="content"]::-webkit-scrollbar-track {- background: var(--sidebar);-}-[data-sidebar="content"]::-webkit-scrollbar-thumb {- background: oklch(0.5 0 0 / 0.22);+/* Search list: re-enable the native scrollbar (CommandList defaults to no-scrollbar). */+.cmd-native-scrollbar {+ scrollbar-width: thin;+ -ms-overflow-style: auto;}--.dark [data-sidebar="content"]::-webkit-scrollbar-thumb {- background: oklch(0.72 0 0 / 0.25);+.cmd-native-scrollbar::-webkit-scrollbar {+ display: block;+ width: 8px;+ height: 8px;}/*---break---*/