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
# 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 asyncio
import inspect
import os
import re
import sqlite3
import sys
import threading
from types import SimpleNamespace
import pytest
from typing import Optional
from fastapi import HTTPException
from pydantic import ValidationError
_backend = os.path.join(os.path.dirname(__file__), "..")
sys.path.insert(0, _backend)
from core.inference.llama_server_args import BATCH_MAX
from routes import chat_history
def _message(message_id: str, thread_id: str) -> chat_history.ChatMessage:
return chat_history.ChatMessage(
id = message_id,
threadId = thread_id,
parentId = None,
role = "user",
content = [{"type": "text", "text": "hello"}],
createdAt = 1_700_000_000_000,
)
def test_async_delete_handlers_dispatch_sqlite_to_the_threadpool():
"""Cleanup handlers may be async, but their blocking sqlite work must leave the event loop."""
coroutine_handlers = sorted(
route.endpoint.__name__
for route in chat_history.router.routes
if inspect.iscoroutinefunction(route.endpoint)
)
assert coroutine_handlers == ["clear_history", "delete_project", "delete_threads"]
for handler in (
chat_history.clear_history,
chat_history.delete_project,
chat_history.delete_threads,
):
assert "run_in_threadpool" in inspect.getsource(handler)
def test_message_removal_paths_sweep_chat_originals(monkeypatch):
"""Removal or rewrite can drop the last reference to a kept original, so all paths sweep."""
for handler in (
chat_history.clear_history,
chat_history.delete_project,
chat_history.delete_threads,
):
assert "chat_originals.sweep" in inspect.getsource(handler)
sweeps = []
monkeypatch.setattr(chat_history, "get_chat_thread", lambda thread_id: {"id": thread_id})
monkeypatch.setattr(chat_history, "sync_chat_messages", lambda *args, **kwargs: [])
monkeypatch.setattr(
chat_history.chat_originals, "sweep", lambda force = False: sweeps.append(force)
)
for prune, deleted in ((False, []), (True, []), (False, ["msg-2"])):
chat_history.replace_thread_messages(
"thread-1",
chat_history.ChatMessageSyncRequest(
messages = [_message("msg-1", "thread-1")],
pruneMissing = prune,
deletedMessageIds = deleted,
),
current_subject = "test-user",
)
monkeypatch.setattr(chat_history, "upsert_chat_message", lambda message, **kwargs: message)
chat_history.save_thread_message(
"thread-1", "msg-1", _message("msg-1", "thread-1"), current_subject = "test-user"
)
assert sweeps == [False] * 4
def test_replace_thread_messages_rejects_body_thread_mismatch(monkeypatch):
called = False
def fake_get_chat_thread(thread_id: str):
return {"id": thread_id}
def fake_sync_chat_messages(*args, **kwargs):
nonlocal called
called = True
return []
monkeypatch.setattr(chat_history, "get_chat_thread", fake_get_chat_thread)
monkeypatch.setattr(chat_history, "sync_chat_messages", fake_sync_chat_messages)
with pytest.raises(HTTPException) as exc_info:
chat_history.replace_thread_messages(
"thread-1",
chat_history.ChatMessageSyncRequest(
messages = [_message("msg-1", "thread-2")],
pruneMissing = True,
),
current_subject = "test-user",
)
assert exc_info.value.status_code == 400
assert "Message threadId mismatch" in str(exc_info.value.detail)
assert called is False
def test_replace_thread_messages_reports_protected_research_turn(monkeypatch):
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: {"id": "thread-1"})
def reject_prune(*_args, **_kwargs):
raise chat_history.ChatMessageProtectedError(
"Research prompts and responses cannot be deleted from their original thread"
)
monkeypatch.setattr(chat_history, "sync_chat_messages", reject_prune)
with pytest.raises(HTTPException) as exc_info:
chat_history.replace_thread_messages(
"thread-1",
chat_history.ChatMessageSyncRequest(messages = [], pruneMissing = True),
current_subject = "test-user",
)
assert exc_info.value.status_code == 409
assert "Research prompts and responses" in str(exc_info.value.detail)
def test_save_thread_message_forwards_explicit_generation_edit(monkeypatch):
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: {"id": "thread-1"})
captured = {}
def save(message, *, allow_generation_edit = False):
captured["allow_generation_edit"] = allow_generation_edit
return message
monkeypatch.setattr(chat_history, "upsert_chat_message", save)
payload = _message("assistant-1", "thread-1").model_copy(update = {"role": "assistant"})
chat_history.save_thread_message(
"thread-1",
"assistant-1",
payload,
allow_generation_edit = True,
current_subject = "test-user",
)
assert captured == {"allow_generation_edit": True}
def test_save_thread_message_returns_404_when_thread_is_deleted_during_write(monkeypatch):
parent_reads = iter(({"id": "thread-1"}, None))
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: next(parent_reads))
def missing_parent(*_args, **_kwargs):
raise sqlite3.IntegrityError("FOREIGN KEY constraint failed")
monkeypatch.setattr(chat_history, "upsert_chat_message", missing_parent)
with pytest.raises(HTTPException) as exc_info:
chat_history.save_thread_message(
"thread-1",
"msg-1",
_message("msg-1", "thread-1"),
current_subject = "test-user",
)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Thread thread-1 not found"
def test_replace_thread_messages_returns_404_when_thread_is_deleted_during_write(monkeypatch):
parent_reads = iter(({"id": "thread-1"}, None))
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: next(parent_reads))
def missing_parent(*_args, **_kwargs):
raise sqlite3.IntegrityError("FOREIGN KEY constraint failed")
monkeypatch.setattr(chat_history, "sync_chat_messages", missing_parent)
with pytest.raises(HTTPException) as exc_info:
chat_history.replace_thread_messages(
"thread-1",
chat_history.ChatMessageSyncRequest(
messages = [_message("msg-1", "thread-1")],
pruneMissing = True,
),
current_subject = "test-user",
)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Thread thread-1 not found"
def test_save_thread_message_does_not_mask_an_unrelated_integrity_error(monkeypatch):
monkeypatch.setattr(
chat_history,
"get_chat_thread",
lambda _thread_id: {"id": "thread-1"},
)
failure = sqlite3.IntegrityError("unrelated constraint")
def raise_unrelated(*_args, **_kwargs):
raise failure
monkeypatch.setattr(chat_history, "upsert_chat_message", raise_unrelated)
with pytest.raises(sqlite3.IntegrityError) as exc_info:
chat_history.save_thread_message(
"thread-1",
"msg-1",
_message("msg-1", "thread-1"),
current_subject = "test-user",
)
assert exc_info.value is failure
def test_save_thread_distinguishes_a_tombstone_from_an_unknown_id(monkeypatch):
def reject_deleted_thread(_thread):
raise chat_history.ChatThreadDeletedError("thread-1")
monkeypatch.setattr(chat_history, "upsert_chat_thread", reject_deleted_thread)
payload = chat_history.ChatThread(
id = "thread-1",
title = "Deleted",
modelType = "base",
modelId = "model-1",
createdAt = 1,
)
with pytest.raises(HTTPException) as exc_info:
chat_history.save_thread(payload, current_subject = "test-user")
assert exc_info.value.status_code == 410
assert exc_info.value.detail == "Thread thread-1 was deleted"
def test_chat_thread_payload_carries_gguf_variant():
thread = chat_history.ChatThread(
id = "thread-1",
title = "GGUF chat",
modelType = "base",
modelId = "unsloth/Qwen3-GGUF",
modelGgufVariant = "Q6_K",
createdAt = 1,
)
patch = chat_history.ChatThreadPatch(modelGgufVariant = "Q8_0")
assert thread.model_dump()["modelGgufVariant"] == "Q6_K"
assert patch.model_dump(exclude_unset = True) == {"modelGgufVariant": "Q8_0"}
def test_clear_history_fences_pending_thread_ids(monkeypatch):
captured: list[str] = []
captured_operation_ids: list[str | None] = []
def clear_with_ids(
thread_ids = (),
operation_id = None,
include_chat_generation_runs = False,
):
captured.extend(thread_ids)
captured_operation_ids.append(operation_id)
result = (list(thread_ids), [])
return (*result, [], False) if include_chat_generation_runs else (*result, False)
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "clear_chat_history_with_replay_status", clear_with_ids)
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
response = asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = ["pending-thread"], operationId = "clear-operation-1"),
current_subject = "test-user",
)
)
assert response == {
"status": "deleted",
"deletedThreadIds": ["pending-thread"],
"sandboxes_removed": 0,
"sandboxes_kept": [],
}
assert captured == ["pending-thread"]
assert captured_operation_ids == ["clear-operation-1"]
def test_clear_history_reaps_search_thumbnails_with_a_body(monkeypatch):
"""Reap search thumbnails on every clear; gating the reap on payload is None meant it never ran."""
from core.inference import search_images
reaped: list[bool] = []
monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append(True))
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(
chat_history,
"clear_chat_history_with_replay_status",
lambda thread_ids = (), operation_id = None, include_chat_generation_runs = False: (
([], [], [], False) if include_chat_generation_runs else ([], [], False)
),
)
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-2"),
current_subject = "test-user",
)
)
assert reaped == [True]
def test_project_delete_cancels_research_before_workspace_cleanup(monkeypatch):
project = {
"id": "project-1",
"name": "Project",
"createdAt": 1,
"updatedAt": 1,
"memberIds": ["thread-1"],
"activeResearchRunIds": ["run-1"],
}
cancelled: list[str] = []
monkeypatch.setattr(
chat_history,
"delete_chat_project",
lambda _project_id, delete_files = False: project,
)
monkeypatch.setattr(
chat_history,
"_cancel_research_runs",
lambda _request, run_ids: cancelled.extend(run_ids),
)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
async def fail_workspace_cleanup(_ids, _delete_files):
raise OSError("workspace is busy")
monkeypatch.setattr(chat_history, "_remove_sandboxes", fail_workspace_cleanup)
with pytest.raises(OSError, match = "workspace is busy"):
asyncio.run(
chat_history.delete_project(
"project-1",
SimpleNamespace(),
delete_files = True,
current_subject = "test-user",
)
)
assert cancelled == ["run-1"]
def test_chat_settings_payload_accepts_fast_mode_presets():
payload = chat_history.ChatSettingsPayload.model_validate(
{
"inferenceParams": {"fastMode": False},
"customPresets": [
{
"name": "Fast Opus",
"params": {
"temperature": 0.6,
"topP": 0.95,
"topK": 20,
"minP": 0.01,
"repetitionPenalty": 1.0,
"presencePenalty": 0.0,
"maxTokens": 8192,
"systemPrompt": "",
"trustRemoteCode": False,
"fastMode": True,
},
},
],
}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped["inferenceParams"]["fastMode"] is False
assert dumped["customPresets"][0]["params"]["fastMode"] is True
def test_chat_settings_payload_carries_per_model_params():
"""The payload is extra="forbid", so per-model memory only reaches the DB if the
schema names both keys. A patch also has to survive exclude_unset with just the
one model it touched, since that is what keeps other models' settings intact."""
payload = chat_history.ChatSettingsPayload.model_validate(
{
"rememberParamsPerModel": True,
"inferenceParamsByModel": {
"unsloth/Qwen3.5-9B-GGUF": {"temperature": 0.2, "maxTokens": 4096},
},
}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped["rememberParamsPerModel"] is True
assert dumped["inferenceParamsByModel"] == {
"unsloth/Qwen3.5-9B-GGUF": {"temperature": 0.2, "maxTokens": 4096},
}
assert "inferenceParams" not in dumped
def test_chat_settings_payload_rejects_junk_per_model_params():
"""Model keys are opaque, but the values are real settings, so unknown fields must 400."""
with pytest.raises(ValidationError):
chat_history.ChatSettingsPayload.model_validate(
{"inferenceParamsByModel": {"openai:gpt-x": {"notAParam": 1}}}
)
def test_conditional_chat_settings_payload_validates_both_sides():
payload = chat_history.ConditionalChatSettingsPayload.model_validate(
{
"expected": {"inferenceParams": {"presencePenalty": 0.0}},
"expectedAbsent": ["reasoningEnabled"],
"expectedAbsentPaths": [["inferenceParams", "topK"]],
"patch": {"inferenceParams": {"presencePenalty": 1.5}},
}
)
assert payload.expected.inferenceParams.presencePenalty == 0.0
assert payload.expectedAbsent == ["reasoningEnabled"]
assert payload.expectedAbsentPaths == [["inferenceParams", "topK"]]
assert payload.patch.inferenceParams.presencePenalty == 1.5
with pytest.raises(ValidationError):
chat_history.ConditionalChatSettingsPayload.model_validate(
{
"expected": {},
"expectedAbsent": ["unknownSetting"],
"patch": {},
}
)
with pytest.raises(ValidationError):
chat_history.ConditionalChatSettingsPayload.model_validate(
{
"expected": {},
"expectedAbsentPaths": [["unknownSetting", "topK"]],
"patch": {},
}
)
def test_chat_settings_payload_accepts_preset_load_config():
payload = chat_history.ChatSettingsPayload.model_validate(
{
"customPresets": [
{
"name": "GGUF preset",
"params": {"temperature": 0.7, "maxTokens": 512},
"loadConfig": {
"customContextLength": 256,
"kvCacheDtype": "q8_0",
"tensorParallel": False,
},
},
],
}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped["customPresets"][0]["loadConfig"]["customContextLength"] == 256
assert dumped["customPresets"][0]["loadConfig"]["kvCacheDtype"] == "q8_0"
def test_chat_settings_payload_accepts_preset_batch_sizes():
from pydantic import ValidationError
# extra='forbid' 400s the whole write, and the normalizer emits both keys on every preset.
payload = chat_history.ChatSettingsPayload.model_validate(
{
"customPresets": [
{
"name": "batch preset",
"params": {"temperature": 0.7},
"loadConfig": {"nParallel": 4, "nBatch": 4096, "nUbatch": 1024},
},
],
}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped["customPresets"][0]["loadConfig"]["nBatch"] == 4096
assert dumped["customPresets"][0]["loadConfig"]["nUbatch"] == 1024
chat_history.ChatPresetLoadConfig.model_validate(
{"nParallel": 4, "nBatch": None, "nUbatch": None}
)
for bad in ({"nBatch": 0}, {"nUbatch": BATCH_MAX + 1}, {"nBatch": True}):
with pytest.raises(ValidationError):
chat_history.ChatPresetLoadConfig.model_validate(bad)
def test_chat_settings_payload_accepts_preset_server_tuning_and_vision():
# normalizePresetLoadConfig always emits these keys; extra='forbid' would 400 the save.
payload = chat_history.ChatSettingsPayload.model_validate(
{
"customPresets": [
{
"name": "Test",
"params": {"temperature": 0.7, "systemPrompt": "You are Test."},
"loadConfig": {
"nParallel": 4,
"nBatch": None,
"nUbatch": None,
"loadMode": None,
"specDraftCacheDtype": None,
"ctxCheckpoints": None,
"cacheRam": None,
"tensorParallel": False,
"disableVision": False,
},
},
],
"activePreset": "Test",
"activePresetSource": "custom",
}
)
dumped = payload.model_dump(exclude_unset = True)
load = dumped["customPresets"][0]["loadConfig"]
assert load["loadMode"] is None
assert load["disableVision"] is False
assert dumped["activePreset"] == "Test"
chat_history.ChatPresetLoadConfig.model_validate(
{
"loadMode": "mmap+mlock",
"specDraftCacheDtype": "q8_0",
"ctxCheckpoints": 8,
"cacheRam": 2048,
"disableVision": True,
}
)
for bad in (
{"ctxCheckpoints": True},
{"cacheRam": True},
{"ctxCheckpoints": -1},
{"cacheRam": -2},
{"loadMode": "swap"},
):
with pytest.raises(ValidationError):
chat_history.ChatPresetLoadConfig.model_validate(bad)
def test_chat_preset_load_config_covers_frontend_persisted_fields():
# Drift guard: every persisted preset load key must exist on ChatPresetLoadConfig (forbid).
preset_ts = os.path.join(
_backend,
"..",
"frontend",
"src",
"features",
"chat",
"presets",
"preset-load-config.ts",
)
if not os.path.exists(preset_ts):
pytest.skip("frontend preset-load-config.ts not present")
with open(preset_ts, encoding = "utf-8") as fh:
block = re.search(
r"export type PresetLoadConfig = Pick<\s*PerModelConfig,\s*((?:.|\n)*?)\s*>;",
fh.read(),
)
assert block, "PresetLoadConfig Pick not found in preset-load-config.ts"
persisted = set(re.findall(r'"(\w+)"', block.group(1)))
assert persisted, "no PresetLoadConfig keys parsed"
backend = set(chat_history.ChatPresetLoadConfig.model_fields)
backend -= {"mlxKvBits"}
assert (
persisted == backend
), f"schema drift: frontend-only {persisted - backend}, backend-only {backend - persisted}"
def test_chat_settings_payload_accepts_mlx_kv_quant():
from pydantic import ValidationError
payload = chat_history.ChatSettingsPayload.model_validate(
{
"customPresets": [
{
"name": "MLX preset",
"params": {"temperature": 0.7},
"loadConfig": {"mlxKvQuant": "tq-3.5"},
},
],
}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped["customPresets"][0]["loadConfig"]["mlxKvQuant"] == "tq-3.5"
chat_history.ChatPresetLoadConfig.model_validate({"mlxKvQuant": "auto"})
for width in (4, None):
chat_history.ChatPresetLoadConfig.model_validate({"mlxKvBits": width})
with pytest.raises(ValidationError):
chat_history.ChatPresetLoadConfig.model_validate({"mlxKvBits": 7})
def test_chat_settings_payload_accepts_nudge_tool_calls():
# extra='forbid' 400s unknown keys, so persisted nudgeToolCalls needs a payload field.
payload = chat_history.ChatSettingsPayload.model_validate(
{"autoHealToolCalls": True, "nudgeToolCalls": False}
)
dumped = payload.model_dump(exclude_unset = True)
assert dumped == {"autoHealToolCalls": True, "nudgeToolCalls": False}
def test_chat_inference_settings_covers_frontend_persisted_fields():
# Drift guard: UI-persisted InferenceParams fields must exist on ChatInferenceSettings.
runtime_ts = os.path.join(
_backend,
"..",
"frontend",
"src",
"features",
"chat",
"types",
"runtime.ts",
)
if not os.path.exists(runtime_ts):
pytest.skip("frontend runtime.ts not present")
with open(runtime_ts, encoding = "utf-8") as fh:
source = fh.read()
block = re.search(r"interface InferenceParams \{(.*?)\n\}", source, re.DOTALL)
assert block, "InferenceParams interface not found in runtime.ts"
omitted = re.search(
r"PersistedInferenceParams = Partial<\s*Omit<\s*InferenceParams,([^>]*)>", source
)
assert omitted, "PersistedInferenceParams Omit<> not found in runtime.ts"
persisted = set(re.findall(r"^\s*(\w+)\??:", block.group(1), re.M)) - set(
re.findall(r'"(\w+)"', omitted.group(1))
)
backend = set(chat_history.ChatInferenceSettings.model_fields)
assert (
persisted == backend
), f"schema drift: frontend-only {persisted - backend}, backend-only {backend - persisted}"
def test_get_import_ledger_round_trips_through_storage(monkeypatch):
seen: list[str] = []
def fake_list():
return list(seen)
monkeypatch.setattr(chat_history, "list_chat_legacy_imports", fake_list)
response = chat_history.get_import_ledger(current_subject = "test-user")
assert response.threadIds == []
seen.extend(["legacy-a", "legacy-b"])
response = chat_history.get_import_ledger(current_subject = "test-user")
assert response.threadIds == ["legacy-a", "legacy-b"]
def test_record_import_ledger_returns_accepted_and_inserted(monkeypatch):
captured: list[list[str]] = []
def fake_upsert(thread_ids):
captured.append(list(thread_ids))
return (len(thread_ids), max(0, len(thread_ids) - 2))
monkeypatch.setattr(chat_history, "upsert_chat_legacy_imports", fake_upsert)
response = chat_history.record_import_ledger(
payload = chat_history.ChatImportLedgerRecordRequest(
threadIds = ["a", "b", "c"],
),
current_subject = "test-user",
)
assert response.accepted == 3
assert response.inserted == 1
assert captured == [["a", "b", "c"]]
def test_record_import_ledger_rejects_oversize_payload():
from pydantic import ValidationError
with pytest.raises(ValidationError):
chat_history.ChatImportLedgerRecordRequest(
threadIds = [f"id-{i}" for i in range(10_001)],
)
def test_fork_thread_404_when_source_missing(monkeypatch):
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: None)
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "missing",
payload = chat_history.ChatForkRequest(
messageId = "m1",
newThreadId = "new",
createdAt = 1,
),
current_subject = "test-user",
)
assert exc.value.status_code == 404
def test_fork_thread_404_when_branch_message_missing(monkeypatch):
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})
monkeypatch.setattr(chat_history, "get_chat_message", lambda _t, _m: None)
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(
messageId = "missing",
newThreadId = "new",
createdAt = 1,
),
current_subject = "test-user",
)
assert exc.value.status_code == 404
@pytest.mark.parametrize("same_timestamp", [False, True])
def test_fork_thread_resolves_the_tip_when_no_message_is_given(same_timestamp):
from storage import studio_db
studio_db.upsert_chat_thread(
{"id": "src", "title": "T", "modelType": "base", "modelId": "local", "createdAt": 1}
)
for message_id, parent_id, role, created_at in (
("root", None, "user", 1),
("z-user", "root", "user", 2),
("a-reply", "z-user", "assistant", 2 if same_timestamp else 3),
):
message = _message(message_id, "src").model_dump()
message.update({"createdAt": created_at, "parentId": parent_id, "role": role})
studio_db.upsert_chat_message(message)
response = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 4),
current_subject = "test-user",
)
assert response.thread.forkedFromMessageId == "a-reply"
assert len(response.messages) == 3
assert any(message.role == "assistant" for message in response.messages)
def test_fork_thread_404_when_the_thread_has_no_messages():
from storage import studio_db
studio_db.upsert_chat_thread(
{"id": "src", "title": "T", "modelType": "base", "modelId": "local", "createdAt": 1}
)
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 1),
current_subject = "test-user",
)
assert exc.value.status_code == 404
assert studio_db.get_chat_thread("new") is None
def test_fork_thread_refuses_before_it_resolves_the_tip(monkeypatch):
"""The generation check runs first, or the tip would be read while it is still moving."""
import threading
from state import active_generations
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})
def _never(_t):
raise AssertionError("the tip was read before the generation check")
monkeypatch.setattr(chat_history, "list_chat_messages", _never)
with active_generations.ActiveGeneration(threading.Event(), thread_id = "src"):
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 1),
current_subject = "test-user",
)
assert exc.value.status_code == 409
def test_fork_thread_409_while_the_chat_is_generating(monkeypatch):
"""Refuse forking a generating chat in the request itself; the client check can race another tab."""
import threading
from state import active_generations
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})
with active_generations.ActiveGeneration(threading.Event(), thread_id = "src"):
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(
messageId = "m1",
newThreadId = "new",
createdAt = 1,
),
current_subject = "test-user",
)
assert exc.value.status_code == 409
assert "still generating" in str(exc.value.detail)
def test_fork_thread_allows_a_fork_of_another_generating_chat(monkeypatch):
"""Only the chat being forked is refused; a different one generating is no reason to."""
import threading
from state import active_generations
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})
monkeypatch.setattr(chat_history, "get_chat_message", lambda _t, _m: None)
with active_generations.ActiveGeneration(threading.Event(), thread_id = "other"):
with pytest.raises(HTTPException) as exc:
chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(
messageId = "missing",
newThreadId = "new",
createdAt = 1,
),
current_subject = "test-user",
)
assert exc.value.status_code == 404
def test_fork_thread_happy_path(monkeypatch):
source = {
"id": "src",
"title": "Original",
"modelType": "base",
"modelId": "m",
"pairId": None,
"archived": False,
"createdAt": 1,
"openaiCodeExecContainerId": None,
"anthropicCodeExecContainerId": None,
"forkedFromThreadId": None,
"forkedFromMessageId": None,
}
forked = {
**source,
"id": "new",
"title": "Original (1)",
"createdAt": 2,
"forkedFromThreadId": "src",
"forkedFromMessageId": "m1",
}
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: source)
monkeypatch.setattr(
chat_history,
"get_chat_message",
lambda _t, _m: {
"id": _m,
"threadId": _t,
"role": "user",
"content": [],
"createdAt": 1,
},
)
monkeypatch.setattr(chat_history, "fork_chat_thread", lambda **_: forked)
monkeypatch.setattr(
chat_history,
"list_chat_messages",
lambda _id: [
{
"id": "n1",
"threadId": "new",
"parentId": None,
"role": "user",
"content": [],
"createdAt": 1,
}
],
)
response = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(
messageId = "m1",
newThreadId = "new",
createdAt = 2,
),
current_subject = "test-user",
)
assert response.thread.id == "new"
assert response.thread.title == "Original (1)"
assert response.thread.forkedFromThreadId == "src"
assert response.thread.forkedFromMessageId == "m1"
assert len(response.messages) == 1
assert response.containerSnapshotWarning is None
def test_fork_thread_warns_when_parent_had_container(monkeypatch):
source = {
"id": "src",
"title": "T",
"modelType": "base",
"modelId": "",
"pairId": None,
"archived": False,
"createdAt": 1,
"openaiCodeExecContainerId": "cnt_123",
"anthropicCodeExecContainerId": None,
"forkedFromThreadId": None,
"forkedFromMessageId": None,
}
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: source)
monkeypatch.setattr(
chat_history,
"get_chat_message",
lambda _t, _m: {
"id": _m,
"threadId": _t,
"role": "user",
"content": [],
"createdAt": 1,
},
)
monkeypatch.setattr(
chat_history,
"fork_chat_thread",
lambda **_: {
**source,
"id": "new",
"title": "T (1)",
"forkedFromThreadId": "src",
"forkedFromMessageId": "m1",
"openaiCodeExecContainerId": None,
},
)
monkeypatch.setattr(chat_history, "list_chat_messages", lambda _id: [])
response = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(
messageId = "m1",
newThreadId = "new",
createdAt = 2,
),
current_subject = "test-user",
)
assert response.containerSnapshotWarning is not None
assert "fresh" in response.containerSnapshotWarning.lower()
def test_get_fork_count(monkeypatch):
monkeypatch.setattr(chat_history, "count_forks_for_message", lambda _t, _m: 3)
response = chat_history.get_fork_count(
thread_id = "t",
message_id = "m",
current_subject = "test-user",
)
assert response.count == 3
def test_get_thread_fork_counts(monkeypatch):
monkeypatch.setattr(chat_history, "fork_counts_for_thread", lambda _t: {"m1": 2, "m2": 1})
response = chat_history.get_thread_fork_counts(
thread_id = "t",
current_subject = "test-user",
)
assert response.counts == {"m1": 2, "m2": 1}
def _clear_thread_row(thread_id: str) -> dict:
return {
"id": thread_id,
"title": "Test Chat",
"modelType": "base",
"modelId": "test-model",
"pairId": None,
"archived": False,
"createdAt": 1_700_000_000_000,
}
def test_a_clear_does_not_reap_an_image_registered_while_it_was_running(tmp_path, monkeypatch):
"""Reap only the thumbnails snapshotted before the slow work, since the registry is global."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
monkeypatch.setattr(search_images, "_registry", {})
monkeypatch.setattr(search_images, "_cleared_unservable", set())
monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")
(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)
old = search_images.register_images(
[
{
"title": "before",
"image": "https://img.example.com/a.jpg",
"thumbnail": "https://tse1.mm.bing.net/th?id=a",
"url": "https://example.com/a",
"source": "Bing",
}
]
)
assert old, "fixture must register: the whole test turns on this id being reapable"
old_id = old[0]["id"]
late: dict[str, str] = {}
async def remove_sandboxes(_thread_ids, _delete_files):
entries = search_images.register_images(
[
{
"title": "during",
"image": "https://img.example.com/b.jpg",
"thumbnail": "https://tse1.mm.bing.net/th?id=b",
"url": "https://example.com/b",
"source": "Bing",
}
]
)
late["id"] = entries[0]["id"]
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-race"),
current_subject = "test-user",
)
)
assert late.get("id"), "the stand-in never registered, so this asserts nothing"
assert search_images.lookup_image(late["id"]) is not None, (
"an image registered while the clear was running belongs to a chat the clear "
"kept, so reaping it 404s that chat's cards"
)
assert (
search_images.lookup_image(old_id) is None
), "the clear still has to reap what it was responsible for"
def test_replayed_clear_keeps_the_thumbnails_of_a_chat_it_did_not_delete(tmp_path, monkeypatch):
"""A replayed clear must not reap the global thumbnail registry again, or it takes others' images."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
reaped: list[str] = []
monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append("reaped"))
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
def clear():
return asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-retry"),
current_subject = "test-user",
)
)
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
assert clear()["deletedThreadIds"] == ["before-clear"]
assert reaped == ["reaped"], "the first clear has to reap: the thumbnails say what was searched"
studio_db.upsert_chat_thread(_clear_thread_row("after-clear"))
replay = clear()
assert replay["deletedThreadIds"] == ["before-clear"]
assert studio_db.get_chat_thread("after-clear") is not None
assert reaped == ["reaped"], "the replay reaped a surviving chat's thumbnails"
def test_the_replay_bit_comes_from_the_clear_transaction(monkeypatch, tmp_path):
"""Of concurrent retries, only the winner clears; replay bit is set in its transaction."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
reaps: list[str] = []
reap_lock = threading.Lock()
def record_reap(only_ids = None):
with reap_lock:
reaps.append("reaped")
monkeypatch.setattr(search_images, "clear_cache", record_reap)
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
# Both threads must pass the point that decides `replayed` before either commits.
start = threading.Barrier(2)
failures: list[BaseException] = []
def clear():
try:
start.wait(timeout = 10)
asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-concurrent"),
current_subject = "test-user",
)
)
except BaseException as exc: # noqa: BLE001 -- re-raised on the main thread
failures.append(exc)
threads = [threading.Thread(target = clear) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout = 30)
if failures:
raise failures[0]
assert reaps == ["reaped"], (
"only the request that actually performed the clear may reap the global "
f"thumbnail registry; got {len(reaps)} reaps"
)
def test_clear_history_does_not_read_the_replay_ledger_outside_the_transaction():
"""The replay flag must come from the clear transaction's own return, not a separate ledger read."""
source = inspect.getsource(chat_history.clear_history)
assert "clear_chat_history_with_replay_status" in source
assert (
"chat_clear_operation_is_recorded" not in source
), "a pre-transaction ledger read cannot tell a replay from a concurrent clear"
def test_a_chat_created_in_the_gap_after_the_clear_keeps_its_images(monkeypatch, tmp_path):
"""Clear and snapshot in one threadpool call; an await between them lets new images register first."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
monkeypatch.setattr(search_images, "_registry", {})
monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")
(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)
reaped: list = []
monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append(only_ids))
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
late_image_id = "beefbeefbeef"
hops = {"n": 0}
# Imported inside the handler, so patch the source module, not routes.chat_history.
import starlette.concurrency
real_run_in_threadpool = starlette.concurrency.run_in_threadpool
async def interleaving_run_in_threadpool(func, *args, **kwargs):
result = await real_run_in_threadpool(func, *args, **kwargs)
hops["n"] += 1
if hops["n"] == 1:
search_images._registry[late_image_id] = {
"thumbnail": "https://example.invalid/x.jpg",
"source": "https://example.invalid/",
"created": 0.0,
"policy": None,
}
return result
monkeypatch.setattr(starlette.concurrency, "run_in_threadpool", interleaving_run_in_threadpool)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-gap"),
current_subject = "test-user",
)
)
assert reaped, "the clear still has to reap what it was responsible for"
snapshot = reaped[0]
assert snapshot is not None, "a real clear reaps a bounded set, not everything"
assert late_image_id not in snapshot, (
"an image registered after the clear committed belongs to a chat the clear kept, "
"so the reap must not be allowed to take it"
)
def test_the_clear_and_its_image_snapshot_share_one_threadpool_hop():
"""The structural half of the race above, which no test scheduling can hide."""
source = inspect.getsource(chat_history.clear_history)
assert source.count("run_in_threadpool(_clear_rows)") == 1
assert (
"run_in_threadpool(_snapshot_chat_images)" not in source
), "a second hop for the snapshot reopens the gap the first one closed"
body = source.split("def _clear_rows(", 1)[1].split("\n # The clear reports", 1)[0]
assert (
"_snapshot_chat_images()" in body
), "the snapshot belongs inside the clear's hop, and it carries the registration fence"
assert "snapshot_and_fence_registrations()" in inspect.getsource(
chat_history._snapshot_chat_images
)
def test_a_replay_finishes_a_reap_the_original_clear_died_before_running(monkeypatch, tmp_path):
"""Ledger keeps the clear's snapshot and reap state, so a replay after a crash finishes the reap."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
monkeypatch.setattr(search_images, "_registry", {})
monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")
(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)
doomed_image_id = "aaaabbbbcccc"
search_images._registry[doomed_image_id] = {
"thumbnail": "https://example.invalid/x.jpg",
"source": "https://example.invalid/",
"created": 0.0,
"policy": None,
}
reaps: list = []
def reap(only_ids = None):
reaps.append(only_ids)
if len(reaps) == 1:
raise RuntimeError("process died before the reap finished")
monkeypatch.setattr(search_images, "clear_cache", reap)
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
def clear():
return asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-crash"),
current_subject = "test-user",
)
)
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
with pytest.raises(RuntimeError):
clear()
assert reaps == [{doomed_image_id}], "the first attempt got as far as its own reap"
studio_db.upsert_chat_thread(_clear_thread_row("after-crash"))
later_image_id = "ddddeeeeffff"
search_images._registry[later_image_id] = {
"thumbnail": "https://example.invalid/y.jpg",
"source": "https://example.invalid/",
"created": 0.0,
"policy": None,
}
clear()
assert len(reaps) == 2, "the replay has to finish the reap the crash interrupted"
finished = reaps[1]
assert finished == {
doomed_image_id
}, "bounded to the original clear's own snapshot, so a chat created since keeps its images"
assert later_image_id not in finished
clear()
assert len(reaps) == 2, "the finished reap must be recorded, not repeated on every retry"
def test_a_plain_replay_with_nothing_outstanding_still_reaps_nothing(monkeypatch, tmp_path):
"""The ordinary retry. The first attempt completed its reap, so the replay must stay out
of the global registry entirely -- that is what the replay branch is for."""
from core.inference import search_images
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
monkeypatch.setattr(search_images, "_registry", {})
monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")
(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)
reaps: list = []
monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaps.append(only_ids))
async def remove_sandboxes(_thread_ids, _delete_files):
return 0, []
monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)
monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)
monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)
monkeypatch.setattr(chat_history, "_remove_thread_rag_data", lambda _ids, cutoff = None: None)
request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
def clear():
return asyncio.run(
chat_history.clear_history(
request,
chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-plain"),
current_subject = "test-user",
)
)
studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))
clear()
assert len(reaps) == 1
clear()
assert len(reaps) == 1, "a replay behind a completed reap must not touch the registry"
def _conflict_kind(exc_info) -> Optional[str]:
return (exc_info.value.headers or {}).get(chat_history.CONFLICT_KIND_HEADER)
@pytest.mark.parametrize(
"error, kind",
[
(
lambda: chat_history.ChatMessageProtectedError(
"server-managed generation messages cannot be edited"
),
"protected",
),
(
lambda: chat_history.ChatMessageConflictError(
"Message id already belongs to another thread: m1"
),
"thread-collision",
),
],
)
def test_the_two_conflicts_are_distinguishable_on_the_wire(monkeypatch, error, kind):
"""The two 409s must differ on the wire, or the frontend swallows a thread collision as success."""
monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: {"id": "t1"})
def reject(*_args, **_kwargs):
raise error()
monkeypatch.setattr(chat_history, "upsert_chat_message", reject)
message = chat_history.ChatMessage(
id = "m1", threadId = "t1", role = "assistant", content = [], createdAt = 1
)
with pytest.raises(HTTPException) as exc_info:
chat_history.save_thread_message("t1", "m1", message, current_subject = "u")
assert exc_info.value.status_code == 409
assert _conflict_kind(exc_info) == kind
def test_compare_and_set_rejects_a_non_finite_number_renderably(monkeypatch):
# json.loads accepts a bare NaN so it reaches validation; echoing it back would hit Starlette's
# allow_nan = False and turn a refused request into a 500.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
app.include_router(chat_history.router, prefix = "/api/chat")
app.dependency_overrides[chat_history.get_current_subject] = lambda: "admin"
client = TestClient(app)
response = client.post(
"/api/chat/settings/compare-and-set",
content = '{"expected": {"inferenceParams": {"temperature": NaN}}, "patch": {}}',
headers = {"Content-Type": "application/json"},
)
assert response.status_code == 400
assert "NaN" not in response.text
def test_fork_route_numbers_the_title_and_reports_the_boundary(tmp_path, monkeypatch):
"""The whole path, real storage: the name loses the prefix and the divider gets its anchor."""
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
studio_db.upsert_chat_thread(
{"id": "src", "title": "Research notes", "modelType": "base", "createdAt": 1}
)
studio_db.sync_chat_messages(
"src",
[
{
"id": f"m{i}",
"threadId": "src",
"parentId": None if i == 1 else f"m{i - 1}",
"role": "user",
"content": [{"type": "text", "text": f"m{i}"}],
"createdAt": i,
}
for i in (1, 2)
],
)
titles = []
for i in range(2):
response = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = f"fork-{i}", createdAt = 10 + i),
current_subject = "test-user",
)
titles.append(response.thread.title)
assert titles == ["Research notes (1)", "Research notes (2)"]
assert not any(t.startswith("fork") for t in titles)
forked = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = "fork-x", createdAt = 20),
current_subject = "test-user",
)
assert forked.thread.title == "Research notes (3)"
assert forked.thread.forkBoundaryMessageId == forked.messages[-1].id
assert forked.thread.forkBoundaryMessageId not in {"m1", "m2"}
def test_fork_title_comes_from_the_row_not_the_route_s_earlier_read(tmp_path, monkeypatch):
"""A rename landing between the route's read and the write lock must not name the fork."""
from storage import studio_db
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))
monkeypatch.setattr(studio_db, "_schema_ready", set())
studio_db.upsert_chat_thread(
{"id": "src", "title": "Renamed", "modelType": "base", "createdAt": 1}
)
studio_db.sync_chat_messages(
"src",
[
{
"id": "m1",
"threadId": "src",
"parentId": None,
"role": "user",
"content": [{"type": "text", "text": "hi"}],
"createdAt": 1,
}
],
)
monkeypatch.setattr(
chat_history,
"get_chat_thread",
lambda _id: {"id": "src", "title": "Stale name", "modelType": "base", "createdAt": 1},
)
response = chat_history.fork_thread(
thread_id = "src",
payload = chat_history.ChatForkRequest(newThreadId = "fork-1", createdAt = 2),
current_subject = "test-user",
)
assert response.thread.title == "Renamed (1)"
assert "Stale" not in response.thread.title