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: read each thread's stored messages once per chat re-import (#16615)
Daniel Han79bf94e7c68b
diff --git a/studio/backend/core/external_import/__init__.py b/studio/backend/core/external_import/__init__.pyindex 46bd261e8ac..3d475030b51 100644--- a/studio/backend/core/external_import/__init__.py+++ b/studio/backend/core/external_import/__init__.py@@ -216,12 +216,13 @@ def _thread_row(transcript: Transcript, existing: dict, project_id: str) -> dict}-def _pending_messages(source: Source, transcript: Transcript, existing: bool) -> list[dict]:+def _pending_messages(+ source: Source, transcript: Transcript, existing: bool, stored: list[dict]+) -> 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.@@ -244,9 +245,9 @@ def _pending_messages(source: Source, transcript: Transcript, existing: bool) ->return reseated-def _late_tool_results(transcript: Transcript) -> list[dict]:+def _late_tool_results(transcript: Transcript, stored_rows: list[dict]) -> 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)}+ stored = {m["id"]: m for m in stored_rows}patched = []for message in transcript.messages:current = stored.get(message["id"])@@ -294,9 +295,11 @@ def _import_session(source: Source, path: Path, project_id: str, summary: Importexcept studio_db.ChatThreadDeletedError:summary.skipped += 1return False- pending = _pending_messages(source, transcript, bool(existing))+ # One read of the thread's rows serves both passes; nothing writes between them.+ stored = studio_db.list_chat_messages(thread_id) if existing else []+ pending = _pending_messages(source, transcript, bool(existing), stored)if existing:- pending = _late_tool_results(transcript) + pending+ pending = _late_tool_results(transcript, stored) + pendingmark = studio_db.ExternalImportMark(source = source.key,session_id = session_id,diff --git a/studio/backend/tests/test_external_import_single_read.py b/studio/backend/tests/test_external_import_single_read.pynew file mode 100644index 00000000000..3f095bab9c3--- /dev/null+++ b/studio/backend/tests/test_external_import_single_read.py@@ -0,0 +1,115 @@+# 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+import sys+from pathlib import Path++import pytest++import storage.studio_db as studio_db+from core.external_import import claude, run_import, thread_id_for+++def _write(path: Path, records: list[dict]) -> None:+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text("".join(json.dumps(r) + "\n" for r in records), encoding = "utf-8")+++def _user(+ uuid,+ content,+ parent = None,+):+ return {+ "type": "user",+ "uuid": uuid,+ "parentUuid": parent,+ "timestamp": "2026-08-01T10:00:00Z",+ "message": {"role": "user", "content": content},+ }+++def _assistant(uuid, content, parent):+ return {+ "type": "assistant",+ "uuid": uuid,+ "parentUuid": parent,+ "timestamp": "2026-08-01T10:00:01Z",+ "message": {"id": f"msg-{uuid}", "role": "assistant", "content": content},+ }+++def _count_importer_reads(monkeypatch, reads):+ """Counts reads made by the importer itself; studio_db calls the same function internally."""+ real = studio_db.list_chat_messages++ def counted(thread_id):+ if sys._getframe(1).f_globals.get("__name__") == "core.external_import":+ reads.append(thread_id)+ return real(thread_id)++ monkeypatch.setattr(studio_db, "list_chat_messages", counted)+ return real+++def claude_home(tmp_path, monkeypatch):+ home = tmp_path / "claude"+ monkeypatch.setenv(claude.SOURCE.home_env, str(home))+ return home+++def _open_call_session():+ return [+ _user("u1", "Read the file"),+ _assistant(+ "a1",+ [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"path": "x"}}],+ "u1",+ ),+ ]+++def _closed_call_tail():+ return [+ _user("r1", [{"type": "tool_result", "tool_use_id": "t1", "content": "body"}], "a1"),+ _assistant("a2", [{"type": "text", "text": "Done."}], "r1"),+ ]+++def test_reimport_reads_each_existing_thread_once(claude_home, monkeypatch):+ sessions = ["s1", "s2", "s3"]+ for sid in sessions:+ _write(claude_home / "projects" / "-Users-me-app" / f"{sid}.jsonl", _open_call_session())+ first = run_import(claude.SOURCE)+ assert (first.new_chats, first.messages) == (3, 6)++ for sid in sessions:+ _write(+ claude_home / "projects" / "-Users-me-app" / f"{sid}.jsonl",+ _open_call_session() + _closed_call_tail(),+ )+ reads = []+ real = _count_importer_reads(monkeypatch, reads)+ second = run_import(claude.SOURCE)+ monkeypatch.setattr(studio_db, "list_chat_messages", real)++ assert sorted(reads) == sorted(thread_id_for(claude.SOURCE, sid) for sid in sessions)+ # One patched tool call plus the new assistant turn per session.+ assert (second.new_chats, second.messages) == (0, 6)+ for sid in sessions:+ rows = real(thread_id_for(claude.SOURCE, sid))+ calls = [p for m in rows for p in m["content"] if p.get("type") == "tool-call"]+ assert [c.get("result") for c in calls] == ["body"]+ texts = [p.get("text") for m in rows for p in m["content"] if p.get("type") == "text"]+ assert texts.count("Done.") == 1+++def test_first_import_does_not_read_message_rows(claude_home, monkeypatch):+ _write(claude_home / "projects" / "-Users-me-app" / "s1.jsonl", _open_call_session())+ reads = []+ real = _count_importer_reads(monkeypatch, reads)+ summary = run_import(claude.SOURCE)+ assert (summary.new_chats, summary.messages) == (1, 2)+ assert reads == []