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: import Cursor, Claude Code and Codex conversations from Settings (#8561)
Tamsi341a06b3587a
diff --git a/studio/backend/core/external_import/__init__.py b/studio/backend/core/external_import/__init__.pynew file mode 100644index 00000000000..0d3ac14e884--- /dev/null+++ b/studio/backend/core/external_import/__init__.py@@ -0,0 +1,363 @@+# 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 another tool's local conversations into Studio, one Studio project per source project.++Re-imports are how new turns arrive, so whatever the user changed in Studio wins: titles,+project placement, archived flags, edited or deleted messages, deleted chats.+"""++from __future__ import annotations++import hashlib+import io+import json+import os+import re+import time+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Callable, Iterator, Optional++from loggers import get_logger+from storage import studio_db++logger = get_logger(__name__)++TITLE_MAX_CHARS = 120+++@dataclass+class ImportSummary:+ projects: int = 0+ chats: int = 0+ # Zero on a second import, which is how the UI says "up to date".+ new_chats: int = 0+ messages: int = 0+ skipped: int = 0+ warnings: list[str] = field(default_factory = list)+++@dataclass+class SourceProject:+ slug: str+ name: str+ sessions: list[Path]+++@dataclass+class Transcript:+ session_id: str+ thread_id: str+ title: str+ created_at_ms: int+ updated_at_ms: int+ messages: list[dict]+ # Which physical file the messages came from; a change (Codex revert) re-bases the ledger+ # at ``inherited``, the count of leading messages carried over from the previous revision.+ revision: str = ""+ inherited: int = 0+++@dataclass(frozen = True)+class Source:+ # Ledger key and id prefix; changing it duplicates every imported chat.+ key: str+ label: str+ home_env: str+ default_home: str+ list_projects: Callable[[Path], list[SourceProject]]+ read_transcript: Callable[[Path, str, str], Transcript]+ # Cheaper than list_projects for the status probe that runs whenever Settings > Data opens.+ count_sessions: Optional[Callable[[Path], int]] = None+ # Thread identity for a session file; Codex keys by session_meta.id (a revert writes a new file).+ session_key: Optional[Callable[[Path], str]] = None++ def session_id(self, path: Path) -> str:+ return self.session_key(path) if self.session_key else session_id_of(path)++ def session_count(self) -> int:+ home = self.home()+ if self.count_sessions is not None:+ return self.count_sessions(home)+ return sum(len(project.sessions) for project in self.list_projects(home))++ def home(self, override: Optional[Path] = None) -> Path:+ if override is not None:+ return Path(override).expanduser()+ from_env = (os.environ.get(self.home_env) or "").strip()+ return Path(from_env).expanduser() if from_env else Path.home() / self.default_home+++def stable_id(+ prefix: str,+ *parts: str,+ length: int = 12,+) -> str:+ digest = hashlib.sha1("\x00".join(parts).encode("utf-8")).hexdigest()+ return f"{prefix}-{digest[:length]}"+++def project_id_for(source: Source, slug: str) -> str:+ return stable_id(source.key, slug)+++def session_id_of(path: Path) -> str:+ # Not path.stem: Codex compresses old x.jsonl to x.jsonl.zst, same session.+ return path.name.split(".", 1)[0]+++def thread_id_for(source: Source, session_id: str) -> str:+ return stable_id(f"{source.key}-thread", session_id)+++def display_name(slug: str) -> str:+ """The slug with the user's home folder dropped; dashes are lossy, so the real path is unknowable."""+ folded = re.sub("-+", "-", slug).strip("-")+ try:+ home = re.sub(r"[^A-Za-z0-9]+", "-", str(Path.home())).strip("-")+ except (OSError, RuntimeError):+ home = ""+ if home and folded.lower().startswith(f"{home.lower()}-"):+ return folded[len(home) + 1 :]+ return folded or slug+++def title_from(text: str, default: str) -> str:+ """Matches the frontend's fallback title."""+ first_line = next((line.strip() for line in text.splitlines() if line.strip()), "")+ if not first_line:+ return default+ if len(first_line) <= TITLE_MAX_CHARS:+ return first_line+ return first_line[: TITLE_MAX_CHARS - 1].rstrip() + "…"+++def file_times_ms(path: Path) -> tuple[int, int]:+ info = path.stat()+ created = getattr(info, "st_birthtime", None) or info.st_ctime+ return int(created * 1000), int(max(info.st_mtime, created) * 1000)+++def _zstd_reader(raw):+ try:+ from compression import zstd # Python 3.14++ return zstd.ZstdFile(raw)+ except ImportError:+ import zstandard # ImportError here means the caller skips the file+ return zstandard.ZstdDecompressor().stream_reader(raw)+++def read_jsonl(path: Path) -> Iterator[dict]:+ """Records of a JSONL(.zst) file; a half-written last line is normal for a live session."""+ with path.open("rb") as raw:+ stream = _zstd_reader(raw) if path.suffix == ".zst" else raw+ for line in io.TextIOWrapper(stream, encoding = "utf-8", errors = "replace"):+ try:+ record = json.loads(line)+ except json.JSONDecodeError:+ continue+ if isinstance(record, dict):+ yield record+++def iso_ms(value) -> Optional[int]:+ try:+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo = timezone.utc)+ return int(parsed.timestamp() * 1000)+++def clean_text(text: str) -> str:+ return re.sub(r"\n{3,}", "\n\n", text).strip()+++def tool_call(tool_id: str, block: dict) -> dict:+ arguments = block.get("input")+ return {+ "type": "tool-call",+ "toolCallId": tool_id,+ "toolName": str(block.get("name") or "unknown"),+ "args": arguments if isinstance(arguments, dict) else {},+ }+++def first_user_text(messages: list[dict]) -> str:+ return next(+ (+ part["text"]+ for message in messages+ if message["role"] == "user"+ for part in message["content"]+ if part.get("type") == "text"+ ),+ "",+ )+++def _thread_row(transcript: Transcript, existing: dict, project_id: str) -> dict:+ # upsert_chat_thread nulls columns it is not handed, so the stored row is the base:+ # sandbox container, compare pair and fork origin survive a re-import.+ return {+ **existing,+ "id": transcript.thread_id,+ "title": existing.get("title") or transcript.title,+ # An empty model id lets the user pick one when they continue the chat.+ "modelType": existing.get("modelType") or "base",+ "modelId": existing.get("modelId") or "",+ # None for a chat the user moved to Recents.+ "projectId": existing.get("projectId") if existing else project_id,+ "archived": bool(existing.get("archived")),+ "createdAt": existing.get("createdAt") or transcript.created_at_ms,+ "updatedAt": max(transcript.updated_at_ms, int(existing.get("updatedAt") or 0)),+ }+++def _pending_messages(source: Source, transcript: Transcript, existing: bool) -> list[dict]:+ # Only turns appended since the last import. The ledger count, not the message rows,+ # says which those are: a message deleted in Studio leaves no row behind.+ if not existing:+ return list(transcript.messages)+ stored = studio_db.list_chat_messages(transcript.thread_id)+ mark = studio_db.get_external_import_mark(source.key, transcript.session_id)+ if mark is None:+ # No rows and no mark = shell thread from an interrupted import.+ return [] if stored else list(transcript.messages)+ turns, revision = mark+ pending = transcript.messages[+ turns if revision == transcript.revision else transcript.inherited :+ ]+ # Hang each new turn off its nearest ancestor that exists, so a parent deleted in Studio+ # does not orphan it (the frontend refuses a thread with a missing parent).+ present = {message["id"] for message in stored}+ by_id = {message["id"]: message for message in transcript.messages}+ reseated = []+ for message in pending:+ parent = message.get("parentId")+ while parent and parent not in present:+ parent = by_id.get(parent, {}).get("parentId")+ reseated.append({**message, "parentId": parent})+ present.add(message["id"])+ return reseated+++def _late_tool_results(transcript: Transcript) -> list[dict]:+ """Stored messages whose tool calls were imported while open and have a result now."""+ stored = {m["id"]: m for m in studio_db.list_chat_messages(transcript.thread_id)}+ patched = []+ for message in transcript.messages:+ current = stored.get(message["id"])+ results = {+ part["toolCallId"]: part["result"]+ for part in message["content"]+ if part.get("type") == "tool-call" and "result" in part+ }+ if current is None or not results:+ continue+ content = [+ {**part, "result": results[part["toolCallId"]]}+ if part.get("type") == "tool-call"+ and "result" not in part+ and part.get("toolCallId") in results+ else part+ for part in current["content"]+ ]+ if content != current["content"]:+ patched.append({**current, "content": content})+ return patched+++def _import_session(source: Source, path: Path, project_id: str, summary: ImportSummary) -> bool:+ session_id = source.session_id(path)+ thread_id = thread_id_for(source, session_id)+ try:+ transcript = source.read_transcript(path, thread_id, session_id)+ except OSError as exc:+ summary.warnings.append(f"{path.name}: could not be read ({exc.strerror or exc}).")+ return False+ except ImportError:+ summary.warnings.append(f"{path.name}: compressed; install zstandard to import it.")+ return False+ if not transcript.messages:+ summary.skipped += 1+ return False++ existing = studio_db.get_chat_thread(thread_id) or {}+ try:+ studio_db.upsert_chat_thread(_thread_row(transcript, existing, project_id))+ except studio_db.ChatThreadDeletedError:+ summary.skipped += 1+ return False+ pending = _pending_messages(source, transcript, bool(existing))+ if existing:+ pending = _late_tool_results(transcript) + pending+ if pending:+ studio_db.sync_chat_messages(thread_id, pending, prune_missing = False)+ studio_db.record_external_import_mark(+ source.key, session_id, len(transcript.messages), transcript.revision+ )+ summary.new_chats += 0 if existing else 1+ summary.messages += len(pending)+ return True+++def _import_project(+ source: Source, project: SourceProject, summary: ImportSummary, now_ms: int+) -> None:+ project_id = project_id_for(source, project.slug)+ existing = studio_db.get_chat_project(project_id) or {}+ studio_db.upsert_chat_project(+ {+ "id": project_id,+ "name": existing.get("name") or f"{source.label} · {project.name}",+ "instructions": existing.get("instructions") or "",+ "archived": bool(existing.get("archived")),+ "createdAt": existing.get("createdAt") or now_ms,+ "updatedAt": existing.get("updatedAt") or now_ms,+ }+ )+ before = (summary.new_chats, summary.messages)+ imported = sum(_import_session(source, path, project_id, summary) for path in project.sessions)+ if studio_db.list_chat_threads(project_id = project_id):+ # updatedAt only moves when something landed, so a no-op click does not re-sort the sidebar.+ if (summary.new_chats, summary.messages) != before:+ studio_db.update_chat_project(project_id, {"updatedAt": now_ms})+ summary.projects += 1+ summary.chats += imported+ elif not existing:+ studio_db.delete_chat_project(project_id)+++def run_import(source: Source, *, home: Optional[Path] = None) -> ImportSummary:+ summary = ImportSummary()+ now_ms = int(time.time() * 1000)+ projects = source.list_projects(source.home(home))+ # An empty Studio (clear-all, fresh database) is a blank slate for this source's chats only:+ # other tombstones still stop a stale tab resurrecting a chat the user deleted.+ if not studio_db.list_chat_threads():+ studio_db.lift_chat_thread_tombstones(+ thread_id_for(source, source.session_id(p))+ for project in projects+ for p in project.sessions+ )+ for project in projects:+ _import_project(source, project, summary, now_ms)+ logger.info(+ "external_import_finished",+ source = source.key,+ projects = summary.projects,+ chats = summary.chats,+ new_chats = summary.new_chats,+ messages = summary.messages,+ skipped = summary.skipped,+ )+ return summary+++def sources() -> dict[str, Source]:+ from core.external_import import claude, codex, cursor+ return {"cursor": cursor.SOURCE, "claude": claude.SOURCE, "codex": codex.SOURCE}diff --git a/studio/backend/core/external_import/claude.py b/studio/backend/core/external_import/claude.pynew file mode 100644index 00000000000..b01a5975d0a--- /dev/null+++ b/studio/backend/core/external_import/claude.py@@ -0,0 +1,148 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Claude Code: ``~/.claude/projects/<encoded-path>/<session>.jsonl``."""++from __future__ import annotations++import re+from pathlib import Path+from typing import Any++from core.external_import import (+ Source,+ SourceProject,+ Transcript,+ clean_text,+ display_name,+ file_times_ms,+ first_user_text,+ iso_ms,+ read_jsonl,+ stable_id,+ title_from,+ tool_call,+)++# Not anchored: Claude Code pads these tags with whitespace.+_COMMAND = re.compile(r"<command-(?:name|message|args)>")+_LOCAL_STDOUT = re.compile(r"</?local-command-stdout>")+++def list_projects(home: Path) -> list[SourceProject]:+ root = home / "projects"+ if not root.is_dir():+ return []+ projects = []+ for entry in sorted(root.iterdir()):+ if not entry.is_dir() or entry.name.startswith("."):+ continue+ sessions = sorted(p for p in entry.iterdir() if p.is_file() and p.suffix == ".jsonl")+ if sessions:+ projects.append(SourceProject(entry.name, display_name(entry.name), sessions))+ return projects+++def _user_text(text: str) -> str:+ # Slash-command echoes are the harness talking; captured command output is cut, it can follow a prompt.+ if _COMMAND.search(text):+ return ""+ return clean_text(_LOCAL_STDOUT.split(text)[0])+++def _result_text(content: Any) -> str:+ if isinstance(content, list):+ content = "\n\n".join(+ block.get("text") or ""+ for block in content+ if isinstance(block, dict) and block.get("type") == "text"+ )+ return clean_text(content) if isinstance(content, str) else ""+++def _parts(record: dict, message_id: str) -> tuple[list[dict], dict[str, str]]:+ """Text and tool-call parts, plus ``{tool_use_id: result}`` this record answers. Thinking is dropped."""+ content = record.get("message", {}).get("content")+ if isinstance(content, str):+ content = [{"type": "text", "text": content}]+ if not isinstance(content, list):+ return [], {}+ user = record.get("type") == "user"+ parts, results = [], {}+ for position, block in enumerate(content):+ if not isinstance(block, dict):+ continue+ kind = block.get("type")+ if kind == "text":+ text = (_user_text if user else clean_text)(block.get("text") or "")+ if text:+ parts.append({"type": "text", "text": text})+ elif kind == "tool_use" and not user:+ parts.append(tool_call(str(block.get("id") or f"{message_id}-{position}"), block))+ elif kind == "tool_result" and user and block.get("tool_use_id"):+ # An empty output is still a finished call; Studio replays "" differently from none.+ results[str(block["tool_use_id"])] = _result_text(block.get("content"))+ return parts, results+++def read_transcript(path: Path, thread_id: str, session_id: str) -> Transcript:+ file_created, file_updated = file_times_ms(path)+ # File order, not a tree walk: the import ledger relies on append-only order.+ records = [+ r+ for r in read_jsonl(path)+ if r.get("type") in ("user", "assistant")+ and not r.get("isSidechain")+ and not r.get("isMeta")+ ]+ by_uuid = {str(r["uuid"]): r for r in records if r.get("uuid")}+ imported: dict[str, str] = {}+ open_calls: dict[str, dict] = {}+ messages: list[dict] = []+ for index, record in enumerate(records):+ uuid = str(record.get("uuid") or "")+ message_id = stable_id("claude", session_id, uuid or f"index:{index}", length = 16)+ parts, results = _parts(record, message_id)+ for call_id, result in results.items():+ if call_id in open_calls:+ open_calls.pop(call_id)["result"] = result+ if not parts:+ continue+ open_calls.update((p["toolCallId"], p) for p in parts if p["type"] == "tool-call")+ # Nearest ancestor that became a message; rewinds keep their branch this way.+ parent, seen = record.get("parentUuid"), set()+ while parent and parent not in imported and parent not in seen:+ seen.add(parent)+ parent = by_uuid.get(parent, {}).get("parentUuid")+ timestamp = iso_ms(record.get("timestamp"))+ messages.append(+ {+ "id": message_id,+ "threadId": thread_id,+ "parentId": imported.get(parent) if parent else None,+ "role": record["type"],+ "content": parts,+ "createdAt": timestamp if timestamp is not None else file_created + index,+ "metadata": {"importedFrom": "claude", "claudeSessionId": session_id},+ }+ )+ if uuid:+ imported[uuid] = message_id+ return Transcript(+ session_id = session_id,+ thread_id = thread_id,+ title = title_from(first_user_text(messages), "Claude session"),+ created_at_ms = messages[0]["createdAt"] if messages else file_created,+ updated_at_ms = max(messages[-1]["createdAt"] if messages else 0, file_updated),+ messages = messages,+ )+++SOURCE = Source(+ key = "claude",+ label = "Claude",+ home_env = "UNSLOTH_CLAUDE_HOME",+ default_home = ".claude",+ list_projects = list_projects,+ read_transcript = read_transcript,+)diff --git a/studio/backend/core/external_import/codex.py b/studio/backend/core/external_import/codex.pynew file mode 100644index 00000000000..10a1e4679b4--- /dev/null+++ b/studio/backend/core/external_import/codex.py@@ -0,0 +1,216 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Codex: ``$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl[.zst]``, grouped by ``session_meta.cwd``.++Lines are ``{timestamp, type, payload}`` (codex-rs ``RolloutLine``). Text comes from the+``user_message`` / ``agent_message`` events, which is what Codex's own thread history replays:+the ``response_item`` user messages also carry injected AGENTS.md / environment context.+"""++from __future__ import annotations++import json+import re+from itertools import islice+from pathlib import Path++from core.external_import import (+ Source,+ SourceProject,+ Transcript,+ clean_text,+ display_name,+ file_times_ms,+ first_user_text,+ iso_ms,+ read_jsonl,+ session_id_of,+ stable_id,+ title_from,+ tool_call,+)++_UNKNOWN_FOLDER = "unknown-folder"+++_META: dict[Path, dict] = {}+++def _meta(path: Path) -> dict:+ """The rollout's session_meta payload ({} when the file cannot say), cached per path."""+ if path not in _META:+ try:+ first = next(islice(read_jsonl(path), 1), {})+ except (OSError, ImportError):+ first = {}+ payload = first.get("payload") if first.get("type") == "session_meta" else None+ payload = payload if isinstance(payload, dict) else {}+ # Only what is read below: the payload also carries the full base instructions.+ _META[path] = {+ k: payload[k] for k in ("id", "cwd", "source", "history_base") if k in payload+ }+ return _META[path]+++def _rollouts(home: Path) -> list[Path]:+ # archived_sessions holds threads archived in Codex; a rollout in both counts once.+ found: dict[str, Path] = {}+ for root in (home / "archived_sessions", home / "sessions"):+ if root.is_dir():+ for path in root.rglob("rollout-*.jsonl*"):+ if path.name.endswith((".jsonl", ".jsonl.zst")):+ found[session_id_of(path)] = path+ return sorted(found.values(), key = lambda p: p.name)+++def _rollout_id(path: Path) -> str:+ """``rollout-<YYYY-MM-DDThh-mm-ss>-<thread id>[_<rollout id>]``: a revert names its own rollout."""+ return session_id_of(path)[len("rollout-YYYY-MM-DDThh-mm-ss-") :].rsplit("_", 1)[-1]+++def _thread_id(path: Path) -> str:+ return str(_meta(path).get("id") or session_id_of(path))+++def _by_thread(home: Path) -> dict[str, list[Path]]:+ """Rollouts per Codex thread, oldest first: a revert writes a new file under the same id."""+ threads: dict[str, list[Path]] = {}+ for path in _rollouts(home):+ threads.setdefault(_thread_id(path), []).append(path)+ return threads+++def list_projects(home: Path) -> list[SourceProject]:+ _META.clear()+ by_cwd: dict[str, list[Path]] = {}+ for paths in _by_thread(home).values():+ path = paths[-1] # the thread's current state+ meta = _meta(path)+ # Subagent threads repeat work their parent already shows.+ source = meta.get("source")+ if isinstance(source, dict) and "subagent" in source:+ continue+ # The raw cwd is the identity (hashed into the project id); "a-b" and "a/b" stay apart.+ by_cwd.setdefault(str(meta.get("cwd") or _UNKNOWN_FOLDER), []).append(path)+ return [+ SourceProject(cwd, display_name(re.sub(r"[^A-Za-z0-9]+", "-", cwd)), paths)+ for cwd, paths in by_cwd.items()+ ]+++def _records(path: Path) -> list[tuple[str, int, dict]]:+ """``(origin file, ordinal, record)`` with a paginated thread's inherited prefix first.++ A fork or revert (codex-rs ``history_base``) writes only the tail; the prefix is the rollout+ named by ``history_base.thread_id`` (a rollout id, not ``session_meta.id``) up to+ ``end_ordinal_exclusive``.+ """+ own = list(read_jsonl(path))+ origin = session_id_of(path)+ tagged = [(origin, record.get("ordinal", index), record) for index, record in enumerate(own)]+ base = _meta(path).get("history_base")+ if not isinstance(base, dict):+ return tagged+ home = next(+ (p.parent for p in path.parents if p.name in ("sessions", "archived_sessions")), None+ )+ rollout = str(base.get("thread_id"))+ base_path = next(+ (p for p in (_rollouts(home) if home else []) if _rollout_id(p) == rollout), None+ )+ if base_path is None or base_path == path:+ return tagged # base rollout deleted: the tail is all there is+ cut = base.get("end_ordinal_exclusive")+ prefix = [t for t in _records(base_path) if not isinstance(cut, int) or t[1] < cut]+ return prefix + tagged+++def _output_text(output) -> str:+ if isinstance(output, list):+ output = "\n\n".join(item.get("text") or "" for item in output if isinstance(item, dict))+ return clean_text(output) if isinstance(output, str) else ""+++def _call(payload: dict, message_id: str) -> dict:+ raw = payload.get("arguments") if payload["type"] == "function_call" else payload.get("input")+ try:+ args = json.loads(raw) if payload["type"] == "function_call" else {"input": raw}+ except (TypeError, ValueError):+ args = {"input": raw}+ return tool_call(+ str(payload.get("call_id") or message_id),+ {"name": payload.get("name"), "input": args},+ )+++def read_transcript(path: Path, thread_id: str, session_id: str) -> Transcript:+ file_created, file_updated = file_times_ms(path)+ revision = session_id_of(path)+ messages: list[dict] = []+ inherited = 0+ open_calls: dict[str, dict] = {}+ for position, (origin, ordinal, line) in enumerate(_records(path)):+ payload = line.get("payload")+ if not isinstance(payload, dict):+ continue+ kind = (line.get("type"), payload.get("type"))+ # Thread + origin file + ordinal: a revert's inherited messages keep their ids, and a fork+ # (another thread) gets its own, since message ids are unique across threads.+ message_id = stable_id("codex", session_id, origin, str(ordinal), length = 16)+ if kind in (("event_msg", "user_message"), ("event_msg", "agent_message")):+ role = "user" if payload["type"] == "user_message" else "assistant"+ parts = [{"type": "text", "text": clean_text(str(payload.get("message") or ""))}]+ elif kind in (("response_item", "function_call"), ("response_item", "custom_tool_call")):+ role, parts = "assistant", [_call(payload, message_id)]+ open_calls[parts[0]["toolCallId"]] = parts[0]+ elif kind in (+ ("response_item", "function_call_output"),+ ("response_item", "custom_tool_call_output"),+ ):+ call = open_calls.pop(str(payload.get("call_id")), None)+ result = _output_text(payload.get("output"))+ if call is not None:+ # An empty output is still a finished call; Studio replays "" differently from none.+ call["result"] = result+ continue+ else:+ continue+ if parts[0]["type"] == "text" and not parts[0]["text"]:+ continue+ timestamp = iso_ms(line.get("timestamp"))+ inherited += origin != revision+ messages.append(+ {+ "id": message_id,+ "threadId": thread_id,+ "parentId": messages[-1]["id"] if messages else None,+ "role": role,+ "content": parts,+ "createdAt": timestamp if timestamp is not None else file_created + position,+ "metadata": {"importedFrom": "codex", "codexSessionId": session_id},+ }+ )+ return Transcript(+ session_id = session_id,+ thread_id = thread_id,+ title = title_from(first_user_text(messages), "Codex session"),+ created_at_ms = messages[0]["createdAt"] if messages else file_created,+ updated_at_ms = max(messages[-1]["createdAt"] if messages else 0, file_updated),+ messages = messages,+ revision = revision,+ inherited = inherited,+ )+++SOURCE = Source(+ key = "codex",+ label = "Codex",+ home_env = "CODEX_HOME",+ default_home = ".codex",+ list_projects = list_projects,+ read_transcript = read_transcript,+ session_key = _thread_id,+ # Counts subagent rollouts too: the probe only decides whether to show the row.+ count_sessions = lambda home: len(_rollouts(home)),+)diff --git a/studio/backend/core/external_import/cursor.py b/studio/backend/core/external_import/cursor.pynew file mode 100644index 00000000000..9303fd8a91e--- /dev/null+++ b/studio/backend/core/external_import/cursor.py@@ -0,0 +1,136 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Cursor: ``~/.cursor/projects/<slug>/agent-transcripts/<session>[/<session>].jsonl``.++Cursor stores no tool results or per-line timestamps, so calls import without ``result``+and times are file creation + 1 ms per message (as the frontend does).+"""++from __future__ import annotations++import re+from pathlib import Path++from core.external_import import (+ Source,+ SourceProject,+ Transcript,+ clean_text,+ display_name,+ file_times_ms,+ first_user_text,+ read_jsonl,+ stable_id,+ title_from,+ tool_call,+)++NO_FOLDER_SLUG = "empty-window"++_USER_QUERY = re.compile(r"<user_query>(.*?)</user_query>", re.DOTALL)+_INJECTED_TAGS = (+ "image_files|system_reminder|attached_files|additional_data|environment_details|timestamp"+)+_INJECTED = re.compile(rf"<({_INJECTED_TAGS})>.*?</\1>|</?(?:{_INJECTED_TAGS})\s*/?>", re.DOTALL)+_REDACTED = re.compile(r"^[ \t]*\[REDACTED\][ \t]*$", re.MULTILINE)+++def _sessions(state_dir: Path) -> list[Path]:+ root = state_dir / "agent-transcripts"+ if not root.is_dir():+ return []+ sessions = []+ for entry in sorted(root.iterdir()):+ nested = entry / f"{entry.name}.jsonl"+ if entry.is_file() and entry.suffix == ".jsonl":+ sessions.append(entry) # older flat layout+ elif nested.is_file():+ # Subagent transcripts beside it are skipped: they repeat the parent's history.+ sessions.append(nested)+ return sessions+++def list_projects(home: Path) -> list[SourceProject]:+ root = home / "projects"+ if not root.is_dir():+ return []+ entries = [e for e in sorted(root.iterdir()) if e.is_dir() and not e.name.startswith(".")]+ # A session started before a folder was opened is filed under both that folder and the+ # no-folder window; the folder keeps it, so the no-folder window goes last.+ entries.sort(key = lambda e: e.name == NO_FOLDER_SLUG)+ claimed: set[str] = set()+ projects = []+ for entry in entries:+ sessions = [p for p in _sessions(entry) if p.stem not in claimed]+ if sessions:+ claimed.update(p.stem for p in sessions)+ name = "No folder open" if entry.name == NO_FOLDER_SLUG else display_name(entry.name)+ projects.append(SourceProject(entry.name, name, sessions))+ return projects+++def _user_text(text: str) -> str:+ queries = [q.strip() for q in _USER_QUERY.findall(text) if q.strip()]+ return clean_text("\n\n".join(queries) if queries else _INJECTED.sub("", text))+++def _parts(role: str, content, message_id: str) -> list[dict]:+ if isinstance(content, str):+ content = [{"type": "text", "text": content}]+ if not isinstance(content, list):+ return []+ parts = []+ for position, block in enumerate(content):+ if not isinstance(block, dict):+ continue+ text = block.get("text") if isinstance(block.get("text"), str) else ""+ if block.get("type") == "text":+ text = _user_text(text) if role == "user" else clean_text(_REDACTED.sub("", text))+ if text:+ parts.append({"type": "text", "text": text})+ elif block.get("type") == "tool_use" and role == "assistant":+ parts.append(tool_call(f"{message_id}-{position}", block))+ return parts+++def read_transcript(path: Path, thread_id: str, session_id: str) -> Transcript:+ created, updated = file_times_ms(path)+ messages: list[dict] = []+ for record in read_jsonl(path):+ role, message = record.get("role"), record.get("message")+ if role not in ("user", "assistant") or not isinstance(message, dict):+ continue+ message_id = stable_id("cursor", session_id, str(len(messages)), length = 16)+ parts = _parts(role, message.get("content"), message_id)+ if not parts:+ continue+ messages.append(+ {+ "id": message_id,+ "threadId": thread_id,+ "parentId": messages[-1]["id"] if messages else None,+ "role": role,+ "content": parts,+ "createdAt": created + len(messages),+ "metadata": {"importedFrom": "cursor", "cursorSessionId": session_id},+ }+ )+ return Transcript(+ session_id = session_id,+ thread_id = thread_id,+ title = title_from(first_user_text(messages), "Cursor session"),+ created_at_ms = created,+ updated_at_ms = max(updated, created + max(0, len(messages) - 1)),+ messages = messages,+ )+++SOURCE = Source(+ key = "cursor",+ label = "Cursor",+ home_env = "UNSLOTH_CURSOR_HOME",+ default_home = ".cursor",+ list_projects = list_projects,+ read_transcript = read_transcript,+)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 328ba9d20a2..203b95df2d0 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -332,6 +332,7 @@ from routes import (data_recipe_router,datasets_router,export_router,+ external_import_router,inference_router,inference_studio_router,mcp_servers_router,@@ -1765,6 +1766,7 @@ app.include_router(engines_router, prefix = "/api/engines", tags = ["engines"])app.include_router(whisper_router, prefix = "/api/whisper", tags = ["whisper"])app.include_router(npu_router, prefix = "/api/npu", tags = ["npu"])app.include_router(export_router, prefix = "/api/export", tags = ["export"])+app.include_router(external_import_router, prefix = "/api/import", tags = ["import"])app.include_router(rag_router, prefix = "/api/rag", tags = ["rag"])app.include_router(training_history_router, prefix = "/api/train", tags = ["training-history"])app.include_router(hub_inventory_router, prefix = "/api/hub", tags = ["hub"])diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.pyindex 9e99e7b37be..372a571fec8 100644--- a/studio/backend/routes/__init__.py+++ b/studio/backend/routes/__init__.py@@ -15,6 +15,7 @@ from routes.data_recipe import router as data_recipe_routerfrom routes.export import router as export_routerfrom routes.training_history import router as training_history_routerfrom routes.chat_history import router as chat_history_router+from routes.external_import import router as external_import_routerfrom routes.providers import router as providers_routerfrom routes.openai_codex_auth import router as openai_codex_auth_router@@ -38,6 +39,7 @@ __all__ = ["export_router","training_history_router","chat_history_router",+ "external_import_router","providers_router","openai_codex_auth_router","mcp_servers_router",diff --git a/studio/backend/routes/external_import.py b/studio/backend/routes/external_import.pynew file mode 100644index 00000000000..ed689b41011--- /dev/null+++ b/studio/backend/routes/external_import.py@@ -0,0 +1,64 @@+# 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 Cursor / Claude Code / Codex conversations from this machine's disk into Studio."""++from typing import Literal++from fastapi import APIRouter, Depends+from pydantic import BaseModel++from auth.authentication import get_current_subject+from auth.policy import OwnerOnly+from core.external_import import run_import, sources+from loggers import get_logger+from utils.account_context import is_owner_context+from utils.utils import log_and_http_error++router = APIRouter()++logger = get_logger(__name__)++SourceKey = Literal["cursor", "claude", "codex"]+++class ExternalImportStatus(BaseModel):+ available: bool = False+ chats: int = 0+++class ExternalImportResult(BaseModel):+ projects: int = 0+ chats: int = 0+ new_chats: int = 0+ messages: int = 0+ skipped: int = 0+ warnings: list[str] = []++[email protected]("/{source}/status", response_model = ExternalImportStatus)+def external_import_status(source: SourceKey, current_subject: str = Depends(get_current_subject)):+ # The host home is the owner's: a managed account never sees its histories.+ if not is_owner_context():+ return ExternalImportStatus()+ try:+ chats = sources()[source].session_count()+ except OSError as exc:+ logger.warning("external_import_status_failed", source = source, error = str(exc))+ return ExternalImportStatus()+ return ExternalImportStatus(available = bool(chats), chats = chats)++[email protected]("/{source}", response_model = ExternalImportResult, dependencies = [OwnerOnly])+def external_import(source: SourceKey, current_subject: str = Depends(get_current_subject)):+ try:+ summary = run_import(sources()[source])+ except OSError as exc:+ raise log_and_http_error(+ exc,+ 500,+ f"Could not read {sources()[source].label}'s conversations.",+ event = "external_import_failed",+ log = logger,+ ) from exc+ return ExternalImportResult(**vars(summary))diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 6cfc35c16c1..ed78ad570c1 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -792,6 +792,18 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:) WITHOUT ROWID""")+ # Import ledger: without it a re-import cannot tell a turn deleted in Studio from a newly appended one.+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS external_import_sessions (+ source TEXT NOT NULL,+ session_id TEXT NOT NULL,+ turns_imported INTEGER NOT NULL,+ revision TEXT NOT NULL DEFAULT '',+ PRIMARY KEY (source, session_id)+ ) WITHOUT ROWID+ """+ )conn.execute("""CREATE TABLE IF NOT EXISTS prompt_entries (@@ -2552,6 +2564,18 @@ def _reparent_surviving_forks(conn: sqlite3.Connection, deleted_ids: set[str]) -)+def lift_chat_thread_tombstones(thread_ids: Iterable[str]) -> None:+ """Forget these deleted thread ids, so an import into an emptied Studio can recreate them."""+ conn = get_connection()+ try:+ conn.executemany(+ "DELETE FROM chat_thread_tombstones WHERE id = ?", [(i,) for i in set(thread_ids)]+ )+ conn.commit()+ finally:+ conn.close()++def _tombstone_chat_threads(conn: sqlite3.Connection, thread_ids: Iterable[str]) -> None:deleted_at = int(datetime.now(timezone.utc).timestamp() * 1000)conn.executemany(@@ -5411,3 +5435,42 @@ def upsert_chat_legacy_imports(legacy_thread_ids: list[str]) -> tuple[int, int]:return len(ids), insertedfinally:conn.close()+++def get_external_import_mark(source: str, session_id: str) -> Optional[tuple[int, str]]:+ """(turns brought over, source revision they came from), or None if never imported."""+ conn = get_connection()+ try:+ row = conn.execute(+ "SELECT turns_imported, revision FROM external_import_sessions"+ " WHERE source = ? AND session_id = ?",+ (source, session_id),+ ).fetchone()+ return None if row is None else (row["turns_imported"], row["revision"])+ finally:+ conn.close()+++def record_external_import_mark(+ source: str,+ session_id: str,+ turns: int,+ revision: str = "",+) -> None:+ conn = get_connection()+ try:+ conn.execute(+ """+ INSERT INTO external_import_sessions (source, session_id, turns_imported, revision)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(source, session_id) DO UPDATE SET+ turns_imported = CASE WHEN excluded.revision = external_import_sessions.revision+ THEN MAX(excluded.turns_imported, external_import_sessions.turns_imported)+ ELSE excluded.turns_imported END,+ revision = excluded.revision+ """,+ (source, session_id, int(turns), revision),+ )+ conn.commit()+ finally:+ conn.close()diff --git a/studio/backend/tests/test_external_import.py b/studio/backend/tests/test_external_import.pynew file mode 100644index 00000000000..c45fb0a265e--- /dev/null+++ b/studio/backend/tests/test_external_import.py@@ -0,0 +1,693 @@+# 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 json+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import storage.studio_db as studio_db+from auth.authentication import get_current_subject+from core.external_import import (+ claude,+ codex,+ cursor,+ display_name,+ project_id_for,+ run_import,+ thread_id_for,+)+from routes.external_import import router+++def _write(path: Path, records: list[dict]) -> Path:+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text("\n".join(json.dumps(r) for r in records) + "\n", encoding = "utf-8")+ return path+++def _append(path: Path, records: list[dict]) -> None:+ with path.open("a", encoding = "utf-8") as handle:+ handle.write("".join(json.dumps(r) + "\n" for r in records))+++def c_user(+ uuid,+ content,+ parent = None,+ ts = "2026-08-01T10:00:00Z",+ **extra,+):+ return {+ "type": "user",+ "uuid": uuid,+ "parentUuid": parent,+ "timestamp": ts,+ "message": {"role": "user", "content": content},+ **extra,+ }+++def c_asst(+ uuid,+ content,+ parent = None,+ ts = "2026-08-01T10:00:01Z",+ **extra,+):+ return {+ "type": "assistant",+ "uuid": uuid,+ "parentUuid": parent,+ "timestamp": ts,+ "message": {"role": "assistant", "content": content},+ **extra,+ }+++def k_turn(role, text):+ return {"role": role, "message": {"content": [{"type": "text", "text": text}]}}+++def x_line(+ kind,+ payload,+ ts = "2026-09-22T12:00:00Z",+):+ return {"timestamp": ts, "type": kind, "payload": payload}+++def _rollout(+ home,+ cwd = "/Users/me/app",+ sid = "019a",+ source = "cli",+ body = None,+ root = "sessions",+ **meta,+):+ path = home / root / "2026" / "09" / "22" / f"rollout-2026-09-22T12-00-00-{sid}.jsonl"+ return _write(+ path,+ [+ x_line(+ "session_meta",+ {"id": sid, "cwd": cwd, "source": source, "originator": "codex_cli_rs", **meta},+ ),+ x_line(+ "response_item",+ {+ "type": "message",+ "role": "developer",+ "content": [{"type": "input_text", "text": "<permissions instructions>"}],+ },+ ),+ x_line(+ "response_item",+ {+ "type": "message",+ "role": "user",+ "content": [+ {+ "type": "input_text",+ "text": "<environment_context>cwd</environment_context>",+ }+ ],+ },+ ),+ *(+ body+ if body is not None+ else [+ x_line("event_msg", {"type": "user_message", "message": "List the files"}),+ x_line(+ "response_item",+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "List the files"}],+ },+ ),+ x_line(+ "response_item",+ {"type": "reasoning", "summary": [], "encrypted_content": "x"},+ ),+ x_line(+ "response_item",+ {+ "type": "function_call",+ "name": "shell",+ "arguments": '{"command": ["ls"]}',+ "call_id": "c1",+ },+ ),+ x_line(+ "response_item",+ {"type": "function_call_output", "call_id": "c1", "output": "a.py"},+ ts = "2026-09-22T12:00:02Z",+ ),+ x_line(+ "response_item",+ {+ "type": "custom_tool_call",+ "name": "apply_patch",+ "input": "*** Begin Patch",+ "call_id": "c2",+ },+ ),+ x_line(+ "response_item",+ {+ "type": "custom_tool_call_output",+ "call_id": "c2",+ "output": [{"type": "input_text", "text": "Done!"}],+ },+ ),+ x_line(+ "event_msg",+ {"type": "agent_message", "message": "One file: a.py"},+ ts = "2026-09-22T12:00:03Z",+ ),+ x_line(+ "response_item",+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "One file: a.py"}],+ },+ ),+ ]+ ),+ ],+ )+++def codex_home(tmp_path, monkeypatch):+ home = tmp_path / "codex"+ monkeypatch.setenv(codex.SOURCE.home_env, str(home))+ return home+++def claude_home(tmp_path, monkeypatch):+ home = tmp_path / "claude"+ monkeypatch.setenv(claude.SOURCE.home_env, str(home))+ return home+++def cursor_home(tmp_path, monkeypatch):+ home = tmp_path / "cursor"+ monkeypatch.setenv(cursor.SOURCE.home_env, str(home))+ return home+++def _session(+ home,+ slug = "-Users-me-app",+ sid = "s1",+ records = None,+):+ return _write(+ home / "projects" / slug / f"{sid}.jsonl",+ records+ or [+ c_user("u1", "Fix the header"),+ c_asst("a1", [{"type": "text", "text": "Fixed it."}], parent = "u1"),+ ],+ )+++def _messages(source, sid):+ return studio_db.list_chat_messages(thread_id_for(source, sid))+++# Parsing+++def test_claude_keeps_the_conversation_and_drops_the_harness(claude_home):+ path = _session(+ claude_home,+ records = [+ c_user("m0", "<command-name>/clear</command-name>"),+ c_user("u1", "Fix it\n<local-command-stdout>noise</local-command-stdout>"),+ c_asst(+ "a1",+ [+ {"type": "thinking", "thinking": "hmm"},+ {"type": "tool_use", "id": "t1", "name": "Bash", "input": {"cmd": "ls"}},+ ],+ parent = "u1",+ ),+ c_user(+ "r1", [{"type": "tool_result", "tool_use_id": "t1", "content": "a.py"}], parent = "a1"+ ),+ c_asst("a2", [{"type": "text", "text": "Done."}], parent = "r1"),+ c_asst("side", [{"type": "text", "text": "subagent"}], isSidechain = True),+ c_user("meta", "caveat", isMeta = True),+ ],+ )+ t = claude.read_transcript(path, "t", "s1")++ assert [(m["role"], m["content"][0].get("text")) for m in t.messages] == [+ ("user", "Fix it"),+ ("assistant", None),+ ("assistant", "Done."),+ ]+ assert t.messages[1]["content"] == [+ {+ "type": "tool-call",+ "toolCallId": "t1",+ "toolName": "Bash",+ "args": {"cmd": "ls"},+ "result": "a.py",+ }+ ]+ # The tool-result record is skipped, so the answer hangs off the call.+ assert t.messages[2]["parentId"] == t.messages[1]["id"]+ assert t.title == "Fix it"+ assert t.messages[0]["createdAt"] == 1785578400000+++def test_claude_rewinds_keep_their_branch(claude_home):+ path = _session(+ claude_home,+ records = [+ c_user("u1", "one"),+ c_asst("a1", [{"type": "text", "text": "A"}], parent = "u1"),+ c_user("u2", "two", parent = "a1"),+ c_user("u2b", "two again", parent = "a1"),+ ],+ )+ ids = [m["id"] for m in claude.read_transcript(path, "t", "s1").messages]+ parents = [m["parentId"] for m in claude.read_transcript(path, "t", "s1").messages]+ assert parents == [None, ids[0], ids[1], ids[1]]+++def test_cursor_reads_the_query_and_strips_injected_context(cursor_home):+ path = _write(+ cursor_home / "projects" / "p" / "agent-transcripts" / "s1" / "s1.jsonl",+ [+ k_turn("user", "<attached_files>x</attached_files><user_query>Why slow?</user_query>"),+ {+ "role": "assistant",+ "message": {+ "content": [+ {"type": "text", "text": "[REDACTED]\nSource maps."},+ {"type": "tool_use", "name": "Read", "input": {"path": "a"}},+ ]+ },+ },+ {"type": "session_event"},+ ],+ )+ t = cursor.read_transcript(path, "t", "s1")++ assert t.messages[0]["content"] == [{"type": "text", "text": "Why slow?"}]+ assert t.messages[1]["content"][0] == {"type": "text", "text": "Source maps."}+ assert t.messages[1]["content"][1]["toolName"] == "Read"+ assert t.messages[1]["parentId"] == t.messages[0]["id"]+++def test_codex_replays_events_not_the_injected_context(codex_home):+ t = codex.read_transcript(_rollout(codex_home), "t", "s1")++ assert [m["role"] for m in t.messages] == ["user", "assistant", "assistant", "assistant"]+ assert t.messages[0]["content"] == [{"type": "text", "text": "List the files"}]+ assert t.messages[1]["content"] == [+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "shell",+ "args": {"command": ["ls"]},+ "result": "a.py",+ }+ ]+ assert t.messages[2]["content"][0]["args"] == {"input": "*** Begin Patch"}+ assert t.messages[2]["content"][0]["result"] == "Done!"+ assert t.messages[3]["content"] == [{"type": "text", "text": "One file: a.py"}]+ assert t.title == "List the files"+++def test_codex_groups_by_cwd_and_skips_subagents(codex_home, monkeypatch):+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: Path("/Users/me")))+ _rollout(codex_home, sid = "a")+ _rollout(codex_home, sid = "b")+ _rollout(codex_home, cwd = "/srv/api", sid = "c")+ _rollout(codex_home, sid = "d", source = {"subagent": "review"})++ projects = {p.name: sorted(s.name for s in p.sessions) for p in codex.list_projects(codex_home)}+ assert projects == {+ "app": ["rollout-2026-09-22T12-00-00-a.jsonl", "rollout-2026-09-22T12-00-00-b.jsonl"],+ "srv-api": ["rollout-2026-09-22T12-00-00-c.jsonl"],+ }+++def test_codex_compressing_a_rollout_keeps_its_chat(codex_home):+ zstandard = pytest.importorskip("zstandard")+ path = _rollout(codex_home)+ assert run_import(codex.SOURCE).new_chats == 1+ zst = path.with_name(path.name + ".zst")+ zst.write_bytes(zstandard.ZstdCompressor().compress(path.read_bytes()))+ path.unlink()++ again = run_import(codex.SOURCE)+ assert (again.new_chats, again.messages, again.warnings) == (0, 0, [])+++def test_codex_without_a_zstd_decoder_warns_instead_of_failing(codex_home, monkeypatch):+ import builtins++ path = _rollout(codex_home)+ path.rename(path.with_name(path.name + ".zst"))+ real_import = builtins.__import__++ def no_zstd(name, *args, **kwargs):+ if name in ("zstandard", "compression"):+ raise ImportError(name)+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", no_zstd)+ summary = run_import(codex.SOURCE)+ assert summary.new_chats == 0+ assert summary.warnings and "zstandard" in summary.warnings[0]+++# Discovery+++def test_project_names_drop_the_home_folder(monkeypatch):+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: Path("/Users/me")))+ assert display_name("-Users-me-dev-my-app") == "dev-my-app"+ assert display_name("users-ME-x") == "x"+ assert display_name("-opt-tool") == "opt-tool"+++def test_cursor_files_a_shared_session_under_its_folder(cursor_home):+ for slug in (cursor.NO_FOLDER_SLUG, "Users-me-app"):+ _write(+ cursor_home / "projects" / slug / "agent-transcripts" / "s1" / "s1.jsonl",+ [k_turn("user", "hi")],+ )+ _write(+ cursor_home / "projects" / cursor.NO_FOLDER_SLUG / "agent-transcripts" / "s2.jsonl",+ [k_turn("user", "yo")],+ )++ projects = {p.slug: [s.stem for s in p.sessions] for p in cursor.list_projects(cursor_home)}+ assert projects == {"Users-me-app": ["s1"], cursor.NO_FOLDER_SLUG: ["s2"]}+++# Importing+++def test_import_groups_by_project_and_a_second_run_is_a_no_op(claude_home):+ _session(claude_home)+ first = run_import(claude.SOURCE)+ second = run_import(claude.SOURCE)++ assert (first.projects, first.chats, first.new_chats, first.messages) == (1, 1, 1, 2)+ assert (second.new_chats, second.messages) == (0, 0)+ assert studio_db.get_chat_project(project_id_for(claude.SOURCE, "-Users-me-app"))[+ "name"+ ].startswith("Claude · ")+++def test_reimport_appends_new_turns_and_keeps_studio_edits(claude_home):+ path = _session(claude_home)+ run_import(claude.SOURCE)+ tid = thread_id_for(claude.SOURCE, "s1")+ studio_db.update_chat_thread(tid, {"title": "Renamed", "projectId": None})+ first, second = _messages(claude.SOURCE, "s1")+ # Edit the prompt, delete the reply.+ studio_db.sync_chat_messages(+ tid, [{**first, "content": [{"type": "text", "text": "edited"}]}], prune_missing = True+ )+ _append(path, [c_user("u2", "More", parent = "a1", ts = "2026-08-01T10:00:02Z")])++ summary = run_import(claude.SOURCE)+ thread = studio_db.get_chat_thread(tid)+ rows = {m["id"]: m for m in _messages(claude.SOURCE, "s1")}++ assert summary.messages == 1+ assert (thread["title"], thread["projectId"]) == ("Renamed", None)+ assert rows[first["id"]]["content"][0]["text"] == "edited"+ assert second["id"] not in rows+ new = next(m for m in rows.values() if m["content"][0].get("text") == "More")+ assert new["parentId"] in rows+++def test_a_deleted_chat_stays_deleted_until_studio_is_emptied(claude_home):+ _session(claude_home, sid = "s1")+ _session(claude_home, sid = "s2")+ run_import(claude.SOURCE)+ studio_db.delete_chat_threads([thread_id_for(claude.SOURCE, "s1")])++ assert run_import(claude.SOURCE).skipped == 1+ assert studio_db.get_chat_thread(thread_id_for(claude.SOURCE, "s1")) is None++ studio_db.delete_chat_threads([t["id"] for t in studio_db.list_chat_threads()])+ assert run_import(claude.SOURCE).new_chats == 2+++def test_a_tool_result_that_arrives_later_reaches_the_stored_call(claude_home):+ path = _session(+ claude_home,+ records = [+ c_user("u1", "List"),+ c_asst(+ "a1", [{"type": "tool_use", "id": "t1", "name": "Bash", "input": {}}], parent = "u1"+ ),+ ],+ )+ run_import(claude.SOURCE)+ _append(+ path,+ [+ c_user(+ "r1", [{"type": "tool_result", "tool_use_id": "t1", "content": "out"}], parent = "a1"+ )+ ],+ )+ run_import(claude.SOURCE)++ call = _messages(claude.SOURCE, "s1")[1]["content"][0]+ assert call["result"] == "out"+++def test_an_interrupted_import_is_retried(claude_home):+ _session(claude_home)+ transcript = claude.read_transcript(+ next((claude_home / "projects").rglob("*.jsonl")), thread_id_for(claude.SOURCE, "s1"), "s1"+ )+ studio_db.upsert_chat_thread(+ {+ "id": transcript.thread_id,+ "title": "x",+ "modelType": "base",+ "modelId": "",+ "createdAt": 1,+ "updatedAt": 1,+ }+ )++ assert run_import(claude.SOURCE).messages == 2+++# Routes+++def client():+ app = FastAPI()+ app.include_router(router, prefix = "/api/import")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app)+++def test_routes_report_status_and_import(client, claude_home, cursor_home, codex_home):+ _session(claude_home)+ assert client.get("/api/import/claude/status").json() == {"available": True, "chats": 1}+ assert client.get("/api/import/cursor/status").json()["available"] is False+ assert client.get("/api/import/codex/status").json()["available"] is False+ body = client.post("/api/import/claude").json()+ assert (body["new_chats"], body["messages"], body["warnings"]) == (1, 2, [])+ assert client.post("/api/import/vscode").status_code == 422+++def test_routes_need_a_signed_in_user(claude_home):+ app = FastAPI()+ app.include_router(router, prefix = "/api/import")+ assert TestClient(app).post("/api/import/claude").status_code in (401, 403)++[email protected]("source", ["claude", "cursor", "codex"])+def test_a_managed_account_cannot_reach_the_owners_histories(+ claude_home, cursor_home, codex_home, source+):+ from utils.account_context import AccountContext, bind_account, reset_account++ _session(claude_home)+ _write(+ cursor_home / "projects" / "p" / "agent-transcripts" / "s1.jsonl", [k_turn("user", "hi")]+ )+ app = FastAPI()+ app.include_router(router, prefix = "/api/import")+ app.dependency_overrides[get_current_subject] = lambda: "alice"++ @app.middleware("http")+ async def as_managed_account(request, call_next):+ token = bind_account(AccountContext("acct-alice", "alice"))+ try:+ return await call_next(request)+ finally:+ reset_account(token)++ managed = TestClient(app)+ assert managed.get(f"/api/import/{source}/status").json()["available"] is False+ assert managed.post(f"/api/import/{source}").status_code == 403+ assert studio_db.list_chat_threads() == []+++def test_every_appended_branch_is_reparented_past_a_deleted_message(claude_home):+ path = _session(+ claude_home,+ records = [+ c_user("u1", "one"),+ c_asst("a1", [{"type": "text", "text": "A"}], parent = "u1"),+ ],+ )+ run_import(claude.SOURCE)+ tid = thread_id_for(claude.SOURCE, "s1")+ studio_db.sync_chat_messages(tid, _messages(claude.SOURCE, "s1")[:1], prune_missing = True)+ # Two rewinds off the deleted reply.+ _append(path, [c_user("u2", "two", parent = "a1"), c_user("u3", "three", parent = "a1")])+ run_import(claude.SOURCE)++ rows = _messages(claude.SOURCE, "s1")+ ids = {m["id"] for m in rows}+ assert len(rows) == 3+ assert all(m["parentId"] is None or m["parentId"] in ids for m in rows)+++def test_an_emptied_studio_keeps_unrelated_tombstones(claude_home):+ _session(claude_home)+ studio_db.upsert_chat_thread(+ {+ "id": "native",+ "title": "mine",+ "modelType": "base",+ "modelId": "",+ "createdAt": 1,+ "updatedAt": 1,+ }+ )+ studio_db.delete_chat_threads(["native"])++ assert run_import(claude.SOURCE).new_chats == 1+ with pytest.raises(studio_db.ChatThreadDeletedError):+ studio_db.upsert_chat_thread(+ {+ "id": "native",+ "title": "stale tab",+ "modelType": "base",+ "modelId": "",+ "createdAt": 1,+ "updatedAt": 2,+ }+ )+++def test_codex_cwds_that_only_differ_in_punctuation_stay_apart(codex_home):+ _rollout(codex_home, cwd = "/work/a-b", sid = "a")+ _rollout(codex_home, cwd = "/work/a/b", sid = "b")+ assert len(codex.list_projects(codex_home)) == 2+++def test_codex_status_counts_rollouts_without_opening_them(codex_home, monkeypatch):+ _rollout(codex_home, sid = "a")+ _rollout(codex_home, sid = "b")+ monkeypatch.setattr(codex, "_meta", lambda path: pytest.fail("status must not parse rollouts"))+ assert codex.SOURCE.session_count() == 2+++def test_codex_reads_archived_rollouts_once(codex_home):+ _rollout(codex_home, sid = "a")+ _rollout(codex_home, sid = "b", root = "archived_sessions")+ _rollout(codex_home, sid = "a", root = "archived_sessions")++ sessions = sorted(s.name for p in codex.list_projects(codex_home) for s in p.sessions)+ assert sessions == [+ "rollout-2026-09-22T12-00-00-a.jsonl",+ "rollout-2026-09-22T12-00-00-b.jsonl",+ ]+++def _continuation(home, name, thread, base_thread, cut, text):+ meta = {+ "id": thread,+ "cwd": "/Users/me/app",+ "source": "cli",+ "history_base": {"thread_id": base_thread, "end_ordinal_exclusive": cut},+ }+ path = home / "sessions" / "2026" / "09" / "23" / f"rollout-2026-09-23T12-00-00-{name}.jsonl"+ return _write(+ path,+ [+ {**x_line("session_meta", meta), "ordinal": cut},+ {**x_line("event_msg", {"type": "user_message", "message": text}), "ordinal": cut + 1},+ ],+ )+++def test_codex_revert_and_fork_rebuild_the_inherited_prefix(codex_home):+ base = _rollout(codex_home, sid = "t1")+ lines = [json.loads(line) for line in base.read_text().splitlines()]+ base.write_text("".join(json.dumps({**r, "ordinal": i}) + "\n" for i, r in enumerate(lines)))+ assert run_import(codex.SOURCE).new_chats == 1+ tid = thread_id_for(codex.SOURCE, "t1")+ before = [m["id"] for m in _messages(codex.SOURCE, "t1")]++ # Revert to just after the first prompt (ordinal 4), then a new prompt; plus a fork there.+ _continuation(codex_home, "t1_r2", "t1", "t1", 4, "Try again")+ _continuation(codex_home, "f1", "f1", "t1", 4, "Forked question")+ summary = run_import(codex.SOURCE)++ rows = {m["id"]: m for m in studio_db.list_chat_messages(tid)}+ retry = next(m for m in rows.values() if m["content"][0].get("text") == "Try again")+ assert set(before) <= set(rows) # the reverted turns stay, as a sibling branch+ assert rows[retry["parentId"]]["content"][0]["text"] == "List the files"+ assert summary.new_chats == 1 # the fork, not a second copy of the reverted thread+ fork = [m["content"][0].get("text") for m in _messages(codex.SOURCE, "f1")]+ assert fork == ["List the files", "Forked question"]++ # A fork of the revert names the replacement rollout ("r2"), not the thread id.+ _continuation(codex_home, "f2", "f2", "r2", 6, "Fork of the retry")+ run_import(codex.SOURCE)+ rows = {m["id"]: m for m in _messages(codex.SOURCE, "f2")}+ tip = next(m for m in rows.values() if m["content"][0].get("text") == "Fork of the retry")+ chain = []+ while tip:+ chain.append(tip["content"][0].get("text"))+ tip = rows.get(tip["parentId"])+ assert chain == ["Fork of the retry", "Try again", "List the files"]+++def test_an_empty_tool_output_still_completes_the_call(claude_home):+ path = _session(+ claude_home,+ records = [+ c_user("u1", "Touch it"),+ c_asst(+ "a1", [{"type": "tool_use", "id": "t1", "name": "Bash", "input": {}}], parent = "u1"+ ),+ c_user(+ "r1", [{"type": "tool_result", "tool_use_id": "t1", "content": ""}], parent = "a1"+ ),+ ],+ )+ call = claude.read_transcript(path, "t", "s1").messages[1]["content"][0]+ assert call["result"] == ""diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 7f12f1de38e..c3339f96e9b 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -164,7 +164,7 @@ export function notifyChatHistoryUpdated(}}-function notifyChatProjectsUpdated(): void {+export function notifyChatProjectsUpdated(): void {notifyChatHistoryUpdated();if (typeof window !== "undefined") {window.dispatchEvent(new Event(CHAT_PROJECTS_UPDATED_EVENT));diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 21272f21093..063eaf7a15e 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -25,6 +25,7 @@ export {loadModel,unloadModel,notifyChatHistoryUpdated,+ notifyChatProjectsUpdated,removeScanFolder,revealCachedModel,revealFineTunedModel,diff --git a/studio/frontend/src/features/settings/api/external-import.ts b/studio/frontend/src/features/settings/api/external-import.tsnew file mode 100644index 00000000000..ac613511513--- /dev/null+++ b/studio/frontend/src/features/settings/api/external-import.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++export const EXTERNAL_IMPORT_SOURCES = ["cursor", "claude", "codex"] as const;++export type ExternalImportSource = (typeof EXTERNAL_IMPORT_SOURCES)[number];++export const EXTERNAL_IMPORT_LABELS: Record<ExternalImportSource, string> = {+ cursor: "Cursor",+ claude: "Claude Code",+ codex: "Codex",+};++export type ExternalImportStatus = {+ available: boolean;+ chats: number;+};++export type ExternalImportResult = {+ newChats: number;+ messages: number;+ warnings: string[];+};++async function request<T>(path: string, init?: RequestInit): Promise<T> {+ const res = await authFetch(path, init);+ if (!res.ok) {+ throw new Error(await readFastApiError(res, "External import failed"));+ }+ return res.json();+}++export function loadExternalImportStatus(+ source: ExternalImportSource,+): Promise<ExternalImportStatus> {+ return request(`/api/import/${source}/status`);+}++export async function importExternalChats(+ source: ExternalImportSource,+): Promise<ExternalImportResult> {+ const result = await request<{+ new_chats: number;+ messages: number;+ warnings: string[];+ }>(`/api/import/${source}`, { method: "POST" });+ return {+ newChats: result.new_chats,+ messages: result.messages,+ warnings: result.warnings,+ };+}diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex 5d859628ece..ca874742869 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -47,6 +47,7 @@ import {nativeImportSource,fileImportSource,type ImportSource,+ notifyChatProjectsUpdated,offerToDeleteKeptSandboxes,useChatPreferencesStore,useChatRuntimeStore,@@ -92,6 +93,14 @@ import { MessageCircleIcon } from "@/lib/hugeicons-derived";import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate, useRouterState } from "@tanstack/react-router";import { useEffect, useRef, useState } from "react";+import {+ EXTERNAL_IMPORT_LABELS,+ EXTERNAL_IMPORT_SOURCES,+ type ExternalImportSource,+ type ExternalImportStatus,+ importExternalChats,+ loadExternalImportStatus,+} from "../api/external-import";import { ArchivedChatsView } from "../components/archived-chats-dialog";import {type ArchivedMediaKind,@@ -207,6 +216,12 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {});const [clearing, setClearing] = useState(false);const [archiving, setArchiving] = useState(false);+ // A source's row appears only once its probe reports conversations.+ const [externalStatus, setExternalStatus] = useState<+ Partial<Record<ExternalImportSource, ExternalImportStatus>>+ >({});+ const [externalImporting, setExternalImporting] =+ useState<ExternalImportSource | null>(null);const [fineTuneExporting, setFineTuneExporting] = useState(false);const [openingRecipe, setOpeningRecipe] = useState(false);const [loadingTraining, setLoadingTraining] = useState(false);@@ -318,6 +333,22 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {};}, [subpage, t]);+ const refreshExternalStatus = (source: ExternalImportSource) =>+ loadExternalImportStatus(source)+ .catch(() => null)+ .then((status) =>+ setExternalStatus((prev) => ({+ ...prev,+ [source]: status?.available ? status : undefined,+ })),+ );++ useEffect(() => {+ for (const source of EXTERNAL_IMPORT_SOURCES) {+ void refreshExternalStatus(source);+ }+ }, []);+const handleExport = async () => {setExporting(true);try {@@ -432,6 +463,43 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {}};+ const handleExternalImport = async (source: ExternalImportSource) => {+ setExternalImporting(source);+ try {+ const result = await importExternalChats(source);+ notifyChatProjectsUpdated();+ setCount(await countAllChats().catch(() => count));+ await refreshExternalStatus(source);+ const vars = { source: EXTERNAL_IMPORT_LABELS[source] };+ if (result.warnings.length > 0) {+ toast.warning(t("settings.chat.importedSourcePartial", vars), {+ description: result.warnings.join("\n"),+ });+ } else if (result.newChats === 0) {+ toast.success(+ result.messages > 0+ ? t("settings.chat.sourceUpdated", { ...vars, count: result.messages })+ : t("settings.chat.sourceUpToDate", vars),+ );+ } else {+ toast.success(+ result.newChats === 1+ ? t("settings.chat.importedSourceOneChat", vars)+ : t("settings.chat.importedSourceChatCount", {+ ...vars,+ count: result.newChats,+ }),+ );+ }+ } catch (error) {+ toast.error(t("settings.chat.importFailed"), {+ description: error instanceof Error ? error.message : String(error),+ });+ } finally {+ setExternalImporting(null);+ }+ };+const handleArchiveAll = async () => {setArchiving(true);try {@@ -859,6 +927,38 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {}}/></SettingsRow>+ {EXTERNAL_IMPORT_SOURCES.map((source) =>+ externalStatus[source] ? (+ <SettingsRow+ key={source}+ label={t("settings.chat.importFromSource", {+ source: EXTERNAL_IMPORT_LABELS[source],+ })}+ description={t("settings.chat.importFromSourceDescription", {+ source: EXTERNAL_IMPORT_LABELS[source],+ })}+ >+ <Button+ variant="outline"+ size="sm"+ onClick={() => void handleExternalImport(source)}+ disabled={externalImporting !== null}+ >+ {externalImporting === source ? (+ <Spinner className="size-3.5 mr-1.5" />+ ) : (+ <HugeiconsIcon+ icon={Upload01Icon}+ className="size-3.5 mr-1.5"+ />+ )}+ {externalImporting === source+ ? t("settings.chat.importingAction")+ : t("settings.chat.importChatsAction")}+ </Button>+ </SettingsRow>+ ) : null,+ )}<SettingsRowlabel={t("settings.chat.exportHistory")}description={t("settings.chat.exportHistoryDescription")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex fbc145c1bb6..321d2c783ca 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2453,6 +2453,16 @@ export const ar = {importingChats: "جارٍ استيراد المحادثات: {count} حتى الآن ({percent}%)...",importedChatCountPartial: "تم استيراد {count} محادثة إلى الأخيرة؛ تعذّر حفظ {failed} منها.",importFailed: "فشل الاستيراد.",+ importFromSource: "الاستيراد من {source}",+ importFromSourceDescription:+ "انسخ محادثاتك في {source} إلى Studio، مجمّعة حسب المشروع.",+ importingAction: "جارٍ الاستيراد...",+ importedSourceOneChat: "تم استيراد محادثة واحدة من {source}.",+ importedSourceChatCount:+ "تم استيراد المحادثات من {source}. العدد: {count}.",+ sourceUpdated: "تمت إضافة {count} رسالة جديدة من {source}.",+ sourceUpToDate: "محادثات {source} محدَّثة بالفعل.",+ importedSourcePartial: "تعذّر استيراد بعض محادثات {source}.",clearHistory: "مسح سجل المحادثات",clearHistoryDescription: "حذف سجل المحادثات من هذا الجهاز.",clearAction: "مسح",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex ac2bfb7368f..36027fa343d 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2492,6 +2492,16 @@ export const de = {importingChats: "Chats werden importiert: bisher {count} ({percent}%)...",importedChatCountPartial: "{count} Unterhaltungen in Zuletzt importiert; {failed} konnten nicht gespeichert werden.",importFailed: "Import fehlgeschlagen.",+ importFromSource: "Aus {source} importieren",+ importFromSourceDescription:+ "Kopieren Sie Ihre {source}-Konversationen nach Studio, gruppiert nach Projekt.",+ importingAction: "Wird importiert...",+ importedSourceOneChat: "1 Konversation aus {source} importiert.",+ importedSourceChatCount:+ "{count} Konversationen aus {source} importiert.",+ sourceUpdated: "{count} neue Nachrichten aus {source} hinzugefügt.",+ sourceUpToDate: "Die {source}-Konversationen sind bereits aktuell.",+ importedSourcePartial: "Einige {source}-Konversationen konnten nicht importiert werden.",clearHistory: "Chatverlauf löschen",clearHistoryDescription: "Chatverlauf von diesem Gerät löschen.",clearAction: "Löschen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 2f127b70c4d..0b7f1b33fdc 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2491,6 +2491,15 @@ export const en = {importingChats: "Importing chats: {count} so far ({percent}%)...",importedChatCountPartial: "Imported {count} conversations to Recents; {failed} could not be saved.",importFailed: "Import failed.",+ importFromSource: "Import from {source}",+ importFromSourceDescription:+ "Copy your {source} conversations into Studio, grouped by the project they belong to.",+ importingAction: "Importing...",+ importedSourceOneChat: "Imported 1 conversation from {source}.",+ importedSourceChatCount: "Imported {count} conversations from {source}.",+ sourceUpdated: "Added {count} new messages from {source}.",+ sourceUpToDate: "{source} conversations are already up to date.",+ importedSourcePartial: "Some {source} conversations could not be imported.",clearHistory: "Clear chat history",clearHistoryDescription: "Delete chat history from this device.",clearAction: "Clear",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 56d737c98f4..3db3c07171d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2482,6 +2482,18 @@ export const es = {importingChats: "Importando chats: {count} hasta ahora ({percent}%)...",importedChatCountPartial: "Se importaron {count} conversaciones a Recientes; {failed} no se pudieron guardar.",importFailed: "La importación falló.",+ importFromSource: "Importar desde {source}",+ importFromSourceDescription:+ "Copia tus conversaciones de {source} a Studio, agrupadas por proyecto.",+ importingAction: "Importando...",+ importedSourceOneChat: "Se importó 1 conversación desde {source}.",+ importedSourceChatCount:+ "Se importaron {count} conversaciones desde {source}.",+ sourceUpdated: "Se añadieron {count} mensajes nuevos desde {source}.",+ sourceUpToDate:+ "Las conversaciones de {source} ya están actualizadas.",+ importedSourcePartial:+ "No se pudieron importar algunas conversaciones de {source}.",clearHistory: "Borrar historial de chat",clearHistoryDescription: "Elimina el historial de chat de este dispositivo.",clearAction: "Borrar",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 3cf4b7ee967..fc1ea4bc24c 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2488,6 +2488,16 @@ export const fr = {importingChats: "Import des discussions : {count} jusqu'ici ({percent}%)...",importedChatCountPartial: "{count} conversations importées dans Récents ; {failed} n'ont pas pu être enregistrées.",importFailed: "Échec de l'importation.",+ importFromSource: "Importer depuis {source}",+ importFromSourceDescription:+ "Copiez vos conversations {source} dans Studio, regroupées par projet.",+ importingAction: "Importation...",+ importedSourceOneChat: "1 conversation importée depuis {source}.",+ importedSourceChatCount:+ "{count} conversations importées depuis {source}.",+ sourceUpdated: "{count} nouveaux messages ajoutés depuis {source}.",+ sourceUpToDate: "Les conversations {source} sont déjà à jour.",+ importedSourcePartial: "Certaines conversations {source} n'ont pas pu être importées.",clearHistory: "Effacer l'historique des discussions",clearHistoryDescription:"Supprimer l'historique des discussions de cet appareil.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 94cf1868495..4b3e7ca3ca0 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2459,6 +2459,16 @@ export const hi = {importingChats: "चैट इंपोर्ट हो रही हैं: अब तक {count} ({percent}%)...",importedChatCountPartial: "{count} बातचीत Recents में इंपोर्ट की गईं; {failed} सेव नहीं हो सकीं।",importFailed: "इंपोर्ट विफल रहा।",+ importFromSource: "{source} से इंपोर्ट करें",+ importFromSourceDescription:+ "अपने {source} वार्तालाप प्रोजेक्ट के अनुसार समूहित करके Studio में कॉपी करें।",+ importingAction: "इंपोर्ट हो रहा है...",+ importedSourceOneChat: "{source} से 1 वार्तालाप इंपोर्ट किया गया।",+ importedSourceChatCount:+ "{source} से {count} वार्तालाप इंपोर्ट किए गए।",+ sourceUpdated: "{source} से {count} नए संदेश जोड़े गए।",+ sourceUpToDate: "{source} वार्तालाप पहले से अद्यतित हैं।",+ importedSourcePartial: "कुछ {source} वार्तालाप इंपोर्ट नहीं हो सके।",clearHistory: "चैट इतिहास साफ़ करें",clearHistoryDescription: "इस डिवाइस से चैट इतिहास हटाएं।",clearAction: "साफ़ करें",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex f413523f411..1d122f3a215 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2447,6 +2447,16 @@ export const it = {importingChats: "Importazione chat: {count} finora ({percent}%)...",importedChatCountPartial: "Importate {count} conversazioni in Recenti; {failed} non sono state salvate.",importFailed: "Importazione non riuscita.",+ importFromSource: "Importa da {source}",+ importFromSourceDescription:+ "Copia le tue conversazioni di {source} in Studio, raggruppate per progetto.",+ importingAction: "Importazione...",+ importedSourceOneChat: "1 conversazione importata da {source}.",+ importedSourceChatCount:+ "{count} conversazioni importate da {source}.",+ sourceUpdated: "Aggiunti {count} nuovi messaggi da {source}.",+ sourceUpToDate: "Le conversazioni di {source} sono già aggiornate.",+ importedSourcePartial: "Alcune conversazioni di {source} non sono state importate.",clearHistory: "Cancella la cronologia delle chat",clearHistoryDescription:"Elimina la cronologia delle chat da questo dispositivo.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 103e98cf7b0..574ef56f670 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2435,6 +2435,16 @@ export const ja = {importingChats: "チャットをインポート中: 現在 {count} 件({percent}%)...",importedChatCountPartial: "{count} 件の会話を最近のチャットにインポートしました。{failed} 件は保存できませんでした。",importFailed: "インポートに失敗しました。",+ importFromSource: "{source} からインポート",+ importFromSourceDescription:+ "{source} の会話をプロジェクトごとにまとめて Studio にコピーします。",+ importingAction: "インポート中...",+ importedSourceOneChat: "{source} から 1 件の会話をインポートしました。",+ importedSourceChatCount:+ "{source} から {count} 件の会話をインポートしました。",+ sourceUpdated: "{source} から {count} 件の新しいメッセージを追加しました。",+ sourceUpToDate: "{source} の会話はすでに最新です。",+ importedSourcePartial: "一部の {source} の会話をインポートできませんでした。",clearHistory: "チャット履歴を消去",clearHistoryDescription: "このデバイスからチャット履歴を削除します。",clearAction: "消去",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex f723438ac47..e6c79cf7ae5 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2446,6 +2446,15 @@ export const ko = {importingChats: "채팅 가져오는 중: 현재 {count}개({percent}%)...",importedChatCountPartial: "{count}개의 대화를 최근 항목으로 가져왔습니다. {failed}개는 저장하지 못했습니다.",importFailed: "가져오기에 실패했습니다.",+ importFromSource: "{source}에서 가져오기",+ importFromSourceDescription:+ "{source}의 대화를 프로젝트별로 묶어 Studio로 복사합니다.",+ importingAction: "가져오는 중...",+ importedSourceOneChat: "{source}에서 대화 1개를 가져왔습니다.",+ importedSourceChatCount: "{source}에서 대화 {count}개를 가져왔습니다.",+ sourceUpdated: "{source}에서 새 메시지 {count}개를 추가했습니다.",+ sourceUpToDate: "{source} 대화가 이미 최신 상태입니다.",+ importedSourcePartial: "일부 {source} 대화를 가져오지 못했습니다.",clearHistory: "채팅 기록 지우기",clearHistoryDescription: "이 기기에서 채팅 기록을 삭제합니다.",clearAction: "지우기",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 4d24d6c2da1..608237c3177 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2469,6 +2469,16 @@ export const ptBR = {importingChats: "Importando chats: {count} até agora ({percent}%)...",importedChatCountPartial: "{count} conversas importadas para Recentes; {failed} não puderam ser salvas.",importFailed: "Falha na importação.",+ importFromSource: "Importar do {source}",+ importFromSourceDescription:+ "Copie suas conversas do {source} para o Studio, agrupadas por projeto.",+ importingAction: "Importando...",+ importedSourceOneChat: "1 conversa importada do {source}.",+ importedSourceChatCount:+ "{count} conversas importadas do {source}.",+ sourceUpdated: "{count} novas mensagens adicionadas do {source}.",+ sourceUpToDate: "As conversas do {source} já estão atualizadas.",+ importedSourcePartial: "Algumas conversas do {source} não puderam ser importadas.",clearHistory: "Limpar histórico de chat",clearHistoryDescription: "Exclui o histórico de chat deste dispositivo.",clearAction: "Limpar",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex c08c6c222e7..89aca400ff0 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2464,6 +2464,15 @@ export const ru = {importingChats: "Импорт чатов: пока {count} ({percent}%)...",importedChatCountPartial: "Импортировано {count} бесед в Недавние; {failed} не удалось сохранить.",importFailed: "Импорт не удался.",+ importFromSource: "Импорт из {source}",+ importFromSourceDescription:+ "Скопируйте свои диалоги из {source} в Studio с группировкой по проектам.",+ importingAction: "Импорт…",+ importedSourceOneChat: "Импортирован 1 диалог из {source}.",+ importedSourceChatCount: "Импортировано диалогов из {source}: {count}.",+ sourceUpdated: "Добавлено новых сообщений из {source}: {count}.",+ sourceUpToDate: "Диалоги {source} уже актуальны.",+ importedSourcePartial: "Некоторые диалоги {source} не удалось импортировать.",clearHistory: "Очистить историю чатов",clearHistoryDescription: "Удалить историю чатов с этого устройства.",clearAction: "Очистить",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex e5562a18c4b..2a1348f56c9 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2412,6 +2412,15 @@ export const zhCN = {importingChats: "正在导入对话:已完成 {count} 个({percent}%)...",importedChatCountPartial: "已将 {count} 个对话导入到最近对话;{failed} 个未能保存。",importFailed: "导入失败。",+ importFromSource: "从 {source} 导入",+ importFromSourceDescription:+ "将你在 {source} 中的对话按项目分组复制到 Studio。",+ importingAction: "导入中...",+ importedSourceOneChat: "已从 {source} 导入 1 个对话。",+ importedSourceChatCount: "已从 {source} 导入 {count} 个对话。",+ sourceUpdated: "已从 {source} 添加 {count} 条新消息。",+ sourceUpToDate: "{source} 对话已是最新。",+ importedSourcePartial: "部分 {source} 对话未能导入。",clearHistory: "清除聊天记录",clearHistoryDescription: "从此设备删除本地聊天记录。",clearAction: "清除",diff --git a/studio/frontend/tests/external-import-api.test.ts b/studio/frontend/tests/external-import-api.test.tsnew file mode 100644index 00000000000..2399300d051--- /dev/null+++ b/studio/frontend/tests/external-import-api.test.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// new_chats is snake_case on the wire; a missed rename reads as "already up to date".++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++// See helpers/auth-stub.mjs.+register("./helpers/settings-api-resolver.mjs", import.meta.url);+installLocalStorageFake();++let calls: string[] = [];+let nextStatus = 200;+let nextBody: unknown = {};++globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(+ typeof input === "string" ? input : (input as Request).url,+ );+ calls.push(`${init?.method ?? "GET"} ${url}`);+ return new Response(JSON.stringify(nextBody), {+ status: nextStatus,+ headers: { "Content-Type": "application/json" },+ });+}) as typeof fetch;++const { importExternalChats, loadExternalImportStatus } = await import(+ "../src/features/settings/api/external-import.ts"+);++test("the client hits each source's routes and maps new_chats", async () => {+ calls = [];+ nextStatus = 200;+ nextBody = { available: true, chats: 42 };+ assert.deepEqual(await loadExternalImportStatus("cursor"), nextBody);++ nextBody = {+ projects: 2,+ chats: 10,+ new_chats: 4,+ messages: 120,+ skipped: 1,+ warnings: [],+ };+ assert.deepEqual(await importExternalChats("claude"), {+ newChats: 4,+ messages: 120,+ warnings: [],+ });+ assert.deepEqual(calls, [+ "GET /api/import/cursor/status",+ "POST /api/import/claude",+ ]);+});++test("a failed import rejects rather than reporting an empty run", async () => {+ nextStatus = 500;+ nextBody = { detail: "Could not read Claude Code's conversations." };+ await assert.rejects(+ importExternalChats("claude"),+ /Could not read Claude Code/,+ );+});