Skip to content

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.

72.1 KB
Raw Blame
# 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 shutil
import sqlite3
import threading
import uuid
from pathlib import Path

import pytest

from storage import studio_db
from utils.paths import studio_db_path


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", set())


@pytest.fixture
def workspace_projects_home(tmp_path):
    """Avoid the delete denylist: macOS tmp_path resolves under /private/tmp, which the guard refuses."""
    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,
        "title": "Test Chat",
        "modelType": "base",
        "modelId": "test-model",
        "pairId": None,
        "archived": False,
        "createdAt": 1_700_000_000_000,
    }


def _message(
    message_id: str,
    created_at: int,
    content: str,
    thread_id: str = "thread-1",
) -> dict:
    return _stored_message(
        id = message_id,
        threadId = thread_id,
        text = content,
        createdAt = created_at,
    )


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 _stored_message(
    *,
    id,
    threadId = "src",
    parentId = None,
    role = "user",
    type = "text",
    text = "Hello",
    createdAt = 9,
):
    """One stored chat message row, with per-test overrides."""
    return {
        "id": id,
        "threadId": threadId,
        "parentId": parentId,
        "role": role,
        "content": [{"type": type, "text": text}],
        "createdAt": createdAt,
    }


def test_sync_chat_messages_upserts_without_pruning(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread())
    studio_db.sync_chat_messages(
        "thread-1",
        [
            _message("msg-1", 1, "keep me"),
            _message("msg-2", 2, "old text"),
        ],
        prune_missing = True,
    )

    messages = studio_db.sync_chat_messages(
        "thread-1",
        [_message("msg-2", 2, "updated text")],
    )

    by_id = {message["id"]: message for message in messages}
    assert set(by_id) == {"msg-1", "msg-2"}
    assert by_id["msg-2"]["content"] == [{"type": "text", "text": "updated text"}]


def test_chat_thread_updated_at_bumps_on_message_writes(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    thread = studio_db.upsert_chat_thread(_thread())
    assert thread["updatedAt"] == thread["createdAt"]

    studio_db.upsert_chat_message(_message("msg-1", 1_700_000_000_500, "hi"))
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_000_500

    studio_db.upsert_chat_message(_message("msg-0", 1_600_000_000_000, "old"))
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_000_500

    studio_db.sync_chat_messages(
        "thread-1",
        [_message("msg-2", 1_700_000_001_000, "newer")],
    )
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_001_000


def test_chat_export_reads_one_snapshot_during_concurrent_delete(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    project = studio_db.upsert_chat_project(_project())
    thread = {**_thread(), "projectId": project["id"]}
    studio_db.upsert_chat_thread(thread)
    studio_db.upsert_chat_message(_message("msg-1", 1, "hello"))

    original_get_connection = studio_db.get_connection
    reader = original_get_connection()
    deleted = False

    class InterleavingConnection:
        def execute(
            self,
            sql,
            parameters = (),
        ):
            nonlocal deleted
            cursor = reader.execute(sql, parameters)
            if not deleted and "SELECT * FROM chat_threads" in sql:
                deleted = True
                writer = original_get_connection()
                try:
                    writer.execute("DELETE FROM chat_threads WHERE id = ?", (thread["id"],))
                    writer.execute("DELETE FROM chat_projects WHERE id = ?", (project["id"],))
                    writer.commit()
                finally:
                    writer.close()
            return cursor

        def __getattr__(self, name):
            return getattr(reader, name)

    monkeypatch.setattr(studio_db, "get_connection", lambda: InterleavingConnection())
    projects, threads, messages = studio_db.build_chat_history_export()

    assert deleted
    assert [item["id"] for item in projects] == [project["id"]]
    assert [item["id"] for item in threads] == [thread["id"]]
    assert [item["id"] for item in messages] == ["msg-1"]


def test_chat_thread_updated_at_recomputed_when_pruning(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    thread = studio_db.upsert_chat_thread(_thread())
    studio_db.sync_chat_messages(
        "thread-1",
        [
            _message("msg-1", 1_700_000_000_500, "older"),
            _message("msg-2", 1_700_000_001_000, "newest"),
        ],
        prune_missing = True,
    )
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_001_000

    studio_db.sync_chat_messages(
        "thread-1",
        [_message("msg-1", 1_700_000_000_500, "older")],
        prune_missing = True,
    )
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_000_500

    studio_db.sync_chat_messages("thread-1", [], prune_missing = True)
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == thread["createdAt"]


def test_chat_thread_updated_at_survives_thread_resave(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread())
    studio_db.upsert_chat_message(_message("msg-1", 1_700_000_000_500, "hi"))

    studio_db.upsert_chat_thread(_thread())
    assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_000_500


def test_chat_thread_preserves_gguf_variant(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    thread = {**_thread(), "modelGgufVariant": "Q6_K"}

    assert studio_db.upsert_chat_thread(thread)["modelGgufVariant"] == "Q6_K"
    studio_db.upsert_chat_thread(_thread())
    assert studio_db.get_chat_thread("thread-1")["modelGgufVariant"] == "Q6_K"

    updated = studio_db.update_chat_thread("thread-1", {"modelGgufVariant": "Q8_0"})
    assert updated is not None
    assert updated["modelGgufVariant"] == "Q8_0"

    replacement = {**_thread(), "modelId": "other-model"}
    assert studio_db.upsert_chat_thread(replacement)["modelGgufVariant"] is None


def test_list_chat_threads_orders_by_last_activity(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    older = _thread("thread-old")
    older["createdAt"] = 1_700_000_000_000
    newer = _thread("thread-new")
    newer["createdAt"] = 1_700_000_100_000
    studio_db.upsert_chat_thread(older)
    studio_db.upsert_chat_thread(newer)
    assert [t["id"] for t in studio_db.list_chat_threads()] == ["thread-new", "thread-old"]

    studio_db.upsert_chat_message(
        _message("msg-1", 1_700_000_200_000, "hi", thread_id = "thread-old")
    )
    assert [t["id"] for t in studio_db.list_chat_threads()] == ["thread-old", "thread-new"]


def test_chat_threads_updated_at_migration_backfills_from_messages(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    db_path = studio_db_path()
    db_path.parent.mkdir(parents = True, exist_ok = True)
    conn = sqlite3.connect(str(db_path))
    try:
        conn.execute(
            """
            CREATE TABLE chat_threads (
                id TEXT NOT NULL PRIMARY KEY,
                title TEXT NOT NULL,
                model_type TEXT NOT NULL,
                model_id TEXT,
                pair_id TEXT,
                archived INTEGER NOT NULL DEFAULT 0,
                created_at INTEGER NOT NULL
            )
            """
        )
        conn.execute(
            """
            CREATE TABLE chat_messages (
                id TEXT NOT NULL PRIMARY KEY,
                thread_id TEXT NOT NULL,
                parent_id TEXT,
                role TEXT NOT NULL,
                content_json TEXT NOT NULL,
                attachments_json TEXT,
                metadata_json TEXT,
                created_at INTEGER NOT NULL
            )
            """
        )
        conn.execute(
            "INSERT INTO chat_threads (id, title, model_type, created_at) VALUES (?, ?, ?, ?)",
            ("thread-with-msgs", "Old", "base", 1_700_000_000_000),
        )
        conn.execute(
            "INSERT INTO chat_threads (id, title, model_type, created_at) VALUES (?, ?, ?, ?)",
            ("thread-empty", "Empty", "base", 1_700_000_050_000),
        )
        conn.execute(
            "INSERT INTO chat_threads (id, title, model_type, created_at) VALUES (?, ?, ?, ?)",
            ("thread-fork", "Fork", "base", 1_700_000_100_000),
        )
        conn.executemany(
            "INSERT INTO chat_messages (id, thread_id, role, content_json, created_at) VALUES (?, ?, ?, ?, ?)",
            [
                ("m1", "thread-with-msgs", "user", "[]", 1_700_000_001_000),
                ("m2", "thread-with-msgs", "assistant", "[]", 1_700_000_002_000),
                ("m3", "thread-fork", "user", "[]", 1_700_000_001_000),
            ],
        )
        conn.commit()
    finally:
        conn.close()

    assert studio_db.get_chat_thread("thread-with-msgs")["updatedAt"] == 1_700_000_002_000
    assert studio_db.get_chat_thread("thread-empty")["updatedAt"] == 1_700_000_050_000
    assert studio_db.get_chat_thread("thread-fork")["updatedAt"] == 1_700_000_100_000
    assert studio_db.get_chat_thread("thread-with-msgs")["modelGgufVariant"] is None


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()
    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.upsert_chat_thread({**_thread(), "projectId": "project-1"})


def test_thread_delete_blocks_a_late_create_with_the_same_id(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)

    studio_db.delete_chat_threads(["late-thread"])

    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.upsert_chat_thread(_thread("late-thread"))
    assert studio_db.get_chat_thread("late-thread") is None


def test_clear_blocks_a_stale_recreate_of_a_deleted_thread(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))

    studio_db.clear_chat_history_with_active_research_runs(["pending-thread"])

    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.upsert_chat_thread(_thread("thread-1"))
    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.upsert_chat_thread(_thread("pending-thread"))
    assert studio_db.get_chat_thread("thread-1") is None
    assert studio_db.get_chat_thread("pending-thread") is None


def test_clear_reports_only_threads_that_had_a_row(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))

    _, deleted_ids = studio_db.clear_chat_history_with_active_research_runs(["never-committed"])

    assert deleted_ids == ["thread-1"]
    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.upsert_chat_thread(_thread("never-committed"))


def test_repeated_clear_operation_does_not_delete_later_threads(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("before-clear"))

    _, first_deleted_ids = studio_db.clear_chat_history_with_active_research_runs(
        operation_id = "clear-operation-1"
    )
    studio_db.upsert_chat_thread(_thread("after-clear"))

    _, repeated_deleted_ids = studio_db.clear_chat_history_with_active_research_runs(
        operation_id = "clear-operation-1"
    )

    assert first_deleted_ids == ["before-clear"]
    assert repeated_deleted_ids == first_deleted_ids
    assert studio_db.get_chat_thread("before-clear") is None
    assert studio_db.get_chat_thread("after-clear") is not None


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())
    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())
    studio_db.sync_chat_messages(
        "thread-1",
        [
            _message("msg-1", 1, "delete me"),
            _message("msg-2", 2, "keep me"),
        ],
    )

    messages = studio_db.sync_chat_messages(
        "thread-1",
        [_message("msg-2", 2, "keep me")],
        prune_missing = True,
    )

    assert [message["id"] for message in messages] == ["msg-2"]


def _turn(message_id: str, parent_id: str | None, created_at: int) -> dict:
    return _stored_message(
        id = message_id,
        threadId = "thread-1",
        parentId = parent_id,
        role = "assistant" if message_id.startswith("a") else "user",
        createdAt = created_at,
    )


def test_a_stale_window_delete_keeps_turns_it_never_saw(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread())
    seen = [_turn("u1", None, 1), _turn("a1", "u1", 2), _turn("u2", "a1", 3), _turn("a2", "u2", 4)]
    studio_db.sync_chat_messages("thread-1", seen)
    studio_db.sync_chat_messages("thread-1", seen + [_turn("u3", "a2", 5), _turn("a3", "u3", 6)])

    messages = studio_db.sync_chat_messages(
        "thread-1",
        seen[:2],
        prune_missing = True,
        deleted_message_ids = ["u2", "a2"],
    )

    parents = {message["id"]: message["parentId"] for message in messages}
    assert parents == {"u1": None, "a1": "u1", "u3": "a1", "a3": "u3"}


@pytest.mark.parametrize(
    "other_window, seen_count, deleted",
    [
        ([_turn("a2b", "u2", 5)], 4, ["u2", "a2"]),
        ([], 3, ["u2"]),
    ],
)
def test_a_stale_window_delete_drops_replies_it_never_saw(
    tmp_path, monkeypatch, other_window, seen_count, deleted
):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread())
    turns = [_turn("u1", None, 1), _turn("a1", "u1", 2), _turn("u2", "a1", 3), _turn("a2", "u2", 4)]
    studio_db.sync_chat_messages("thread-1", turns + other_window)

    messages = studio_db.sync_chat_messages(
        "thread-1",
        [m for m in turns[:seen_count] if m["id"] not in deleted],
        prune_missing = True,
        deleted_message_ids = deleted,
    )

    parents = {message["id"]: message["parentId"] for message in messages}
    assert parents == {"u1": None, "a1": "u1"}


def test_a_prune_does_not_walk_the_chain_of_rows_it_deletes(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread())
    ids = [f"u{i}" if i % 2 == 0 else f"a{i}" for i in range(40)]
    turns = [_turn(m, ids[i - 1] if i else None, i) for i, m in enumerate(ids)]
    studio_db.sync_chat_messages("thread-1", turns)
    walked = []
    real = studio_db._surviving_parent_id
    monkeypatch.setattr(
        studio_db,
        "_surviving_parent_id",
        lambda conn, thread_id, message_id, pruned: walked.append(message_id)
        or real(conn, thread_id, message_id, pruned),
    )

    assert studio_db.sync_chat_messages("thread-1", [], prune_missing = True) == []
    assert walked == []


def test_upsert_chat_message_rejects_cross_thread_id_conflict(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))
    studio_db.upsert_chat_thread(_thread("thread-2"))
    studio_db.upsert_chat_message(_message("msg-1", 1, "original", "thread-1"))

    with pytest.raises(studio_db.ChatMessageConflictError):
        studio_db.upsert_chat_message(_message("msg-1", 2, "moved", "thread-2"))

    assert [m["id"] for m in studio_db.list_chat_messages("thread-1")] == ["msg-1"]
    assert studio_db.list_chat_messages("thread-2") == []


def test_sync_chat_messages_detects_conflict_before_prune(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))
    studio_db.upsert_chat_thread(_thread("thread-2"))
    studio_db.sync_chat_messages(
        "thread-1",
        [_message("keep-me", 1, "keep", "thread-1")],
    )
    studio_db.upsert_chat_message(_message("conflict", 2, "other", "thread-2"))

    with pytest.raises(studio_db.ChatMessageConflictError):
        studio_db.sync_chat_messages(
            "thread-1",
            [_message("conflict", 3, "bad", "thread-1")],
            prune_missing = True,
        )

    assert [m["id"] for m in studio_db.list_chat_messages("thread-1")] == ["keep-me"]
    assert [m["id"] for m in studio_db.list_chat_messages("thread-2")] == ["conflict"]


def test_settings_merge_atomic_under_concurrency(tmp_path, monkeypatch):
    """Two threads writing distinct keys must not drop each other's update."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge({"inferenceParams": {}})

    barrier = threading.Barrier(2)

    def writer(key: str, value: float) -> None:
        barrier.wait()
        studio_db.upsert_chat_settings_merge({"inferenceParams": {key: value}})

    t1 = threading.Thread(target = writer, args = ("temperature", 0.7))
    t2 = threading.Thread(target = writer, args = ("topP", 0.9))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    merged = studio_db.list_chat_settings()["inferenceParams"]
    assert merged.get("temperature") == 0.7
    assert merged.get("topP") == 0.9


def test_settings_merge_preserves_nested_keys(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.5, "topP": 0.8}})
    studio_db.upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.9}})

    params = studio_db.list_chat_settings()["inferenceParams"]
    assert params == {"temperature": 0.9, "topP": 0.8}


def test_settings_compare_and_set_rejects_a_newer_nested_edit(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    original = {"inferenceParams": {"temperature": 0.6, "presencePenalty": 0.0}}
    studio_db.upsert_chat_settings_merge(original)
    studio_db.upsert_chat_settings_merge({"inferenceParams": {"presencePenalty": 0.4}})

    settings, applied = studio_db.upsert_chat_settings_merge_if_current(
        original,
        {"inferenceParams": {"presencePenalty": 1.5}},
    )

    assert applied is False
    assert settings["inferenceParams"]["presencePenalty"] == 0.4
    assert studio_db.list_chat_settings() == settings


def test_settings_compare_and_set_atomically_applies_a_matching_patch(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    original = {"inferenceParams": {"temperature": 0.6, "presencePenalty": 0.0}}
    studio_db.upsert_chat_settings_merge(original)

    settings, applied = studio_db.upsert_chat_settings_merge_if_current(
        original,
        {"inferenceParams": {"presencePenalty": 1.5}},
    )

    assert applied is True
    assert settings["inferenceParams"] == {"temperature": 0.6, "presencePenalty": 1.5}


def test_settings_compare_and_set_fences_an_expected_absent_field(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    original = {"inferenceParams": {"presencePenalty": 0.0}}
    studio_db.upsert_chat_settings_merge(original)
    studio_db.upsert_chat_settings_merge({"reasoningEnabled": False})

    settings, applied = studio_db.upsert_chat_settings_merge_if_current(
        original,
        {"inferenceParams": {"presencePenalty": 1.5}},
        ["reasoningEnabled"],
    )

    assert applied is False
    assert settings["reasoningEnabled"] is False
    assert settings["inferenceParams"]["presencePenalty"] == 0.0


def test_settings_compare_and_set_fences_an_expected_absent_nested_path(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    original = {"inferenceParams": {"presencePenalty": 0.0}}
    studio_db.upsert_chat_settings_merge(original)
    studio_db.upsert_chat_settings_merge({"inferenceParams": {"topK": 40}})

    settings, applied = studio_db.upsert_chat_settings_merge_if_current(
        original,
        {"inferenceParams": {"presencePenalty": 1.5}},
        expected_absent_paths = [["inferenceParams", "topK"]],
    )

    assert applied is False
    assert settings["inferenceParams"]["topK"] == 40
    assert settings["inferenceParams"]["presencePenalty"] == 0.0


def test_settings_compare_and_set_leaves_timestamps_alone_for_an_empty_patch(tmp_path, monkeypatch):
    """An empty patch is not a settings change: without a short-circuit, the merge would rewrite
    updated_at on every key, reading as a fresh edit."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge(
        {"inferenceParams": {"temperature": 0.6}, "autoTitle": True}
    )
    conn = studio_db.get_connection()
    before = {
        row["key"]: row["updated_at"]
        for row in conn.execute("SELECT key, updated_at FROM chat_settings")
    }
    conn.close()

    settings, applied = studio_db.upsert_chat_settings_merge_if_current({}, {})

    conn = studio_db.get_connection()
    after = {
        row["key"]: row["updated_at"]
        for row in conn.execute("SELECT key, updated_at FROM chat_settings")
    }
    conn.close()
    assert applied is True
    assert after == before
    assert settings["inferenceParams"] == {"temperature": 0.6}


def test_settings_compare_and_set_fences_a_model_row_added_after_the_read(tmp_path, monkeypatch):
    """Normalizing a cased model key writes a new exact-key row, and the subset compare only sees
    the read spelling, so it needs an absence fence or a newer row is overwritten."""
    _reset_studio_db(tmp_path, monkeypatch)
    lower = "unsloth/qwen3.8-27b-gguf"
    exact = "unsloth/Qwen3.8-27B-GGUF"
    legacy = {"temperature": 0.6, "minP": 0.01, "presencePenalty": 0.0}
    studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {lower: legacy}})
    newer = {"temperature": 0.31, "presencePenalty": 0.4}
    studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {exact: newer}})

    settings, applied = studio_db.upsert_chat_settings_merge_if_current(
        {"inferenceParamsByModel": {lower: legacy}},
        {"inferenceParamsByModel": {exact: {**legacy, "minP": 0.0, "presencePenalty": 1.5}}},
        expected_absent_paths = [["inferenceParamsByModel", exact]],
    )

    assert applied is False
    assert settings["inferenceParamsByModel"][exact] == newer


def test_settings_merge_keeps_each_model_s_remembered_params(tmp_path, monkeypatch):
    """Per-model memory patches one model at a time, so the merge must keep the others; otherwise
    tuning a second model would wipe the first one's remembered settings."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge(
        {"inferenceParamsByModel": {"qwen": {"temperature": 0.2, "topP": 0.8}}}
    )
    studio_db.upsert_chat_settings_merge(
        {"inferenceParamsByModel": {"llama": {"temperature": 0.9}}}
    )
    studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {"qwen": {"temperature": 0.4}}})

    by_model = studio_db.list_chat_settings()["inferenceParamsByModel"]
    assert by_model == {"qwen": {"temperature": 0.4, "topP": 0.8}, "llama": {"temperature": 0.9}}


def test_picking_a_preset_can_forget_one_model_s_params(tmp_path, monkeypatch):
    """A preset pick drops the loaded model's preset-owned keys (issue 14068) because a merge cannot
    remove a key; the forget runs first, so a key it does not name survives."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge(
        {
            "inferenceParamsByModel": {
                "qwen": {"temperature": 0.3, "systemPrompt": "Pirate", "fastMode": True},
                "llama": {"temperature": 0.9},
            }
        }
    )
    studio_db.upsert_chat_settings_merge(
        {
            "forgetInferenceParamsByModel": {"qwen": ["temperature", "systemPrompt", "topP"]},
            "inferenceParamsByModel": {"qwen": {"topP": 0.5}},
        }
    )
    settings = studio_db.list_chat_settings()
    assert settings["inferenceParamsByModel"] == {
        "qwen": {"fastMode": True, "topP": 0.5},
        "llama": {"temperature": 0.9},
    }
    assert "forgetInferenceParamsByModel" not in settings

    _, applied = studio_db.upsert_chat_settings_merge_if_current(
        {}, {"forgetInferenceParamsByModel": {"qwen": ["fastMode", "topP"], "missing": ["x"]}}
    )
    assert applied is True
    settings = studio_db.list_chat_settings()
    assert settings["inferenceParamsByModel"] == {"llama": {"temperature": 0.9}}
    assert "forgetInferenceParamsByModel" not in settings


def test_settings_merge_quarantines_corrupt_json_and_rejects_partial_patch(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.5, "topP": 0.8}})
    conn = studio_db.get_connection()
    try:
        conn.execute(
            "UPDATE chat_settings SET value_json = ? WHERE key = ?",
            ('{"temperature": 0.5', "inferenceParams"),
        )
        conn.commit()
    finally:
        conn.close()

    with pytest.raises(studio_db.CorruptSettingsError):
        studio_db.upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.9}})

    conn = studio_db.get_connection()
    try:
        quarantined = conn.execute(
            "SELECT key, value_json, reason FROM chat_settings_quarantine"
        ).fetchall()
        remaining = conn.execute(
            "SELECT key FROM chat_settings WHERE key = ?",
            ("inferenceParams",),
        ).fetchall()
    finally:
        conn.close()
    assert [row["key"] for row in quarantined] == ["inferenceParams"]
    assert quarantined[0]["reason"] == "json_decode_error"
    assert remaining == []


def test_settings_merge_replaces_corrupt_scalar_after_quarantine(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_settings_merge({"autoTitle": False})
    conn = studio_db.get_connection()
    try:
        conn.execute(
            "UPDATE chat_settings SET value_json = ? WHERE key = ?",
            ("not-json", "autoTitle"),
        )
        conn.commit()
    finally:
        conn.close()

    settings = studio_db.upsert_chat_settings_merge({"autoTitle": True})

    assert settings["autoTitle"] is True
    conn = studio_db.get_connection()
    try:
        quarantined = conn.execute("SELECT key, reason FROM chat_settings_quarantine").fetchall()
    finally:
        conn.close()
    assert [(row["key"], row["reason"]) for row in quarantined] == [
        ("autoTitle", "json_decode_error")
    ]


def test_list_chat_messages_for_threads_chunks_over_900_ids(tmp_path, monkeypatch):
    """SQLite host-parameter limit is 999 on older builds; chunk at 900."""
    _reset_studio_db(tmp_path, monkeypatch)
    n = 901
    for i in range(n):
        studio_db.upsert_chat_thread(
            {
                "id": f"t-{i}",
                "title": "T",
                "modelType": "base",
                "modelId": "m",
                "pairId": None,
                "archived": False,
                "createdAt": 1_700_000_000_000 + i,
            }
        )
        studio_db.upsert_chat_message(
            {
                "id": f"m-{i}",
                "threadId": f"t-{i}",
                "parentId": None,
                "role": "user",
                "content": [{"type": "text", "text": "hi"}],
                "createdAt": 1_700_000_000_000 + i,
            }
        )
    out = studio_db.list_chat_messages_for_threads([f"t-{i}" for i in range(n)])
    assert len(out) == n
    assert {m["threadId"] for m in out} == {f"t-{i}" for i in range(n)}


def test_chat_thread_modified_at_stamps_only_real_edits(tmp_path, monkeypatch):
    """Rename, move and archive stamp modified_at; a no-op patch or other field does not."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("t"))
    assert studio_db.get_chat_thread("t")["modifiedAt"] is None

    studio_db.update_chat_thread("t", {"title": "Test Chat"})
    studio_db.update_chat_thread("t", {"archived": False, "modelId": "other"})
    assert studio_db.get_chat_thread("t")["modifiedAt"] is None

    renamed = studio_db.update_chat_thread("t", {"title": "Renamed"})
    assert renamed["modifiedAt"] is not None

    with sqlite3.connect(studio_db_path()) as conn:
        conn.execute("UPDATE chat_threads SET modified_at = 1 WHERE id = 't'")
    archived = studio_db.update_chat_thread("t", {"archived": True})
    assert archived["modifiedAt"] > 1


def test_count_chat_messages_for_threads_follows_the_newest_branch(tmp_path, monkeypatch):
    """Counts user/assistant rows; a branched thread counts only its newest path."""
    _reset_studio_db(tmp_path, monkeypatch)
    for tid in ("flat", "branched", "empty"):
        studio_db.upsert_chat_thread(_thread(tid))

    def msg(tid, mid, parent, role, at):
        studio_db.upsert_chat_message(
            {
                "id": mid,
                "threadId": tid,
                "parentId": parent,
                "role": role,
                "content": [{"type": "text", "text": "x"}],
                "createdAt": at,
            }
        )

    msg("flat", "f1", None, "user", 1)
    msg("flat", "f2", None, "assistant", 2)
    msg("flat", "f3", None, "system", 3)
    msg("branched", "b1", None, "user", 10)
    msg("branched", "b2", "b1", "assistant", 11)
    msg("branched", "b3", "b1", "assistant", 12)
    msg("branched", "b4", "b3", "user", 13)

    counts = studio_db.count_chat_messages_for_threads(["flat", "branched", "empty", "missing"])
    assert counts == {"flat": 2, "branched": 3, "empty": 0, "missing": 0}
    assert studio_db.count_chat_messages_for_threads([]) == {}


def test_legacy_imports_empty_by_default(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    assert studio_db.list_chat_legacy_imports() == []


def test_legacy_imports_records_and_lists(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    accepted, inserted = studio_db.upsert_chat_legacy_imports(
        ["legacy-a", "legacy-b", "legacy-c"],
    )
    assert accepted == 3
    assert inserted == 3
    assert set(studio_db.list_chat_legacy_imports()) == {"legacy-a", "legacy-b", "legacy-c"}


def test_legacy_imports_is_idempotent(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    accepted1, inserted1 = studio_db.upsert_chat_legacy_imports(
        ["legacy-a", "legacy-b"],
    )
    accepted2, inserted2 = studio_db.upsert_chat_legacy_imports(
        ["legacy-b", "legacy-c"],
    )
    assert (accepted1, inserted1) == (2, 2)
    assert (accepted2, inserted2) == (2, 1)
    assert set(studio_db.list_chat_legacy_imports()) == {"legacy-a", "legacy-b", "legacy-c"}


def test_legacy_imports_dedups_input(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    accepted, inserted = studio_db.upsert_chat_legacy_imports(
        ["x", "x", "y", "x"],
    )
    assert accepted == 2
    assert inserted == 2
    assert set(studio_db.list_chat_legacy_imports()) == {"x", "y"}


def test_legacy_imports_ignores_empty(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    assert studio_db.upsert_chat_legacy_imports([]) == (0, 0)
    assert studio_db.upsert_chat_legacy_imports(["", None]) == (0, 0)  # type: ignore[list-item]
    assert studio_db.list_chat_legacy_imports() == []


def _msg(mid: str, parent: str | None, t: int) -> dict:
    return _stored_message(id = mid, parentId = parent, text = mid, createdAt = t)


def test_fork_chat_thread_copies_ancestry_with_fresh_ids(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(
        {
            **_thread("src"),
            "title": "Original",
            "modelGgufVariant": "Q6_K",
            "openaiCodeExecContainerId": "cnt-x",
        }
    )
    studio_db.sync_chat_messages(
        "src",
        [
            _msg("m1", None, 1),
            _msg("m2", "m1", 2),
            _msg("m3", "m2", 3),
            _msg("m4", "m2", 4),
        ],
    )

    counter = {"i": 0}

    def id_factory():
        counter["i"] += 1
        return f"new-{counter['i']}"

    forked = studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "m3",
        new_thread_id = "fork-1",
        created_at = 99,
        id_factory = id_factory,
    )
    assert forked is not None
    assert forked["id"] == "fork-1"
    assert forked["forkedFromThreadId"] == "src"
    assert forked["forkedFromMessageId"] == "m3"
    assert forked["modelGgufVariant"] == "Q6_K"
    assert forked["openaiCodeExecContainerId"] is None

    copied = studio_db.list_chat_messages("fork-1")
    assert len(copied) == 3
    assert copied[0]["parentId"] is None
    assert copied[1]["parentId"] == copied[0]["id"]
    assert copied[2]["parentId"] == copied[1]["id"]
    assert {m["id"] for m in copied}.isdisjoint({"m1", "m2", "m3"})


@pytest.mark.parametrize("linked_tip", [False, True])
@pytest.mark.parametrize("branch_message_id", [None, "m2"])
def test_fork_preserves_legacy_ancestry(tmp_path, monkeypatch, linked_tip, branch_message_id):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    studio_db.sync_chat_messages(
        "src",
        [_msg("m1", None, 1), _msg("m2", None, 2), _msg("m3", "m2" if linked_tip else None, 3)],
    )
    studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = branch_message_id,
        new_thread_id = "fork-1",
        created_at = 4,
        id_factory = iter(("copy-1", "copy-2", "copy-3")).__next__,
    )
    copied = studio_db.list_chat_messages("fork-1")
    expected = ["m1", "m2", "m3"] if branch_message_id is None else ["m1", "m2"]
    assert [row["content"][0]["text"] for row in copied] == expected
    assert [row["parentId"] for row in copied] == [None, *[row["id"] for row in copied[:-1]]]


def test_fork_chat_thread_preserves_project_id(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_project(_project("project-1"))
    studio_db.upsert_chat_thread({**_thread("src"), "projectId": "project-1"})
    studio_db.upsert_chat_message(_msg("m1", None, 1))

    forked = studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "m1",
        new_thread_id = "fork-1",
        created_at = 99,
        id_factory = lambda: "new-1",
    )

    assert forked is not None
    assert forked["projectId"] == "project-1"
    assert {thread["id"] for thread in studio_db.list_chat_threads(project_id = "project-1")} == {
        "fork-1",
        "src",
    }


def test_fork_chat_thread_detaches_research_run_metadata(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    studio_db.upsert_chat_message(_msg("user", None, 1))
    studio_db.upsert_chat_message(
        {
            "id": "research-report",
            "threadId": "src",
            "parentId": "user",
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "# Copied report",
                    "researchRunId": "run-source",
                },
                {
                    "type": "source",
                    "url": "https://example.com",
                    "title": "Example",
                    "researchStatus": "completed",
                },
            ],
            "metadata": {
                "researchRunId": "run-source",
                "researchStatus": "completed",
                "researchPlanRevision": 1,
                "serverManaged": True,
                "model": "local-model",
            },
            "createdAt": 2,
        }
    )

    studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "research-report",
        new_thread_id = "fork-1",
        created_at = 3,
        id_factory = iter(("fork-user", "fork-report")).__next__,
    )

    report = next(
        message
        for message in studio_db.list_chat_messages("fork-1")
        if message["role"] == "assistant"
    )
    assert report["content"][0]["text"] == "# Copied report"
    assert report["content"][1]["url"] == "https://example.com"
    assert all(
        not ({"researchRunId", "researchStatus", "serverManaged"} & set(part))
        for part in report["content"]
    )
    assert report["metadata"] == {"model": "local-model"}


def test_fork_detachment_detects_non_id_research_content_keys():
    content_json, metadata_json = studio_db._detach_research_message_json(
        '[{"type":"text","text":"Report","serverManaged":true}]',
        '{"model":"local-model","generationRunId":"run-1","generationSeq":3}',
    )

    assert "serverManaged" not in content_json
    assert "generationRunId" not in metadata_json
    assert metadata_json == '{"model": "local-model"}'


def test_fork_chat_thread_returns_none_for_missing_source(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    result = studio_db.fork_chat_thread(
        source_thread_id = "nope",
        branch_message_id = "m1",
        new_thread_id = "fork",
        created_at = 1,
        id_factory = lambda: "x",
    )
    assert result is None


def test_fork_chat_thread_rejects_a_deleted_target_id(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    studio_db.upsert_chat_message(_msg("m1", None, 1))
    studio_db.delete_chat_threads(["fork"])

    with pytest.raises(studio_db.ChatThreadDeletedError):
        studio_db.fork_chat_thread(
            source_thread_id = "src",
            branch_message_id = "m1",
            new_thread_id = "fork",
            created_at = 2,
            id_factory = lambda: "new-1",
        )
    assert studio_db.get_chat_thread("fork") is None


def test_count_forks_for_message(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    assert studio_db.count_forks_for_message("src", "m1") == 0

    counter = {"i": 0}

    def id_factory():
        counter["i"] += 1
        return f"id-{counter['i']}"

    studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "m1",
        new_thread_id = "f1",
        created_at = 2,
        id_factory = id_factory,
    )
    studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "m1",
        new_thread_id = "f2",
        created_at = 3,
        id_factory = id_factory,
    )
    assert studio_db.count_forks_for_message("src", "m1") == 2


def test_fork_counts_for_thread(tmp_path, monkeypatch):
    """One read for the whole thread, so a rendered thread costs one request, not one per message."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    studio_db.sync_chat_messages(
        "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]
    )
    assert studio_db.fork_counts_for_thread("src") == {}

    counter = {"i": 0}

    def id_factory():
        counter["i"] += 1
        return f"id-{counter['i']}"

    for index, (branch, new_id) in enumerate([("m1", "f1"), ("m1", "f2"), ("m2", "f3")]):
        studio_db.fork_chat_thread(
            source_thread_id = "src",
            branch_message_id = branch,
            new_thread_id = new_id,
            created_at = 10 + index,
            id_factory = id_factory,
        )

    counts = studio_db.fork_counts_for_thread("src")
    assert counts == {"m1": 2, "m2": 1}
    for message_id in ["m1", "m2", "m3"]:
        assert counts.get(message_id, 0) == studio_db.count_forks_for_message("src", message_id)
    assert studio_db.fork_counts_for_thread("f1") == {}


def _research_thread(
    tmp_path,
    monkeypatch,
    *,
    extra_ancestors: int = 1,
):
    """Returns ancestor ids; the prompt and report pair is server-managed and claimed by a research run."""
    from storage import research_runs_db

    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))

    ancestors = [f"a{index}" for index in range(extra_ancestors)]
    chain = [*ancestors, "prompt", "report"]
    messages = []
    for position, message_id in enumerate(chain):
        messages.append(
            {
                "id": message_id,
                "threadId": "src",
                "parentId": chain[position - 1] if position else None,
                "role": "assistant" if message_id == "report" else "user",
                "content": [{"type": "text", "text": message_id}],
                "metadata": (
                    {"researchRunId": "run-1", "serverManaged": True}
                    if message_id == "report"
                    else None
                ),
                "createdAt": position + 1,
            }
        )
    studio_db.sync_chat_messages("src", messages)
    research_runs_db.create_run(
        run_id = "run-1",
        owner_subject = "owner",
        thread_id = "src",
        user_message_id = "prompt",
        assistant_message_id = "report",
        config = {},
        created_at = 1,
    )
    return ancestors, studio_db.list_chat_messages("src")


def _without(messages: list[dict], *drop: str) -> list[dict]:
    return [dict(m) for m in messages if m["id"] not in drop]


@pytest.mark.parametrize("owner", ["generation", "research"])
@pytest.mark.parametrize("revision", [None, 4])
def test_reparented_managed_prompt_invalidates_saved_usage_after_reload(
    tmp_path, monkeypatch, owner, revision
):
    from storage import chat_generation_runs_db, research_runs_db

    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("src"))
    prompt = _stored_message(id = "prompt", parentId = "ancestor")
    prompt["metadata"] = {"kept": "server value"}
    if revision is not None:
        prompt["metadata"]["revision"] = revision
    studio_db.sync_chat_messages(
        "src",
        [
            _stored_message(id = "ancestor", role = "assistant", createdAt = 1),
            prompt,
            _stored_message(id = "sibling", createdAt = 10),
        ],
    )
    common = dict(
        run_id = "run-1",
        owner_subject = "owner",
        thread_id = "src",
        user_message_id = "prompt",
        assistant_message_id = "report",
    )
    if owner == "generation":
        chat_generation_runs_db.create_run(
            **common,
            request_payload = {"model": "local", "messages": [{"role": "user", "content": "Hello"}]},
        )
    else:
        research_runs_db.create_run(**common, config = {}, created_at = 11)
    before = {m["id"]: m for m in studio_db.list_chat_messages("src")}
    payload = _without(list(before.values()), "ancestor")
    edited = next(m for m in payload if m["id"] == "prompt")
    edited["parentId"] = None
    edited["metadata"] = {"revision": 999, "untrusted": True}
    edited["content"] = [{"type": "text", "text": "client drift"}]

    studio_db.sync_chat_messages("src", payload, prune_missing = True)
    reloaded = {m["id"]: m for m in studio_db.list_chat_messages("src")}

    assert reloaded["prompt"]["parentId"] is None
    assert reloaded["prompt"]["metadata"] == {
        **before["prompt"]["metadata"],
        "revision": (revision or 0) + 1,
    }
    assert reloaded["prompt"]["content"] == before["prompt"]["content"]
    assert reloaded["report"] == before["report"]
    assert reloaded["sibling"] == before["sibling"]
    studio_db.sync_chat_messages("src", payload, prune_missing = True)
    assert studio_db.list_chat_messages("src") == list(reloaded.values())


def test_deleting_an_ancestor_relinks_the_research_prompt(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    payload = _without(messages, "a0")
    payload[0]["parentId"] = None

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = True)

    assert [m["id"] for m in synced] == ["prompt", "report"]
    assert synced[0]["parentId"] is None


def test_deleting_a_mid_chain_ancestor_relinks_to_the_surviving_grandparent(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch, extra_ancestors = 3)
    payload = _without(messages, "a1", "a2")
    next(m for m in payload if m["id"] == "prompt")["parentId"] = "a0"

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = True)

    assert next(m for m in synced if m["id"] == "prompt")["parentId"] == "a0"


def test_a_stale_window_delete_relinks_a_research_prompt_it_never_saw(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch, extra_ancestors = 2)

    synced = studio_db.sync_chat_messages(
        "src",
        _without(messages, "a1", "prompt", "report"),
        prune_missing = True,
        deleted_message_ids = ["a1"],
    )

    assert {m["id"]: m["parentId"] for m in synced} == {
        "a0": None,
        "prompt": "a0",
        "report": "prompt",
    }


def test_a_relink_to_a_surviving_message_that_is_not_the_ancestor_is_ignored(tmp_path, monkeypatch):
    # The bulk sync drops the claim instead of rejecting the batch; reseat uses the stored chain.
    _, messages = _research_thread(tmp_path, monkeypatch, extra_ancestors = 3)
    payload = _without(messages, "a1", "a2")
    next(m for m in payload if m["id"] == "prompt")["parentId"] = "report"

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = True)

    assert next(m for m in synced if m["id"] == "prompt")["parentId"] == "a0"


def test_a_relink_with_nothing_pruned_leaves_the_stored_parent_alone(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    payload = [dict(m) for m in messages]
    next(m for m in payload if m["id"] == "prompt")["parentId"] = None

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = True)

    assert next(m for m in synced if m["id"] == "prompt")["parentId"] == "a0"


def test_a_relink_is_ignored_when_pruning_is_off(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    payload = _without(messages, "a0")
    payload[0]["parentId"] = None

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = False)

    assert {m["id"] for m in synced} >= {"a0", "prompt"}
    assert next(m for m in synced if m["id"] == "prompt")["parentId"] == "a0"


@pytest.mark.parametrize(
    "field, value",
    [
        ("content", [{"type": "text", "text": "edited"}]),
        ("role", "assistant"),
        ("metadata", {"tampered": True}),
        ("createdAt", 999),
    ],
)
def test_the_reseat_does_not_carry_any_other_edit(tmp_path, monkeypatch, field, value):
    _, messages = _research_thread(tmp_path, monkeypatch)
    stored = next(m for m in messages if m["id"] == "prompt")
    payload = _without(messages, "a0")
    payload[0]["parentId"] = None
    payload[0][field] = value

    synced = studio_db.sync_chat_messages("src", payload, prune_missing = True)

    prompt = next(m for m in synced if m["id"] == "prompt")
    assert prompt["parentId"] is None
    expected = stored.get(field)
    if field == "metadata":
        expected = {**(expected or {}), "revision": 1}
    assert prompt.get(field) == expected
    assert prompt.get(field) != value


def test_deleting_a_protected_message_itself_is_still_refused(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)

    for dropped in ("prompt", "report"):
        synced = studio_db.sync_chat_messages(
            "src", _without(messages, dropped), prune_missing = True
        )
        assert dropped in {m["id"] for m in synced}


def test_a_research_prompt_already_at_the_root_is_unaffected(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch, extra_ancestors = 0)

    synced = studio_db.sync_chat_messages("src", messages, prune_missing = True)

    assert [m["id"] for m in synced] == ["prompt", "report"]


def test_an_unrelated_sibling_can_still_be_deleted(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    sibling = _stored_message(id = "sibling", parentId = "a0", text = "sibling")
    studio_db.sync_chat_messages("src", [*messages, sibling])

    synced = studio_db.sync_chat_messages("src", messages, prune_missing = True)

    assert "sibling" not in {m["id"] for m in synced}


def test_a_plain_message_whose_parent_is_pruned_is_never_guarded(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    plain_parent = _stored_message(
        id = "plain-parent",
        parentId = "report",
        text = "plain-parent",
        createdAt = 8,
    )
    plain_child = _stored_message(
        id = "plain-child",
        parentId = "plain-parent",
        role = "assistant",
        text = "plain-child",
    )
    studio_db.sync_chat_messages("src", [*messages, plain_parent, plain_child])

    relinked = {**plain_child, "parentId": "report"}
    synced = studio_db.sync_chat_messages("src", [*messages, relinked], prune_missing = True)

    assert next(m for m in synced if m["id"] == "plain-child")["parentId"] == "report"


def test_a_corrupt_self_link_resolves_to_the_root_rather_than_itself(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    cyclic = [dict(m) for m in messages]
    next(m for m in cyclic if m["id"] == "a0")["parentId"] = "prompt"
    studio_db.sync_chat_messages("src", cyclic)

    conn = studio_db.get_connection()
    try:
        assert studio_db._surviving_parent_id(conn, "src", "prompt", {"a0"}) is None
    finally:
        conn.close()


def test_an_empty_stored_parent_reads_as_the_root(tmp_path, monkeypatch):
    _, messages = _research_thread(tmp_path, monkeypatch)
    conn = studio_db.get_connection()
    try:
        conn.execute("UPDATE chat_messages SET parent_id = '' WHERE id = 'a0'")
        conn.commit()
        assert studio_db._surviving_parent_id(conn, "src", "a0", set()) is None
    finally:
        conn.close()


def test_deleting_a_thread_signals_only_research_runs_a_worker_owns(tmp_path, monkeypatch):
    # A planning run has no worker; signalling it would leave an unconsumed cancellation event.
    _research_thread(tmp_path, monkeypatch)

    assert studio_db.delete_chat_threads_with_active_research_runs(["src"]) == []


def test_deleting_a_thread_signals_a_leased_research_run(tmp_path, monkeypatch):
    _research_thread(tmp_path, monkeypatch)
    conn = studio_db.get_connection()
    try:
        conn.execute(
            "UPDATE research_runs SET lease_owner = 'worker-1', status = 'running' WHERE id = ?",
            ("run-1",),
        )
        conn.commit()
    finally:
        conn.close()

    assert studio_db.delete_chat_threads_with_active_research_runs(["src"]) == ["run-1"]


def test_replaying_a_clear_does_not_signal_its_research_runs_again(tmp_path, monkeypatch):
    _research_thread(tmp_path, monkeypatch)
    conn = studio_db.get_connection()
    try:
        conn.execute(
            "UPDATE research_runs SET lease_owner = 'worker-1', status = 'running' WHERE id = ?",
            ("run-1",),
        )
        conn.commit()
    finally:
        conn.close()

    first = studio_db.clear_chat_history_with_active_research_runs(operation_id = "op-1")
    assert first == (["run-1"], ["src"])

    replay = studio_db.clear_chat_history_with_active_research_runs(operation_id = "op-1")
    assert replay == ([], ["src"])


def test_repeated_identical_user_sends_persist_separately(tmp_path, monkeypatch):
    """Repeated identical user sends (e.g. user sending 'Hello' multiple times) have distinct IDs and persist separately."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))

    msg1 = {
        "id": "u1",
        "threadId": "thread-1",
        "parentId": None,
        "role": "user",
        "content": [{"type": "text", "text": "Hello"}],
        "attachments": [{"name": "doc.pdf", "content": [{"type": "text", "text": "raw"}]}],
        "createdAt": 1000,
    }
    studio_db.upsert_chat_message(msg1)
    studio_db.upsert_chat_message(
        {
            "id": "a1",
            "threadId": "thread-1",
            "parentId": "u1",
            "role": "assistant",
            "content": [{"type": "text", "text": "Hi"}],
            "createdAt": 1500,
        }
    )

    msg2 = {
        "id": "u2",
        "threadId": "thread-1",
        "parentId": "a1",
        "role": "user",
        "content": [{"type": "text", "text": "Hello"}],
        "attachments": [{"name": "doc.pdf", "content": [{"type": "text", "text": "raw"}]}],
        "createdAt": 2000,
    }
    res = studio_db.upsert_chat_message(msg2)
    assert res["id"] == "u2"

    messages = studio_db.list_chat_messages("thread-1")
    assert {m["id"] for m in messages} == {"u1", "a1", "u2"}


def test_repeated_identical_sends_in_flat_thread_persist_separately(tmp_path, monkeypatch):
    """In a flat thread where parent_id is None, repeated identical sends with different IDs must not collapse."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("thread-1"))

    payload = [
        _stored_message(id = "u1", threadId = "thread-1", createdAt = 1000),
        _stored_message(id = "u2", threadId = "thread-1", createdAt = 2000),
    ]
    messages = studio_db.sync_chat_messages("thread-1", payload)
    assert len(messages) == 2
    assert [m["id"] for m in messages] == ["u1", "u2"]


@pytest.mark.parametrize(
    "stored,title,base",
    [
        ("Chat", "Chat (2)", "Chat"),
        ("Chat (2)", "Chat (2) (3)", "Chat (2)"),
        (None, "Chat", "Chat"),
        (None, "Budget (2026)", "Budget (2026)"),
        (None, "Release (2)", "Release (2)"),
        (None, "(2)", "(2)"),
        (None, "  Spaced  ", "Spaced"),
        ("", "Chat (2)", "Chat (2)"),
        ("  ", "Chat (2)", "Chat (2)"),
    ],
)
def test_fork_base_of(stored, title, base):
    """Without a stored base the whole title is one, so only a generated "(n)" is replaced."""
    assert studio_db.fork_base_of({"fork_title_base": stored, "title": title}) == base


def _fork(source: str, new_id: str, at: int):
    return studio_db.fork_chat_thread(
        source_thread_id = source,
        branch_message_id = None,
        new_thread_id = new_id,
        created_at = at,
        id_factory = lambda: uuid.uuid4().hex,
    )


def test_fork_of_an_ordinary_chat_keeps_a_numeric_suffix(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Budget (2026)"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])

    assert _fork("src", "f0", 10)["title"] == "Budget (2026) (1)"
    assert _fork("f0", "f1", 11)["title"] == "Budget (2026) (2)"


def test_a_renamed_fork_keeps_the_name_the_user_gave_it(tmp_path, monkeypatch):
    """forked_from_thread_id survives a rename, so it alone cannot say the "(n)" is ours."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.upsert_chat_thread(
        {**_thread("f"), "title": "Report (2026)", "forkedFromThreadId": "orig"}
    )
    studio_db.sync_chat_messages("f", [_msg("m1", None, 1)])

    assert _fork("f", "f2", 10)["title"] == "Report (2026) (1)"


def test_a_generated_suffix_is_still_replaced(tmp_path, monkeypatch):
    """A real fork carries the base it was built from, so its "(n)" is ours to take."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])

    assert _fork("orig", "f", 10)["title"] == "Notes (1)"
    assert _fork("f", "f2", 11)["title"] == "Notes (2)"


def test_a_fork_numbers_from_its_base_after_the_source_is_gone(tmp_path, monkeypatch):
    """The stored base is the whole signal, so nothing about the source can take it away."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])
    assert _fork("orig", "f", 10)["title"] == "Notes (1)"

    studio_db.delete_chat_threads(["orig"])

    assert _fork("f", "f2", 11)["title"] == "Notes (2)"


def test_a_fork_numbers_from_its_base_after_the_source_is_renamed(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])
    assert _fork("orig", "f", 10)["title"] == "Notes (1)"

    studio_db.update_chat_thread("orig", {"title": "Journal"})

    assert _fork("f", "f2", 11)["title"] == "Notes (2)"


def test_renaming_a_fork_ends_the_generated_name(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])
    _fork("orig", "f", 10)

    studio_db.update_chat_thread("f", {"title": "Report (2026)"})
    assert studio_db.get_chat_thread("f")["forkTitleBase"] is None

    assert _fork("f", "f2", 11)["title"] == "Report (2026) (1)"


def test_a_rename_through_upsert_also_ends_it(tmp_path, monkeypatch):
    """Whole-record writers rebuild the row without the base; only a new title drops it."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})
    studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])
    _fork("orig", "f", 10)

    studio_db.upsert_chat_thread({**_thread("f"), "title": "Notes (1)", "archived": True})
    assert studio_db.get_chat_thread("f")["forkTitleBase"] == "Notes"

    studio_db.upsert_chat_thread({**_thread("f"), "title": "Report (2026)"})
    assert studio_db.get_chat_thread("f")["forkTitleBase"] is None


def test_fork_titles_number_from_the_original_name(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Research notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1), _msg("m2", "m1", 2)])

    titles = [_fork("src", f"f{i}", 10 + i)["title"] for i in range(3)]
    assert titles == ["Research notes (1)", "Research notes (2)", "Research notes (3)"]

    assert _fork("f0", "deep", 20)["title"] == "Research notes (4)"


def test_fork_title_fills_the_lowest_free_number(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    for i in range(3):
        _fork("src", f"f{i}", 10 + i)
    studio_db.delete_chat_threads(["f1"])

    assert _fork("src", "f-new", 30)["title"] == "Notes (2)"


def test_fork_title_ignores_other_names_and_archived_state(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    studio_db.upsert_chat_thread({**_thread("other"), "title": "Notes extra (1)"})
    studio_db.upsert_chat_thread({**_thread("old"), "title": "Notes (1)", "archived": True})

    assert _fork("src", "f-new", 30)["title"] == "Notes (2)"


@pytest.mark.parametrize("title", ["New Chat", ""])
def test_a_fork_of_an_untitled_chat_stays_untitled(tmp_path, monkeypatch, title):
    """The frontend auto-titles only "New Chat", so "New Chat (1)" would never get a name."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": title})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])

    fork = _fork("src", "f", 10)
    assert fork["title"] == "New Chat"
    assert fork["forkTitleBase"] is None
    assert _fork("f", "f2", 11)["title"] == "New Chat"

    # Once auto-titled, its own forks number from the new name.
    studio_db.update_chat_thread("f", {"title": "Notes"})
    assert _fork("f", "f3", 12)["title"] == "Notes (1)"


def test_fork_records_the_last_inherited_message(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages(
        "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]
    )

    forked = studio_db.fork_chat_thread(
        source_thread_id = "src",
        branch_message_id = "m2",
        new_thread_id = "fork-1",
        created_at = 99,
        id_factory = lambda: uuid.uuid4().hex,
    )
    copied = studio_db.list_chat_messages("fork-1")
    boundary = forked["forkBoundaryMessageId"]
    assert boundary == copied[-1]["id"]
    assert boundary not in {"m1", "m2", "m3"}
    assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == boundary


def test_the_boundary_skips_a_trailing_message_that_paints_no_row(tmp_path, monkeypatch):
    """A trailing system message paints no row, so the divider must not anchor on it."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})
    studio_db.sync_chat_messages(
        "src",
        [
            _stored_message(id = "m1", parentId = None, createdAt = 1),
            _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),
            _stored_message(id = "m3", parentId = "m2", role = "system", createdAt = 3),
        ],
    )

    forked = _fork("src", "fork-1", 99)
    copied = {m["id"]: m for m in studio_db.list_chat_messages("fork-1")}

    assert [m["role"] for m in copied.values()] == ["user", "assistant", "system"]
    assert copied[forked["forkBoundaryMessageId"]]["role"] == "assistant"


def test_a_fork_with_nothing_visible_to_inherit_has_no_boundary(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Prompt only"})
    studio_db.sync_chat_messages(
        "src", [_stored_message(id = "m1", parentId = None, role = "system", createdAt = 1)]
    )

    assert _fork("src", "fork-1", 99)["forkBoundaryMessageId"] is None


def test_a_whole_record_save_without_the_boundary_keeps_it(tmp_path, monkeypatch):
    """The backend owns the anchor and moves it itself, so an absent one is not a clear."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    boundary = _fork("src", "fork-1", 99)["forkBoundaryMessageId"]
    assert boundary is not None

    stored = studio_db.get_chat_thread("fork-1")
    studio_db.upsert_chat_thread({k: v for k, v in stored.items() if k != "forkBoundaryMessageId"})

    assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == boundary


def test_a_stale_whole_record_save_cannot_move_the_boundary_back(tmp_path, monkeypatch):
    """A whole-record writer carries whatever it read, which may predate a prune that moved
    the anchor. Writing that back would park the divider on a deleted row for good."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages(
        "src",
        [
            _stored_message(id = "m1", parentId = None, createdAt = 1),
            _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),
        ],
    )
    _fork("src", "fork-1", 99)
    stale = dict(studio_db.get_chat_thread("fork-1"))

    copied = studio_db.list_chat_messages("fork-1")
    studio_db.sync_chat_messages(
        "fork-1",
        [m for m in copied if m["id"] != stale["forkBoundaryMessageId"]],
        prune_missing = True,
    )
    reseated = studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"]
    assert reseated != stale["forkBoundaryMessageId"]

    studio_db.upsert_chat_thread({**stale, "archived": True})

    assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == reseated
    assert studio_db.get_chat_thread("fork-1")["archived"] is True


def test_a_patch_repeating_the_stored_title_keeps_the_base(tmp_path, monkeypatch):
    """Renaming a pair patches every thread in it, so one can be sent the name it already has.
    That is not a rename, and clearing there would cost its next fork a number."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    forked = _fork("src", "fork-1", 99)
    assert forked["title"] == "Notes (1)"

    studio_db.update_chat_thread("fork-1", {"title": "Notes (1)"})

    assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] == "Notes"
    assert _fork("fork-1", "fork-2", 100)["title"] == "Notes (2)"


def test_a_stale_whole_record_save_cannot_restore_a_cleared_base(tmp_path, monkeypatch):
    """A writer carries the base it read, which a rename it never saw may have cleared.
    Renaming away and back leaves the titles equal, so only the stored value can decide."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    _fork("src", "fork-1", 99)
    stale = dict(studio_db.get_chat_thread("fork-1"))
    assert stale["forkTitleBase"] == "Notes"

    studio_db.update_chat_thread("fork-1", {"title": "Report"})
    studio_db.update_chat_thread("fork-1", {"title": "Notes (1)"})
    assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None

    studio_db.upsert_chat_thread({**stale, "archived": True})

    assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None
    assert _fork("fork-1", "fork-2", 100)["title"] == "Notes (1) (1)"


def test_a_whole_record_rename_clears_the_base_it_carries(tmp_path, monkeypatch):
    """The record a client read still holds the old base, so the title has to decide alone."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])
    _fork("src", "fork-1", 99)

    carried = dict(studio_db.get_chat_thread("fork-1"))
    assert carried["forkTitleBase"] == "Notes"
    studio_db.upsert_chat_thread({**carried, "title": "Report"})

    assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None
    assert _fork("fork-1", "fork-2", 100)["title"] == "Report (1)"


def test_plain_thread_has_no_fork_boundary(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread(_thread("plain"))
    assert studio_db.get_chat_thread("plain")["forkBoundaryMessageId"] is None


def _forked_thread(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})
    studio_db.sync_chat_messages(
        "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]
    )
    return _fork("src", "f", 9)


def test_pruning_the_boundary_moves_the_divider_up(tmp_path, monkeypatch):
    """Left on a deleted row the boundary matches nothing, and the divider never comes back."""
    _forked_thread(tmp_path, monkeypatch)
    copied = studio_db.list_chat_messages("f")
    studio_db.sync_chat_messages("f", copied[:-1], prune_missing = True)

    survivors = [m["id"] for m in studio_db.list_chat_messages("f")]
    assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] == survivors[-1]


def test_pruning_every_inherited_message_clears_the_boundary(tmp_path, monkeypatch):
    _forked_thread(tmp_path, monkeypatch)
    studio_db.sync_chat_messages("f", [], prune_missing = True)

    assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] is None


def test_pruning_an_earlier_message_leaves_the_boundary_alone(tmp_path, monkeypatch):
    forked = _forked_thread(tmp_path, monkeypatch)
    copied = studio_db.list_chat_messages("f")
    studio_db.sync_chat_messages("f", copied[1:], prune_missing = True)

    assert (
        studio_db.get_chat_thread("f")["forkBoundaryMessageId"] == forked["forkBoundaryMessageId"]
    )


def test_the_reseat_skips_an_ancestor_that_paints_no_row(tmp_path, monkeypatch):
    """A system message can survive a prune that takes the boundary. It renders as nothing,
    so parking the divider there loses it just as surely as leaving it on the deleted row."""
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})
    studio_db.sync_chat_messages(
        "src",
        [
            _stored_message(id = "m1", parentId = None, createdAt = 1),
            _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),
            _stored_message(id = "m3", parentId = "m2", role = "system", createdAt = 3),
            _stored_message(id = "m4", parentId = "m3", createdAt = 4),
        ],
    )
    forked = _fork("src", "f", 10)
    copied = studio_db.list_chat_messages("f")
    by_id = {m["id"]: m for m in copied}
    boundary = forked["forkBoundaryMessageId"]

    studio_db.sync_chat_messages(
        "f", [m for m in copied if m["id"] != boundary], prune_missing = True
    )

    moved = studio_db.get_chat_thread("f")["forkBoundaryMessageId"]
    assert by_id[moved]["role"] == "assistant"


def test_the_reseat_clears_when_only_hidden_ancestors_survive(tmp_path, monkeypatch):
    _reset_studio_db(tmp_path, monkeypatch)
    studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})
    studio_db.sync_chat_messages(
        "src",
        [
            _stored_message(id = "m1", parentId = None, role = "system", createdAt = 1),
            _stored_message(id = "m2", parentId = "m1", createdAt = 2),
        ],
    )
    forked = _fork("src", "f", 10)
    copied = studio_db.list_chat_messages("f")
    boundary = forked["forkBoundaryMessageId"]

    studio_db.sync_chat_messages(
        "f", [m for m in copied if m["id"] != boundary], prune_missing = True
    )

    assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] is None