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.

92.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

"""Chat history API; sync SQLite handlers, except mixed ones that use Starlette's threadpool."""

import asyncio
import json
import os
import re
import sqlite3
from typing import Annotated, Any, Literal, Optional, Union

from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile
from pydantic import (
    BaseModel,
    BeforeValidator,
    ConfigDict,
    Field,
    ValidationError,
    field_serializer,
    field_validator,
    model_validator,
)

from auth.authentication import get_current_subject
from core import chat_originals
from auth import policy
from routes.chat_generation_runs import cancel_account_run
from core.inference.llama_server_args import (
    BATCH_MAX,
    BATCH_MIN,
    CACHE_RAM_MAX_MIB,
    CTX_CHECKPOINTS_MAX,
    PARALLEL_MAX,
    PARALLEL_MIN,
)
from loggers import get_logger
from utils.reasoning_budget import validate_reasoning_budget_message
from utils.api_errors import safe_validation_errors
from utils.account_context import is_owner_context
from utils.utils import safe_curated_detail, log_and_http_error
from storage.studio_db import (
    ChatForkActiveGenerationError,
    MAX_PINNED_CHAT_IDS,
    MAX_PINNED_CHAT_ID_LENGTH,
    ChatMessageConflictError,
    ChatMessageProtectedError,
    ChatThreadDeletedError,
    ChatThreadPreconditionFailed,
    CorruptSettingsError,
    ProjectWorkspaceError,
    build_chat_history_export,
    clear_chat_history,
    clear_chat_history_with_replay_status,
    mark_clear_operation_caches_cleared,
    record_clear_operation_reap_scope,
    unreaped_clear_operation_image_ids,
    count_chat_threads,
    count_forks_for_message,
    delete_chat_attachment,
    delete_chat_project,
    delete_chat_threads_with_active_runs,
    ensure_chat_project_workspace,
    fork_chat_thread,
    fork_counts_for_thread,
    get_chat_attachment,
    get_chat_project,
    get_chat_thread,
    get_chat_pins,
    get_chat_message,
    next_message_created_at,
    list_chat_attachments_page,
    list_chat_projects,
    list_chat_sidebar_rows,
    lookup_chat_sidebar_row_ids,
    SidebarCursorError,
    SIDEBAR_ROWS_MAX_LIMIT,
    list_chat_legacy_imports,
    list_chat_settings,
    list_chat_messages,
    list_chat_messages_for_threads,
    count_chat_messages_for_threads,
    list_chat_threads,
    remap_chat_thread_document_ids,
    set_chat_project_working_folder,
    ProjectWorkingFolderConflictError,
    migrate_chat_pins,
    sync_chat_messages,
    update_chat_project,
    update_chat_thread,
    upsert_chat_project,
    upsert_chat_legacy_imports,
    upsert_chat_message,
    upsert_chat_settings_merge,
    upsert_chat_settings_merge_if_current,
    write_chat_thread_settings,
    upsert_chat_thread,
)

router = APIRouter()

logger = get_logger(__name__)


def _reject_boolean(value: Any) -> Any:
    """bool subclasses int, so lax mode would take `true` for a number the user never set."""
    if isinstance(value, bool):
        raise ValueError("Expected a number, got a boolean.")
    return value


NotABoolean = Annotated[Optional[int], BeforeValidator(_reject_boolean)]
# sqlite INTEGER is signed 64-bit: a wider value raises OverflowError (a 500) where it is bound.
SqliteInt = Annotated[int, Field(ge = -(2**63), le = 2**63 - 1)]

# llama.cpp spends 0xFFFFFFFF on its "draw one" sentinel, so a pin stops one below it.
MAX_SAMPLING_SEED = 2**32 - 2
SamplingSeed = Optional[
    Annotated[int, Field(ge = 0, le = MAX_SAMPLING_SEED), BeforeValidator(_reject_boolean)]
]


class ChatRagThreadSource(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    type: Literal["thread"]


class ChatRagKnowledgeBaseSource(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    type: Literal["kb"]
    kbId: str = Field(min_length = 1, max_length = 256)


class ChatThreadSettings(BaseModel):
    """The chat settings captured per thread; a thread storing none uses the global ones."""

    # Reject NaN: it would be stored as a token strict readers can't parse.
    model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)

    reasoningEnabled: Optional[bool] = None
    reasoningEffort: Optional[
        Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]
    ] = None
    toolsEnabled: Optional[bool] = None
    codeToolsEnabled: Optional[bool] = None
    imageToolsEnabled: Optional[bool] = None
    webFetchToolsEnabled: Optional[bool] = None
    deepResearchEnabled: Optional[bool] = None
    artifactsEnabled: Optional[bool] = None
    mcpEnabledForChat: Optional[bool] = None
    # "full" (Full access) is session-only and never persisted, per thread or globally.
    permissionMode: Optional[Literal["ask", "auto", "off"]] = None
    ragEnabled: Optional[bool] = None
    ragSource: Optional[
        Annotated[
            Union[ChatRagThreadSource, ChatRagKnowledgeBaseSource],
            Field(discriminator = "type"),
        ]
    ] = None
    ragMode: Optional[Literal["hybrid", "lexical", "dense"]] = None
    # Matches the ge/le the retrieval endpoint enforces on its own top_k.
    ragTopK: Optional[int] = Field(default = None, ge = 1, le = 50)
    ragAutoInject: Optional[Literal["auto", "on", "off"]] = None
    ragAutoInjectMinScore: Optional[float] = Field(default = None, ge = 0, le = 1)
    # The sampling params a chat runs with. Ranges match the sliders that set them.
    temperature: Optional[float] = Field(default = None, ge = 0, le = 2)
    topP: Optional[float] = Field(default = None, ge = 0, le = 1)
    # -1 disables top-k, matching ChatCompletionRequest and the default.yaml fallback.
    topK: Optional[int] = Field(default = None, ge = -1, le = 100)
    minP: Optional[float] = Field(default = None, ge = 0, le = 1)
    minPMode: Optional[Literal["server-default", "custom"]] = None
    repetitionPenalty: Optional[float] = Field(default = None, ge = 1, le = 2)
    presencePenalty: Optional[float] = Field(default = None, ge = 0, le = 2)
    seed: SamplingSeed = None
    # Not length-capped: truncating would silently change the chat's prompt.
    systemPrompt: Optional[str] = None
    systemVariables: Optional[str] = None


class ChatThread(BaseModel):
    id: str
    title: str = "New Chat"
    modelType: Literal["base", "lora", "model1", "model2"]
    modelId: str = ""
    modelGgufVariant: Optional[str] = None
    pairId: Optional[str] = None
    projectId: Optional[str] = None
    archived: bool = False
    createdAt: SqliteInt
    updatedAt: Optional[SqliteInt] = None
    openaiCodeExecContainerId: Optional[str] = None
    anthropicCodeExecContainerId: Optional[str] = None
    forkedFromThreadId: Optional[str] = None
    forkedFromMessageId: Optional[str] = None
    forkBoundaryMessageId: Optional[str] = None
    forkTitleBase: Optional[str] = None
    # Server-set: the scheduled task whose run made this chat.
    scheduledTaskId: Optional[str] = None
    # Server-set on rename, move or (un)archive.
    modifiedAt: Optional[int] = None
    settings: Optional[ChatThreadSettings] = None

    @field_serializer("settings")
    def _only_the_keys_the_snapshot_stored(
        self, settings: Optional[ChatThreadSettings]
    ) -> Optional[dict]:
        """Report a key the snapshot never held as absent rather than as null. `seed` is the one
        setting whose null is a value: it means this chat draws its own rather than taking the
        pinned one. Spelling every unset field as null, which the default dump does, would make a
        snapshot written before the field existed read as a chat that cleared it."""
        if settings is None:
            return None
        return settings.model_dump(exclude_unset = True)


def thread_from_row(row: dict) -> ChatThread:
    """Read a stored snapshot leniently so newer fields do not 500 the chat on open; the row stays untouched so an upgrade restores them."""
    settings = row.get("settings")
    if isinstance(settings, dict):
        row = {**row, "settings": readable_thread_settings(settings)}
    elif settings is not None:
        row = {**row, "settings": None}
    return ChatThread(**row)


def readable_thread_settings(settings: dict) -> Optional[dict]:
    """The part of a stored snapshot this build can validate, or None if none of it is."""
    known = {k: v for k, v in settings.items() if k in ChatThreadSettings.model_fields}
    # Drop all fields pydantic names per retry; version gaps add several at once.
    for _ in range(len(known) + 1):
        try:
            ChatThreadSettings.model_validate(known)
            return known
        except ValidationError as exc:
            bad = {str(e["loc"][0]) for e in exc.errors() if e.get("loc")}
            if not bad or not bad & set(known):
                return None
            known = {k: v for k, v in known.items() if k not in bad}
    return None


def _unreadable_thread_settings(stored: dict) -> dict:
    """Carry unvalidatable stored settings forward on write, so an older build cannot erase newer fields."""
    readable = readable_thread_settings(stored) or {}
    return {k: v for k, v in stored.items() if k not in readable}


def _settings_write_from_patch(patch: dict) -> Optional[dict]:
    """Returns the write for storage to execute atomically, so concurrent tabs cannot merge a stale row."""
    replace = "settings" in patch
    merge = "settingsPatch" in patch
    seq = patch.pop("settingsSeq", None)
    writer = patch.pop("settingsWriter", None)
    if not (replace or merge):
        return None
    incoming = patch.pop("settingsPatch", None)
    if merge:
        # A merge is the more specific instruction; sending both is a client bug.
        patch.pop("settings", None)
    else:
        incoming = patch.pop("settings")
    if incoming is None:
        # Only a clear wipes the whole column; a merge of nothing leaves the row alone.
        if replace and not merge:
            return {"clear": True, "seq": seq, "writer": writer}
        return None
    return {
        "merge": incoming if merge else None,
        "replace": None if merge else incoming,
        "seq": seq,
        "writer": writer,
        "keep_unreadable": _unreadable_thread_settings,
    }


class ChatThreadPatch(BaseModel):
    title: Optional[str] = None
    # Apply only while the row still holds this title, so a rename beats a background rewrite.
    expectedTitle: Optional[str] = None
    # Title regeneration must not move an old conversation up in Last modified.
    preserveTitleModifiedAt: bool = False
    # Apply only while this is still the opening user message, so a title from a deleted one is rejected.
    expectedOpeningMessageId: Optional[str] = None
    modelType: Optional[Literal["base", "lora", "model1", "model2"]] = None
    modelId: Optional[str] = None
    modelGgufVariant: Optional[str] = None
    pairId: Optional[str] = None
    projectId: Optional[str] = None
    archived: Optional[bool] = None
    createdAt: Optional[SqliteInt] = None
    updatedAt: Optional[SqliteInt] = None
    openaiCodeExecContainerId: Optional[str] = None
    anthropicCodeExecContainerId: Optional[str] = None
    # Replaces the whole snapshot, except for anything the client could not read.
    settings: Optional[ChatThreadSettings] = None
    # settingsPatch applies only the fields it names, for writers that have not read the row yet.
    settingsPatch: Optional[ChatThreadSettings] = None
    # Orders this writer's own snapshot writes; never compared across writers.
    settingsSeq: Optional[int] = None
    settingsWriter: Optional[str] = None


class ChatMessage(BaseModel):
    id: str
    threadId: str
    parentId: Optional[str] = None
    role: str
    content: Any = Field(default_factory = list)
    attachments: Optional[Any] = None
    metadata: Optional[dict[str, Any]] = None
    createdAt: SqliteInt


class ChatProject(BaseModel):
    id: str
    name: str
    instructions: str = ""
    rootPath: Optional[str] = None
    sandboxPath: Optional[str] = None
    # Read only: a saved record cannot set the folder.
    workingFolder: Optional[str] = None
    archived: bool = False
    createdAt: SqliteInt
    updatedAt: SqliteInt
    lastActivityAt: Optional[int] = None


class ChatProjectWorkingFolder(BaseModel):
    model_config = ConfigDict(extra = "forbid", populate_by_name = True)
    native_path_lease: str = Field(alias = "nativePathLease", min_length = 1)


class ChatProjectCreate(ChatProject):
    nativePathLease: Optional[str] = Field(default = None, min_length = 1)


class ChatAgentsMd(BaseModel):
    text: str = ""


class ChatProjectDeleted(ChatProject):
    """The deleted project, plus the member sandboxes that still hold files."""

    sandboxes_kept: list[str] = []


class ChatProjectPatch(BaseModel):
    name: Optional[str] = None
    instructions: Optional[str] = None
    archived: Optional[bool] = None
    createdAt: Optional[SqliteInt] = None
    updatedAt: Optional[SqliteInt] = None


# Advertised on the thread lists so the title repair skips fetching /openapi.json (older backends still need it).
_THREAD_PATCH_GUARD_FIELDS = ("expectedTitle", "expectedOpeningMessageId")
THREAD_PATCH_GUARDS = all(
    name in ChatThreadPatch.model_fields for name in _THREAD_PATCH_GUARD_FIELDS
)


class ChatThreadListResponse(BaseModel):
    threads: list[ChatThread]
    threadPatchGuards: bool = False


class ChatProjectListResponse(BaseModel):
    projects: list[ChatProject]


class ChatSidebarRowsRequest(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    archived: bool = False
    projectId: Optional[str] = None
    unfiledOnly: bool = False
    includeIds: Optional[list[str]] = None
    excludeIds: list[str] = Field(default_factory = list)
    sort: Literal["updated", "manual"] = "updated"
    manualOrder: Optional[list[str]] = None
    limit: int = Field(default = 20, ge = 1, le = SIDEBAR_ROWS_MAX_LIMIT)
    cursor: Optional[str] = Field(default = None, max_length = 4096)


class ChatSidebarRow(BaseModel):
    """One sidebar row, shaped as the frontend's SidebarItem."""

    id: str
    type: Literal["single", "compare"]
    threadIds: list[str]
    title: str
    createdAt: int
    updatedAt: int
    modifiedAt: Optional[int] = None
    modelIds: Optional[list[str]] = None
    isFork: Optional[bool] = None
    isScheduled: Optional[bool] = None
    threadTitles: Optional[list[str]] = None
    projectId: Optional[str] = None


class ChatSidebarRowsResponse(BaseModel):
    rows: list[ChatSidebarRow]
    nextCursor: Optional[str] = None
    hasMore: bool
    total: int
    threadPatchGuards: bool = False


class ChatSidebarThreadRowsResponse(BaseModel):
    rowIdByThreadId: dict[str, str]


class ChatMessageListResponse(BaseModel):
    messages: list[ChatMessage]


class ChatMessageSyncRequest(BaseModel):
    messages: list[ChatMessage]
    pruneMissing: bool = False
    deletedMessageIds: list[str] = Field(default_factory = list)


class ChatDeleteRequest(BaseModel):
    ids: list[str]
    # Tool-written files are kept by default since the user owns them; empty sandboxes always go.
    delete_files: bool = False


class ChatClearRequest(BaseModel):
    # Must exceed what a migrated install can hold: a 422 fails the whole Clear all.
    ids: list[str] = Field(default_factory = list, max_length = 200_000)
    operationId: Optional[str] = Field(default = None, min_length = 1, max_length = 128)


class ChatCountResponse(BaseModel):
    count: int


class ChatExportResponse(BaseModel):
    exportedAt: str
    version: int
    threadCount: int
    projects: list[ChatProject] = Field(default_factory = list)
    threads: list[ChatThread]
    messages: list[ChatMessage]


class ChatInferenceSettings(BaseModel):
    # Reject NaN/Infinity: json.loads accepts them and they read back as null.
    model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)

    temperature: Optional[float] = None
    topP: Optional[float] = None
    topK: Optional[float] = None
    minP: Optional[float] = None
    minPMode: Optional[Literal["server-default", "custom"]] = None
    repetitionPenalty: Optional[float] = None
    presencePenalty: Optional[float] = None
    maxSeqLength: Optional[float] = None
    maxTokens: Optional[float] = None
    systemPrompt: Optional[str] = None
    systemVariables: Optional[str] = None
    trustRemoteCode: Optional[bool] = None
    fastMode: Optional[bool] = None
    seed: SamplingSeed = None


class ChatPresetLoadConfig(BaseModel):
    model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)

    customContextLength: Optional[int] = Field(default = None, gt = 0)
    maxSeqLength: Optional[float] = None
    kvCacheDtype: Optional[str] = None
    mlxKvQuant: Optional[
        Literal["auto", "8", "6", "5", "4", "3", "2", "tq-4", "tq-3.5", "tq-3", "tq-2"]
    ] = None
    # Declared only because extra="forbid" would 400 the whole save for a client still sending it.
    mlxKvBits: Optional[Literal[8, 6, 5, 4, 3, 2]] = None
    speculativeType: Optional[str] = None
    specDraftNMax: Optional[int] = Field(default = None, ge = 1, le = 16)
    nParallel: Optional[int] = Field(default = None, ge = PARALLEL_MIN, le = PARALLEL_MAX)
    reasoningBudget: NotABoolean = Field(default = None, ge = -1, le = 2_147_483_647)
    reasoningBudgetMessage: Optional[str] = None
    # The normalizer always emits these keys and extra="forbid" would 400 the save.
    nBatch: NotABoolean = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
    nUbatch: NotABoolean = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
    # Same forbid trap as nBatch: normalizePresetLoadConfig always emits these keys.
    loadMode: Optional[Literal["auto", "none", "mmap", "mlock", "mmap+mlock", "dio"]] = None
    specDraftCacheDtype: Optional[str] = None
    ctxCheckpoints: NotABoolean = Field(default = None, ge = 0, le = CTX_CHECKPOINTS_MAX)
    cacheRam: NotABoolean = Field(default = None, ge = -1, le = CACHE_RAM_MAX_MIB)
    tensorParallel: Optional[bool] = None
    disableVision: Optional[bool] = None
    gpuMemoryMode: Optional[Literal["manual"]] = None
    gpuLayers: Optional[int] = None
    nCpuMoe: Optional[int] = Field(default = None, ge = 0)

    @field_validator("reasoningBudgetMessage")
    @classmethod
    def _validate_reasoning_budget_message(cls, value: Optional[str]) -> Optional[str]:
        return None if value is None else validate_reasoning_budget_message(value)


class ChatPreset(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    name: str
    params: ChatInferenceSettings
    loadConfig: Optional[ChatPresetLoadConfig] = None


class ChatResearchWebsitePolicy(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    # 253 is the maximum length of a DNS name.
    allowedDomains: list[Annotated[str, Field(max_length = 253)]] = Field(
        default_factory = list, max_length = 1_000
    )
    blockedDomains: list[Annotated[str, Field(max_length = 253)]] = Field(
        default_factory = list, max_length = 1_000
    )


class ChatResearchMcpSource(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    serverId: str = Field(min_length = 1, max_length = 200)
    tool: str = Field(min_length = 1, max_length = 500)


class ChatSettingsPayload(BaseModel):
    model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)

    # Sidebar IDs (incl. comparison pair IDs), not thread rows. Omitted = no change; [] unpins all.
    pinnedChatIds: list[
        Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]
    ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)
    inferenceParams: Optional[ChatInferenceSettings] = None
    # Deep-merged per key so patching one model keeps the others.
    inferenceParamsByModel: Optional[dict[str, ChatInferenceSettings]] = None
    # Per model id, keys of the entry above removed before this patch merges; never stored.
    forgetInferenceParamsByModel: Optional[
        dict[str, Annotated[list[str], Field(max_length = 64)]]
    ] = Field(default = None, max_length = 1_000)
    rememberParamsPerModel: Optional[bool] = None
    customPresets: Optional[list[ChatPreset]] = None
    activePreset: Optional[str] = None
    activePresetSource: Optional[Literal["builtin-default", "custom", "modified"]] = None
    autoTitle: Optional[bool] = None
    reasoningEffort: Optional[
        Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]
    ] = None
    preserveThinking: Optional[bool] = None
    collapseHtmlArtifacts: Optional[bool] = None
    allowArtifactNetworkAccess: Optional[bool] = None
    # Read by the web_search tool at call time, so it lives with the install, not one browser.
    searchImages: Optional[bool] = None
    autoHealToolCalls: Optional[bool] = None
    nudgeToolCalls: Optional[bool] = None
    deduplicateToolCalls: Optional[bool] = None
    maxToolCallsPerMessage: Optional[int] = Field(default = None, ge = 0)
    toolCallTimeout: Optional[int] = Field(default = None, ge = 1)

    # Install-wide, not per-browser, so other sessions read them back.
    reasoningEnabled: Optional[bool] = None
    toolsEnabled: Optional[bool] = None
    codeToolsEnabled: Optional[bool] = None
    imageToolsEnabled: Optional[bool] = None
    webFetchToolsEnabled: Optional[bool] = None
    deepResearchEnabled: Optional[bool] = None
    researchWebsitePolicy: Optional[ChatResearchWebsitePolicy] = None
    researchMcpSources: Optional[list[ChatResearchMcpSource]] = Field(default = None, max_length = 20)
    # Seconds per Deep Research model request; zero leaves the total wall clock off. Bounded
    # like the run route so a value it would reject cannot be persisted and replayed.
    researchModelTimeoutSeconds: Optional[int] = Field(default = None, ge = 0, le = 365 * 24 * 3600)
    artifactsEnabled: Optional[bool] = None
    showCanvasMenuItem: Optional[bool] = None
    mcpEnabledForChat: Optional[bool] = None
    confirmToolCalls: Optional[bool] = None
    # "full" (Full access) is session-only by design and never persisted.
    permissionMode: Optional[Literal["ask", "auto", "off"]] = None
    sandboxLevel: Optional[Literal["high", "low"]] = None
    ragSource: Optional[
        Annotated[
            Union[ChatRagThreadSource, ChatRagKnowledgeBaseSource],
            Field(discriminator = "type"),
        ]
    ] = None
    ragMode: Optional[Literal["hybrid", "lexical", "dense"]] = None
    # Matches the ge/le the retrieval endpoint enforces on its own top_k.
    ragTopK: Optional[int] = Field(default = None, ge = 1, le = 50)
    ragAutoInject: Optional[Literal["auto", "on", "off"]] = None
    ragAutoInjectMinScore: Optional[float] = Field(default = None, ge = 0, le = 1)
    ragOcrScanned: Optional[bool] = None
    ragCaptionFigures: Optional[bool] = None
    # Standing load preferences the model-load path reads outside the store.
    speculativeType: Optional[Literal["auto", "ngram", "off"]] = None
    gpuMemoryMode: Optional[Literal["auto", "manual"]] = None
    expandQuantizations: Optional[bool] = None
    showAllQuantizations: Optional[bool] = None
    fitOnDeviceOnly: Optional[bool] = None
    # Off omits context_overflow, so a full window errors. contextPolicy/headroom override UNSLOTH_CONTEXT_POLICY and ROLLING_COMPACTION_HEADROOM_RATIO.
    autoCompactEnabled: Optional[bool] = None
    # Off: a chat or Deep Research run stops once no tab follows it (state/unattended_runs.py).
    keepRunningWhenTabClosed: Optional[bool] = None
    contextPolicy: Optional[Literal["inherit", "checkpoint", "rolling"]] = None
    compactionHeadroomRatio: Optional[float] = Field(default = None, ge = 0.0, le = 0.9)

    @field_validator("pinnedChatIds")
    @classmethod
    def _unique_pinned_chat_ids(cls, value: list[str]) -> list[str]:
        if any(0xD800 <= ord(character) <= 0xDFFF for id in value for character in id):
            raise ValueError("pinnedChatIds must contain valid Unicode")
        if len(value) != len(set(value)):
            raise ValueError("pinnedChatIds must not contain duplicate IDs")
        return value

    @field_validator("researchModelTimeoutSeconds", "maxToolCallsPerMessage", mode = "before")
    @classmethod
    def _not_a_boolean(cls, value: Any) -> Any:
        # bool subclasses int, so False would persist as the 0 sentinel for every later run.
        if isinstance(value, bool):
            raise ValueError("Expected an integer, got a boolean.")
        return value

    @field_validator("researchModelTimeoutSeconds")
    @classmethod
    def _run_route_accepts_it(cls, value: Optional[int]) -> Optional[int]:
        # The run route accepts 0 or >= 10; a persisted 1..9 would 400 every run.
        if value is not None and 0 < value < 10:
            raise ValueError("researchModelTimeoutSeconds must be 0 (unlimited) or at least 10")
        return value


class ChatSettingsResponse(BaseModel):
    settings: dict[str, Any]


class ConditionalChatSettingsPayload(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    expected: ChatSettingsPayload
    expectedAbsent: list[str] = Field(default_factory = list)
    expectedAbsentPaths: list[list[str]] = Field(default_factory = list)
    patch: ChatSettingsPayload
    operationId: Optional[Annotated[str, Field(strict = True, min_length = 1, max_length = 128)]] = None
    # Explicit unpins can predate importing the corresponding legacy thread.
    unpinnedChatIds: list[
        Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]
    ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)

    # Queued pins this unpin superseded: acknowledged here so a delayed one is never applied.
    cancelledOperationIds: list[
        Annotated[str, Field(strict = True, min_length = 1, max_length = 128)]
    ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)

    @field_validator("unpinnedChatIds", "cancelledOperationIds")
    @classmethod
    def _unique_unpinned_ids(cls, value: list[str]) -> list[str]:
        return ChatSettingsPayload._unique_pinned_chat_ids(value)

    @field_validator("operationId")
    @classmethod
    def _valid_operation_id(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and any(0xD800 <= ord(character) <= 0xDFFF for character in value):
            raise ValueError("operationId must contain valid Unicode")
        return value

    @model_validator(mode = "after")
    def _operation_is_pin_only(self):
        if (
            self.operationId is not None
            or "unpinnedChatIds" in self.model_fields_set
            or "cancelledOperationIds" in self.model_fields_set
        ) and self.patch.model_fields_set != {"pinnedChatIds"}:
            raise ValueError("Pin operation metadata requires a pinnedChatIds-only patch")
        if set(self.unpinnedChatIds).intersection(self.patch.pinnedChatIds):
            raise ValueError("An unpinned chat ID cannot also be pinned in the same patch")
        return self

    @field_validator("expectedAbsent")
    @classmethod
    def _known_absent_fields(cls, value: list[str]) -> list[str]:
        unknown = set(value) - set(ChatSettingsPayload.model_fields)
        if unknown:
            unknown_names = ", ".join(sorted(unknown))
            raise ValueError(f"Unknown chat settings field(s): {unknown_names}")
        return value

    @field_validator("expectedAbsentPaths")
    @classmethod
    def _known_absent_paths(cls, value: list[list[str]]) -> list[list[str]]:
        for path in value:
            if len(path) < 2 or any(not segment for segment in path):
                raise ValueError("Expected-absent paths require at least two non-empty segments")
            if path[0] not in ChatSettingsPayload.model_fields:
                raise ValueError(f"Unknown chat settings field: {path[0]}")
        return value


class ConditionalChatSettingsResponse(ChatSettingsResponse):
    applied: bool


class ChatPinsResponse(BaseModel):
    pinnedIds: list[str] = Field(default_factory = list)


class ChatPinsMigrationRequest(BaseModel):
    model_config = ConfigDict(extra = "forbid")

    ids: list[
        Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]
    ] = Field(max_length = MAX_PINNED_CHAT_IDS)

    @field_validator("ids")
    @classmethod
    def _unique_ids(cls, value: list[str]) -> list[str]:
        return ChatSettingsPayload._unique_pinned_chat_ids(value)


class ChatMessagesBatchRequest(BaseModel):
    threadIds: list[str]
    view: Literal["full", "search"] = "full"


class ChatMessagesBatchResponse(BaseModel):
    messagesByThreadId: dict[str, list[ChatMessage]]


class ChatMessageCountsResponse(BaseModel):
    countsByThreadId: dict[str, int]


class ChatImportLedgerResponse(BaseModel):
    threadIds: list[str]


class ChatImportLedgerRecordRequest(BaseModel):
    # 10k cap bounds the request body; real users have << 1k threads.
    threadIds: list[str] = Field(default_factory = list, max_length = 10_000)


class ChatImportLedgerRecordResponse(BaseModel):
    # accepted counts deduped non-empty ids; inserted counts rows new under ON CONFLICT DO NOTHING.
    accepted: int
    inserted: int


# Two 409s mean opposite things (protected: stop resending; thread collision: surface failure); tell them apart by header, not detail; main.py must expose it.
CONFLICT_KIND_HEADER = "X-Unsloth-Conflict-Kind"


def _conflict_headers(exc: Exception) -> dict:
    kind = "protected" if isinstance(exc, ChatMessageProtectedError) else "thread-collision"
    return {CONFLICT_KIND_HEADER: kind}


@router.get("/threads", response_model = ChatThreadListResponse)
def list_threads(
    model_type: Optional[str] = Query(None),
    pair_id: Optional[str] = Query(None),
    project_id: Optional[str] = Query(None),
    include_archived: bool = Query(True),
    current_subject: str = Depends(get_current_subject),
):
    threads = list_chat_threads(
        model_type = model_type,
        pair_id = pair_id,
        project_id = project_id,
        include_archived = include_archived,
    )
    return ChatThreadListResponse(
        threads = [thread_from_row(t) for t in threads],
        threadPatchGuards = THREAD_PATCH_GUARDS,
    )


@router.post(
    "/sidebar/rows",
    response_model = ChatSidebarRowsResponse,
    response_model_exclude_unset = True,
)
def list_sidebar_rows(
    payload: ChatSidebarRowsRequest, current_subject: str = Depends(get_current_subject)
):
    """One page of sidebar rows, compare pairs grouped before the limit."""
    try:
        page = list_chat_sidebar_rows(
            archived = payload.archived,
            project_id = payload.projectId,
            unfiled_only = payload.unfiledOnly,
            include_ids = payload.includeIds,
            exclude_ids = payload.excludeIds,
            sort = payload.sort,
            manual_order = payload.manualOrder,
            limit = payload.limit,
            cursor = payload.cursor,
        )
    except SidebarCursorError as exc:
        raise HTTPException(status_code = 400, detail = str(exc)) from exc
    return ChatSidebarRowsResponse(**page, threadPatchGuards = THREAD_PATCH_GUARDS)


_SIDEBAR_THREAD_ROWS_MAX = 500


@router.get("/sidebar/thread-rows", response_model = ChatSidebarThreadRowsResponse)
def sidebar_thread_rows(
    thread_ids: list[str] = Query(default_factory = list),
    current_subject: str = Depends(get_current_subject),
):
    if len(thread_ids) > _SIDEBAR_THREAD_ROWS_MAX:
        raise HTTPException(
            status_code = 400,
            detail = f"At most {_SIDEBAR_THREAD_ROWS_MAX} thread ids per request",
        )
    return ChatSidebarThreadRowsResponse(rowIdByThreadId = lookup_chat_sidebar_row_ids(thread_ids))


def _missing_project_error(project_id: Optional[str]) -> HTTPException:
    """The row references a project that is gone, whether the check or the write noticed it."""
    return HTTPException(status_code = 404, detail = f"Project {project_id} not found")


def _missing_thread_error(thread_id: str) -> HTTPException:
    return HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")


def _deleted_thread_error(thread_id: str) -> HTTPException:
    return HTTPException(status_code = 410, detail = f"Thread {thread_id} was deleted")


@router.post("/threads", response_model = ChatThread)
def save_thread(payload: ChatThread, current_subject: str = Depends(get_current_subject)):
    if payload.projectId and get_chat_project(payload.projectId) is None:
        raise _missing_project_error(payload.projectId)
    try:
        return thread_from_row(upsert_chat_thread(payload.model_dump()))
    except ChatThreadDeletedError as exc:
        raise _deleted_thread_error(payload.id) from exc
    except sqlite3.IntegrityError as exc:
        # The project can be deleted before this insert (FK failure); report 404, not 500.
        if not payload.projectId:
            raise
        raise _missing_project_error(payload.projectId) from exc


@router.get("/threads/{thread_id}", response_model = ChatThread)
def get_thread(thread_id: str, current_subject: str = Depends(get_current_subject)):
    thread = get_chat_thread(thread_id)
    if thread is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    return thread_from_row(thread)


@router.patch("/threads/{thread_id}", response_model = ChatThread)
def patch_thread(
    thread_id: str,
    payload: ChatThreadPatch,
    current_subject: str = Depends(get_current_subject),
):
    patch = payload.model_dump(exclude_unset = True)
    expected_title = patch.pop("expectedTitle", None)
    preserve_title_modified_at = patch.pop("preserveTitleModifiedAt", False)
    expected_opening_message_id = patch.pop("expectedOpeningMessageId", None)
    for field in ("title", "modelType", "modelId", "archived", "createdAt", "updatedAt"):
        if field in patch and patch[field] is None:
            raise HTTPException(status_code = 400, detail = f"{field} cannot be null")
    if patch.get("projectId") and get_chat_project(patch["projectId"]) is None:
        raise _missing_project_error(patch["projectId"])
    settings_write = _settings_write_from_patch(patch)
    try:
        thread = update_chat_thread(
            thread_id,
            patch,
            expected_title = expected_title,
            preserve_title_modified_at = preserve_title_modified_at,
            expected_opening_message_id = expected_opening_message_id,
            settings_write = settings_write,
        )
    except sqlite3.IntegrityError as exc:
        # Same race as save_thread: the project can go away before this write lands.
        if not patch.get("projectId"):
            raise
        raise _missing_project_error(patch["projectId"]) from exc
    except ChatThreadPreconditionFailed:
        raise HTTPException(
            status_code = 409,
            detail = f"Thread {thread_id} changed since it was read",
        )
    if thread is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    return thread_from_row(thread)


def _cancel_deleted_research_runs(request: Request, run_ids: list[str]) -> None:
    """Signal workers for active runs captured by the deletion transaction."""
    supervisor = getattr(request.app.state, "research_supervisor", None)
    if supervisor is None and not policy.installation_has_managed_accounts():
        return
    for run_id in run_ids:
        try:
            cancel_account_run(request, run_id, supervisor_name = "research_supervisor")
        except Exception:  # noqa: BLE001 - cancellation is best-effort after commit
            logger.warning(
                "chat_history.cancel_deleted_research_failed run_id=%s",
                run_id,
                exc_info = True,
            )


def _cancel_active_research(request: Request, thread_ids: list[str]) -> None:
    """Compatibility path for callers that must cancel runs before deleting their rows."""
    if not thread_ids:
        return
    try:
        from storage import research_runs_db
    except Exception:  # noqa: BLE001 - research storage optional/unavailable
        return
    supervisor = getattr(request.app.state, "research_supervisor", None)
    for thread_id in thread_ids:
        try:
            active = research_runs_db.list_active(thread_id)
        except Exception:  # noqa: BLE001
            continue
        for run in active:
            try:
                status = research_runs_db.request_cancel(run["id"])
                if status == "cancelling" and (
                    supervisor is not None or policy.installation_has_managed_accounts()
                ):
                    cancel_account_run(request, run["id"], supervisor_name = "research_supervisor")
            except Exception:  # noqa: BLE001
                logger.warning(
                    "chat_history.cancel_active_research_failed run_id=%s",
                    run.get("id"),
                    exc_info = True,
                )


def _cancel_research_runs(request: Request, run_ids: list[str]) -> None:
    """Stop these research runs by id. Best effort, like every cleanup here."""
    if not run_ids:
        return
    try:
        from storage import research_runs_db
    except Exception:  # noqa: BLE001 - research storage optional/unavailable
        return
    supervisor = getattr(request.app.state, "research_supervisor", None)
    for run_id in run_ids:
        # Row is usually gone, so request_cancel raises; the supervisor is what stops the worker, so tell it first; status update is best effort.
        if supervisor is not None or policy.installation_has_managed_accounts():
            try:
                cancel_account_run(request, run_id, supervisor_name = "research_supervisor")
            except Exception:  # noqa: BLE001
                logger.warning("Could not signal research run %s", run_id, exc_info = True)
        try:
            research_runs_db.request_cancel(run_id)
        except Exception:  # noqa: BLE001
            pass


def _cancel_active_generations(thread_ids: list[str]) -> None:
    """Stop running generations of these threads so a late tool call cannot recreate the sandbox; best effort, since calls not yet in the executor escape."""
    if not thread_ids:
        return
    try:
        from state import active_generations
    except Exception:  # noqa: BLE001 - never block a delete on this
        return
    for thread_id in thread_ids:
        try:
            active_generations.cancel_thread(thread_id)
        except Exception:  # noqa: BLE001
            continue


def _cancel_chat_generation_runs(request: Request, run_ids: list[str]) -> None:
    """Cancel durable producers whose rows were captured before thread cascade."""
    if not run_ids:
        return
    for run_id in run_ids:
        try:
            cancel_account_run(request, run_id, supervisor_name = "chat_generation_supervisor")
        except Exception:  # noqa: BLE001 - deletion must still complete
            logger.warning("Could not signal chat generation run %s", run_id, exc_info = True)


@router.delete("/threads")
async def delete_threads(
    payload: ChatDeleteRequest,
    request: Request,
    current_subject: str = Depends(get_current_subject),
):
    from starlette.concurrency import run_in_threadpool

    # Before the rows go, so a thread id that comes back in the gap is cut here.
    cutoff = _archive_cutoff()
    deleted_research_run_ids, deleted_chat_run_ids = await run_in_threadpool(
        delete_chat_threads_with_active_runs,
        payload.ids,
    )
    _cancel_research_runs(request, deleted_research_run_ids)
    _cancel_chat_generation_runs(request, deleted_chat_run_ids)
    _cancel_active_generations(payload.ids)
    # Off-loop: the legacy move can be a cross-filesystem copy; folder is keyed by thread id, so unreachable once the thread is gone.
    removed, kept = await _remove_sandboxes(payload.ids, payload.delete_files)
    # Archives and uploads are keyed by thread id; drop them so each deleted chat does not leak a scope.
    await run_in_threadpool(_remove_thread_rag_data, payload.ids, cutoff = cutoff)
    await run_in_threadpool(chat_originals.sweep)
    return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}


def _archive_cutoff() -> str:
    """The instant a delete was accepted, as an ISO-8601 UTC string. See below."""
    from datetime import datetime, timezone
    return datetime.now(timezone.utc).isoformat()


def _remove_thread_rag_data(thread_ids, *, cutoff: "str | None" = None) -> None:
    """Drop each deleted thread's archived turns and uploaded documents. Never raises."""
    try:
        from core.rag import conversation_archive
    except Exception:
        return
    for thread_id in thread_ids or []:
        # Cut at delete time, not recreation: skipping the scope when the id was recreated left the deleted chat recallable.
        recreated = get_chat_thread(str(thread_id)) is not None
        if recreated and not cutoff:
            continue
        created_before = cutoff if recreated else None
        try:
            conversation_archive.delete_for_thread(str(thread_id), created_before = created_before)
        except Exception:
            logger.warning("Could not remove the conversation archive for %s", thread_id)
        try:
            conversation_archive.delete_thread_documents(
                str(thread_id), created_before = created_before
            )
        except Exception:
            logger.warning("Could not remove the uploaded documents for %s", thread_id)


def _fork_document_cutoff(
    source_thread_id: str, branch_message_id: Optional[str], client_now_ms: int
) -> Optional[str]:
    """Uploads made after the fork point stay behind (None at the tip); the cutoff is shifted by the
    browser-to-server clock skew the fork request shows."""
    import time
    from datetime import datetime, timezone

    if not branch_message_id:
        return None
    next_at = next_message_created_at(source_thread_id, branch_message_id)
    if next_at is None:
        return None
    skew_ms = int(time.time() * 1000) - client_now_ms
    return datetime.fromtimestamp((next_at + skew_ms) / 1000, timezone.utc).isoformat()


def _copy_thread_rag_documents(
    source_thread_id: str,
    thread_id: str,
    *,
    created_before: Optional[str] = None,
) -> bool:
    """Copy the source's uploads into the fork; False if some were left behind, so warn."""
    try:
        from core.rag import conversation_archive
        from storage import rag_db

        if not rag_db.rag_available():
            return not conversation_archive.thread_has_documents(source_thread_id)
        document_ids, missed = conversation_archive.copy_thread_documents(
            source_thread_id, thread_id, created_before = created_before
        )
        if get_chat_thread(thread_id) is None:
            conversation_archive.delete_thread_documents(thread_id)
            return False
        if not document_ids and get_chat_thread(source_thread_id) is None:
            return False
        remap_chat_thread_document_ids(thread_id, document_ids)
        return not missed
    except Exception:
        logger.warning(
            "Could not copy the uploaded documents of %s to %s",
            source_thread_id,
            thread_id,
            exc_info = True,
        )
        return False


async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[str]]":
    """Remove sandboxes off the event loop, never raising; returns count and ids still holding files."""
    from starlette.concurrency import run_in_threadpool

    def _remove() -> "tuple[int, list[str]]":
        from core.inference.tools import (
            record_kept_sandbox,
            remove_session_sandbox,
            sandbox_removal_deferred,
            session_sandbox_has_files,
        )
        from storage.studio_db import sandbox_is_referenced_elsewhere

        removed, kept = 0, []
        for thread_id in thread_ids:
            # Another tab may have recreated this id; its folder is not ours to take.
            if get_chat_thread(thread_id) is not None:
                continue
            _drop_file_history(thread_id)
            # A fork clones message cards, so the source's files still show in a kept chat.
            if delete_files and sandbox_is_referenced_elsewhere(thread_id):
                if session_sandbox_has_files(thread_id):
                    kept.append(thread_id)
                    # Recorded as kept so the collection below takes it once the last fork goes; the chat is gone.
                    record_kept_sandbox(thread_id)
                continue
            # Recheck: the reference scan is slow and the chat can be recreated meanwhile.
            if get_chat_thread(thread_id) is not None:
                continue
            if remove_session_sandbox(thread_id, delete_files = delete_files):
                removed += 1
            # A deferred removal is reported as kept: the running call can still write a file.
            elif sandbox_removal_deferred(thread_id) or session_sandbox_has_files(thread_id):
                kept.append(thread_id)
        return removed, kept

    try:
        result = await run_in_threadpool(_remove)
    except Exception:
        logger.warning("chat_history.sandbox_cleanup_failed", exc_info = True)
        return 0, []
    # Only pending records are collected; the last chat on a doomed workspace takes the plain path.
    from core.inference.tools import collect_orphaned_project_workspaces

    await run_in_threadpool(collect_orphaned_project_workspaces)
    return result


@router.get("/attachments")
def list_attachments(
    limit: Annotated[int, Query(ge = 1, le = 100)] = 50,
    offset: Annotated[int, Query(ge = 0, le = 2**63 - 1)] = 0,
    current_subject: str = Depends(get_current_subject),
) -> dict:
    """One bounded page of chat uploads for the settings Data tab."""
    attachments, next_offset = list_chat_attachments_page(limit = limit, offset = offset)
    return {"attachments": attachments, "nextOffset": next_offset}


def _decode_attachment_base64(payload: str) -> bytes:
    """Strict base64 decode; validate=False would silently drop bad characters and serve corrupt
    bytes, so raise 422 instead."""
    import base64

    # An imported file part can keep its data URL; base64 has no ':', so this never cuts a payload.
    if payload[:5].lower() == "data:" and "," in payload:
        payload = payload.split(",", 1)[1]
    normalized = "".join(payload.split())
    altchars = b"-_" if ("-" in normalized or "_" in normalized) else None
    normalized += "=" * (-len(normalized) % 4)
    try:
        return base64.b64decode(normalized, altchars = altchars, validate = True)
    except Exception as exc:  # noqa: BLE001 - corrupt stored payload
        raise HTTPException(status_code = 422, detail = "Attachment data is corrupt") from exc


# A long paste is attached as text under its own tag (attachmentContentText in pasted-text.ts).
_ATTACHMENT_TAG_RE = re.compile(r"<(attachment|pasted_text) name=[^\n]*>\n(.*)\n</\1>", re.DOTALL)
_ATTACHMENT_LABEL_RE = re.compile(r"\[(?:PDF|DOCX|HTML|ODS|ODT|XLSX|PPTX|RTF): [^\n]*\]\n")


def _attachment_body_text(text: str) -> str:
    """An attachment's text without its chat wrapper, as the file itself reads."""
    tagged = _ATTACHMENT_TAG_RE.fullmatch(text)
    if tagged:
        return tagged.group(2)
    labelled = _ATTACHMENT_LABEL_RE.match(text)
    return text[labelled.end() :] if labelled else text


_AUDIO_FORMAT_MEDIA_TYPES = {
    "mp3": "audio/mpeg",
    "wav": "audio/wav",
    "ogg": "audio/ogg",
    "flac": "audio/flac",
}


def _safe_image_media_type(media_type: str) -> str:
    """Only plain raster types are echoed; imported text/html or SVG would run with the app origin."""
    lowered = media_type.strip().lower()
    if lowered.startswith("image/") and lowered != "image/svg+xml":
        return lowered
    return "application/octet-stream"


@router.post("/attachment-originals")
def upload_attachment_original(
    file: UploadFile = File(...), current_subject: str = Depends(get_current_subject)
) -> dict:
    """Store an attachment's original file; the message records the returned hash. Any name is
    taken, since the python tool reads every text and code format. Sync, so disk writes run in
    the threadpool."""
    try:
        sha256, size = chat_originals.save(
            iter(lambda: file.file.read(1024 * 1024), b""),
            chat_originals.max_bytes(file.filename or ""),
        )
    except chat_originals.TooLarge:
        raise HTTPException(status_code = 413, detail = f"{file.filename} is too large")
    chat_originals.sweep()
    return {"sha256": sha256, "sizeBytes": size}


@router.get("/attachments/{message_id}/{attachment_id}/file")
def get_attachment_file(
    message_id: str,
    attachment_id: str,
    current_subject: str = Depends(get_current_subject),
):
    """Serve one attachment's stored content: a document's original file, image, audio or video
    bytes, or extracted text."""
    import urllib.parse

    from fastapi.responses import FileResponse, Response

    attachment = get_chat_attachment(message_id, attachment_id)
    if attachment is None:
        raise HTTPException(status_code = 404, detail = "Attachment not found")

    original = chat_originals.path_for(attachment)
    if original is not None:
        return FileResponse(
            original,
            media_type = "application/octet-stream",
            headers = {"X-Content-Type-Options": "nosniff"},
        )

    attachment_content_type = attachment.get("contentType")
    texts: list[str] = []
    for part in attachment.get("content") or []:
        if not isinstance(part, dict):
            continue
        image = part.get("image")
        if isinstance(image, str) and image[:5].lower() == "data:":
            header, _, payload = image.partition(",")
            media_type = _safe_image_media_type(
                header[5:].split(";", 1)[0] or "application/octet-stream"
            )
            if "base64" not in header.lower():
                # RFC 2397 non-base64 form stores percent-encoded bytes.
                data = urllib.parse.unquote_to_bytes(payload)
                return Response(content = data, media_type = media_type)
            data = _decode_attachment_base64(payload)
            return Response(content = data, media_type = media_type)
        # Adapter stores {data, format}; compare chats store a bare base64 string.
        audio = part.get("audio")
        if isinstance(audio, dict) or (isinstance(audio, str) and audio):
            if isinstance(audio, dict):
                payload = audio.get("data")
                audio_format = audio.get("format")
            else:
                payload = audio.rsplit(",", 1)[-1]
                audio_format = None
            if isinstance(payload, str) and payload:
                data = _decode_attachment_base64(payload)
                media_type = (
                    attachment_content_type
                    if isinstance(attachment_content_type, str)
                    and attachment_content_type.startswith("audio/")
                    else _AUDIO_FORMAT_MEDIA_TYPES.get(
                        str(audio_format or "").lower(), "application/octet-stream"
                    )
                )
                return Response(content = data, media_type = media_type)
        file_data = part.get("data")
        mime_type = str(part.get("mimeType") or attachment_content_type or "")
        mime_type = mime_type.split(";", 1)[0].strip().lower()
        if (
            part.get("type") == "file"
            and isinstance(file_data, str)
            and file_data
            and re.fullmatch(r"video/[a-z0-9.+-]+", mime_type)
        ):
            return Response(content = _decode_attachment_base64(file_data), media_type = mime_type)
        text = part.get("text")
        if isinstance(text, str) and text:
            texts.append(_attachment_body_text(text))
    if texts:
        return Response(content = "\n".join(texts), media_type = "text/plain; charset=utf-8")
    raise HTTPException(status_code = 404, detail = "Attachment has no stored content")


@router.delete("/attachments/{message_id}/{attachment_id}")
def delete_attachment(
    message_id: str,
    attachment_id: str,
    current_subject: str = Depends(get_current_subject),
) -> dict:
    """Remove one attachment from its chat message."""
    try:
        deleted = delete_chat_attachment(message_id, attachment_id)
    except ChatMessageProtectedError as exc:
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "chat_history.delete_attachment_conflict",
            log = logger,
            headers = _conflict_headers(exc),
        ) from exc
    if not deleted:
        raise HTTPException(status_code = 404, detail = "Attachment not found")
    chat_originals.sweep()
    return {"ok": True}


@router.get("/projects", response_model = ChatProjectListResponse)
def list_projects(
    include_archived: bool = Query(False), current_subject: str = Depends(get_current_subject)
):
    # Backfill only projects without a recorded root; the rest are ensured where their files are used.
    return ChatProjectListResponse(
        projects = [
            ChatProject(
                **{
                    **(
                        project
                        if project.get("rootPath")
                        else (ensure_chat_project_workspace(project["id"]) or project)
                    ),
                    "lastActivityAt": project["lastActivityAt"],
                }
            )
            for project in list_chat_projects(include_archived = include_archived)
        ]
    )


@router.post("/projects", response_model = ChatProject)
def save_project(payload: ChatProjectCreate, current_subject: str = Depends(get_current_subject)):
    lease = getattr(payload, "nativePathLease", None)
    if lease is not None and not is_owner_context():
        raise HTTPException(status_code = 403, detail = "Only the owner can use a local folder.")
    try:
        project = payload.model_dump(exclude = {"nativePathLease"})
        if lease is None:
            return ChatProject(**upsert_chat_project(project))
        working_folder = _resolve_project_working_folder(lease)
        return ChatProject(**upsert_chat_project(project, working_folder = working_folder))
    except HTTPException:
        raise
    except ProjectWorkingFolderConflictError as exc:
        raise HTTPException(status_code = 409, detail = str(exc)) from exc
    except ProjectWorkspaceError as exc:
        # Only this project path error: the same upsert also opens the database elsewhere.
        raise log_and_http_error(
            exc,
            500,
            f"Could not create the project folder {exc.path}. Check that the "
            "folder is writable, or set UNSLOTH_STUDIO_PROJECTS_HOME to another "
            "location.",
            event = "chat_history.create_project_workspace_failed",
            log = logger,
        ) from exc
    except Exception as exc:
        if lease is None:
            raise
        # The grant is spent: HTTPException keeps CORS so the webview does not resend it (#13131).
        raise log_and_http_error(
            exc,
            500,
            "Could not create the project.",
            event = "chat_history.create_project_with_folder_failed",
            log = logger,
        ) from exc


@router.get("/projects/{project_id}", response_model = ChatProject)
def get_project(project_id: str, current_subject: str = Depends(get_current_subject)):
    project = ensure_chat_project_workspace(project_id)
    if project is None:
        raise HTTPException(
            status_code = 404,
            detail = f"Project {project_id} not found",
        )
    return ChatProject(**project)


@router.get("/agents-md", response_model = ChatAgentsMd)
def get_agents_md(
    project_id: Optional[str] = Query(None), current_subject: str = Depends(get_current_subject)
):
    from core.agents_md import agents_md_text
    project = get_chat_project(project_id) if project_id else None
    return ChatAgentsMd(text = agents_md_text(project))


@router.patch("/projects/{project_id}", response_model = ChatProject)
def patch_project(
    project_id: str,
    payload: ChatProjectPatch,
    current_subject: str = Depends(get_current_subject),
):
    patch = payload.model_dump(exclude_unset = True)
    for field in ("name", "archived", "createdAt", "updatedAt"):
        if field in patch and patch[field] is None:
            raise HTTPException(status_code = 400, detail = f"{field} cannot be null")
    project = update_chat_project(project_id, patch)
    if project is not None:
        project = ensure_chat_project_workspace(project_id)
    if project is None:
        raise HTTPException(
            status_code = 404,
            detail = f"Project {project_id} not found",
        )
    return ChatProject(**project)


def _resolve_project_working_folder(lease: str) -> tuple[str, tuple[int, int]]:
    """Studio's own roots are reserved: they hold every account's data."""
    from core.inference.tools import shared_sandbox_root
    from core.rag import folder_sync
    from utils.native_path_leases import NativePathLeaseError, verify_native_path_lease
    from utils.paths.path_utils import is_path_within
    from utils.paths.storage_roots import (
        shared_project_workspaces_root,
        shared_tmp_root,
        studio_root,
    )

    try:
        grant = verify_native_path_lease(
            lease,
            operation = "link-documents",
            expected_kind = "document-folder",
            expected_path_type = "directory",
        )
        path = folder_sync.validate_folder_path(str(grant.canonical_path))
    except (NativePathLeaseError, ValueError) as exc:
        raise HTTPException(status_code = 400, detail = str(exc)) from exc
    for reserved in (
        studio_root(),
        shared_project_workspaces_root(),
        shared_sandbox_root(),
        shared_tmp_root(),
    ):
        reserved = os.path.realpath(str(reserved))
        if is_path_within(path, reserved, allow_root = True) or is_path_within(
            reserved, path, allow_root = True
        ):
            raise HTTPException(
                status_code = 400,
                detail = "Unsloth's own folders cannot be used as a project folder.",
            )
    if not os.access(path, os.W_OK):
        raise HTTPException(status_code = 400, detail = "The folder is not writable.")
    st = os.stat(path)
    return path, (st.st_dev, st.st_ino)


@router.put("/projects/{project_id}/working-folder", response_model = ChatProject)
def set_project_working_folder(
    project_id: str,
    payload: ChatProjectWorkingFolder,
    current_subject: str = Depends(get_current_subject),
):
    if not is_owner_context():
        raise HTTPException(status_code = 403, detail = "Only the owner can use a local folder.")
    if get_chat_project(project_id) is None:
        raise HTTPException(status_code = 404, detail = f"Project {project_id} not found")
    try:
        path, identity = _resolve_project_working_folder(payload.native_path_lease)
        project = set_chat_project_working_folder(project_id, path, identity)
    except HTTPException:
        raise
    except Exception as exc:
        # HTTPException keeps CORS so the webview does not resend a spent grant (#13131).
        raise log_and_http_error(
            exc,
            500,
            "Could not use the folder.",
            event = "chat_history.project_working_folder_failed",
            log = logger,
        ) from exc
    if project is None:
        raise HTTPException(status_code = 404, detail = f"Project {project_id} not found")
    return ChatProject(**project)


@router.delete("/projects/{project_id}/working-folder", response_model = ChatProject)
def clear_project_working_folder(
    project_id: str, current_subject: str = Depends(get_current_subject)
):
    # The user's folder is never touched.
    project = set_chat_project_working_folder(project_id, None)
    if project is None:
        raise HTTPException(status_code = 404, detail = f"Project {project_id} not found")
    return ChatProject(**project)


def _delete_project_rag_sources(project_id: str) -> None:
    """Retire an ownerless project scope and reap it when RAG is available."""
    from storage import rag_db
    from core.rag import folder_sync, store as rag_store

    scope = rag_store.project_scope(project_id)
    # Project ids are reusable; retiring a recreated scope would disable its RAG for good.
    with folder_sync.scope_lock(scope):
        owned = folder_sync.linked_folder_ids(scope)
        if get_chat_project(project_id) is not None:
            return
        # Tombstone first, rows after a recheck: tombstone blocks new links and only unretire_scope can undo it; retired rows block create_folder for good.
        folder_sync.retire_scope(scope, owned, rows = False)
        if get_chat_project(project_id) is not None:
            folder_sync.unretire_scope(scope)
            return
        folder_sync.retire_scope(scope, owned)
        # The purge takes the whole scope, so retirement only helps if the purge is skipped too.
        if rag_db.rag_available():
            folder_sync.delete_retired_scope(scope)


@router.delete("/projects/{project_id}", response_model = ChatProjectDeleted)
async def delete_project(
    project_id: str,
    request: Request,
    delete_files: bool = Query(False),
    current_subject: str = Depends(get_current_subject),
):
    from starlette.concurrency import run_in_threadpool

    # Rows first, files last: a member chat tool may still run there, and a vanished cwd kills the call or strands what it writes.
    cutoff = _archive_cutoff()
    try:
        project = await run_in_threadpool(
            lambda: delete_chat_project(project_id, delete_files = False)
        )
    except Exception:
        try:
            if await run_in_threadpool(get_chat_project, project_id) is None:
                await run_in_threadpool(_delete_project_rag_sources, project_id)
        except Exception:  # noqa: BLE001 - preserve the original deletion error
            logger.warning(
                "failed to delete RAG sources for committed project %s", project_id, exc_info = True
            )
        raise
    if project is None:
        raise HTTPException(
            status_code = 404,
            detail = f"Project {project_id} not found",
        )
    # Transaction is authoritative on membership and captured worker ids before cascades; signal them before slow RAG or workspace cleanup.
    member_ids = list(project.get("memberIds") or [])
    _cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))
    _cancel_chat_generation_runs(
        request,
        list(project.get("activeChatGenerationRunIds") or []),
    )
    _cancel_active_generations(member_ids)
    # before any workspace work: the row is already gone.
    try:
        await run_in_threadpool(_delete_project_rag_sources, project_id)
    except Exception:  # noqa: BLE001 - source cleanup must not block project deletion
        logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)
    # The project's chats go with it, so their archives and documents have to as well.
    await run_in_threadpool(_remove_thread_rag_data, member_ids, cutoff = cutoff)
    await run_in_threadpool(chat_originals.sweep)
    if project.get("sandboxPath"):
        from core.inference.tools import (
            finish_workspace_delete_when_idle,
            forget_orphaned_project,
            forget_orphaned_project_if_gone,
            live_project_owns,
            project_session_id,
            record_orphaned_project,
            wait_for_sessions_idle,
        )
        from storage.studio_db import (
            delete_project_workspace,
            sandbox_is_referenced_elsewhere,
        )

        # Cancel only asks; a running call still uses the cwd. Shared id first (`project-<id>`).
        shared = project_session_id(project_id)
        idle = (
            await run_in_threadpool(wait_for_sessions_idle, [shared, *member_ids])
            if delete_files
            else True
        )
        # A fork of the project still shows cards for the shared workspace and is not deleted here.
        referenced = await run_in_threadpool(sandbox_is_referenced_elsewhere, shared, None)
        # A project with this id may have been recreated and be writing there now.
        recreated = await run_in_threadpool(get_chat_project, project_id) is not None
        if not delete_files:
            # Files stay; the custom-path row is gone and forks' cards still name the session, so record it.
            await run_in_threadpool(
                record_orphaned_project,
                project_id,
                project["sandboxPath"],
                False,
                project.get("rootPath"),
            )
        elif recreated:
            logger.warning(
                "Kept project workspace %s: a project was created with that id",
                project_id,
            )
        elif not idle:
            # Never remove a live tool call's cwd; the record lets a later delete collect it.
            logger.warning(
                "Kept project workspace %s: a tool call was still running in it",
                project_id,
            )
        elif referenced:
            logger.info(
                "Kept project workspace %s: a surviving chat still shows its files",
                project_id,
            )
        if delete_files and idle and not referenced and not recreated:
            # Record first: the delete can decline a path or stop at a locked file, and the row that knew this workspace location is already gone.
            await run_in_threadpool(
                record_orphaned_project,
                project_id,
                project["sandboxPath"],
                True,
                project.get("rootPath"),
            )
            # Recheck: a project created during the await resolves to this same path.
            if await run_in_threadpool(get_chat_project, project_id) is not None:
                logger.warning(
                    "Kept project workspace %s: a project was created with that id",
                    project_id,
                )
                # Only if the new row covers these folders; a remade project may live elsewhere and strand the old.
                if await run_in_threadpool(
                    live_project_owns,
                    project_id,
                    project["sandboxPath"],
                    project.get("rootPath"),
                ):
                    await run_in_threadpool(forget_orphaned_project, project_id)
            else:
                await run_in_threadpool(delete_project_workspace, project)
                await run_in_threadpool(
                    forget_orphaned_project_if_gone,
                    project_id,
                    project["sandboxPath"],
                    project.get("rootPath"),
                )
        elif delete_files and not recreated:
            # Recorded for later collection, root included, since its row is gone; never for a live id.
            await run_in_threadpool(
                record_orphaned_project,
                project_id,
                project["sandboxPath"],
                True,
                project.get("rootPath"),
            )
            if not idle:
                # Nothing else returns to it; otherwise collection waits on a later delete that may never happen.
                finish_workspace_delete_when_idle(project_id)
    # Member chats keep pre-join sandboxes; deleting the project removes the only records of them.
    _, sandboxes_kept = await _remove_sandboxes(member_ids, delete_files)
    # Surviving folders are unreachable now, so the response lists them for a one-time delete offer.
    return ChatProjectDeleted(**project, sandboxes_kept = sandboxes_kept)


@router.get("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)
def get_thread_messages(thread_id: str, current_subject: str = Depends(get_current_subject)):
    if get_chat_thread(thread_id) is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    return ChatMessageListResponse(
        messages = [ChatMessage(**m) for m in list_chat_messages(thread_id)]
    )


# Part types extractText (frontend use-chat-search-index.ts) reads; a frontend test guards drift.
_SEARCH_PART_TYPES = frozenset(("text", "reasoning", "thinking", "tool-call", "source"))
_PASTED_TEXT_PREFIX = "<pasted_text name="


def _search_view_attachment_part(part: Any) -> bool:
    """Keep what attachmentsPastedText reads; malformed parts stay so the index fails as before."""
    if not isinstance(part, dict):
        return True
    if part.get("type") != "text" or "text" not in part:
        return False
    text = part["text"]
    return not isinstance(text, str) or text.startswith(_PASTED_TEXT_PREFIX)


# Mirrors searchableText: tool output keeps only text it would index, so images and widget seeds stay home.
# ASCII: JavaScript's /i never folds a non-ASCII letter such as "ı" onto an ASCII one.
_SEARCH_SKIPPED_KEY = re.compile(r"b64|base64|^(?:images?|audio|video)\Z", re.IGNORECASE | re.ASCII)
_MCP_IMAGES_MARKER = "\n__MCP_IMAGES__:"
_IMAGES_MARKER = "\n__IMAGES__:"


def _reject_json_constant(name: str) -> Any:
    raise ValueError(name)


def _split_mcp_images(text: str) -> str:
    """splitMcpImages: only a valid image envelope after the last marker is cut."""
    at = text.rfind(_MCP_IMAGES_MARKER)
    if at == -1:
        return text
    try:
        # parse_int: JSON.parse takes integers past Python's digit limit.
        images = json.loads(
            text[at + len(_MCP_IMAGES_MARKER) :],
            parse_constant = _reject_json_constant,
            parse_int = float,
        )
    except ValueError:
        return text
    valid = (
        isinstance(images, list)
        and len(images) > 0
        and all(
            isinstance(image, dict)
            and isinstance(image.get("data"), str)
            and isinstance(image.get("mimeType"), str)
            for image in images
        )
    )
    return text[:at] if valid else text


# JavaScript's \s, which differs from Python's (no \x1c-\x1f or \x85, adds \ufeff).
_JS_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
_DATA_URL = re.compile(f"data:[^;,{_JS_SPACE}]+;base64,[A-Za-z0-9+/=]+")


def _searchable_string(text: str) -> str:
    """searchableText on a string, minus stripBase64Runs, which is far slower in Python."""
    text = _split_mcp_images(text)
    at = text.find(_IMAGES_MARKER)
    if at != -1:
        text = text[:at]
    return _DATA_URL.sub(" ", text)


def _search_view_string(text: str) -> str:
    try:
        cut = _searchable_string(text)
        # Sent only when the browser would read it back unchanged, else the original.
        stable = _searchable_string(cut) == cut
    except RecursionError:
        # JSON.parse may still read nesting this deep, so leave the string to the browser.
        return text
    return cut if stable else text


def _search_view_value(
    value: Any,
    depth: int = 0,
    tool_name: Any = None,
) -> Any:
    if isinstance(value, str):
        return _search_view_string(value)
    if value is None or depth > 4:
        return None
    if isinstance(value, list):
        return [_search_view_value(v, depth + 1) for v in value]
    if isinstance(value, dict):
        ui = value.get("ui")
        if (
            depth == 0
            and isinstance(tool_name, str)
            and tool_name.startswith("mcp__")
            and isinstance(value.get("text"), str)
            and isinstance(ui, dict)
            and isinstance(ui.get("resourceUri"), str)
        ):
            return {"text": _search_view_string(value["text"])}
        return {
            k: _search_view_value(v, depth + 1)
            for k, v in value.items()
            if not _SEARCH_SKIPPED_KEY.search(k)
        }
    return value


def _search_view_tool_call(part: dict) -> dict:
    out = {key: part[key] for key in ("type", "toolName", "provenance") if key in part}
    if isinstance(part.get("argsText"), str):
        out["argsText"] = _search_view_string(part["argsText"])
    elif "args" in part:
        out["args"] = _search_view_value(part["args"])
    if "result" in part:
        out["result"] = _search_view_value(part["result"], 0, part.get("toolName"))
    return out


def _search_view_message(message: dict) -> dict:
    """What the search index reads of a message: no metadata, media or document bodies."""
    out = {
        key: message[key]
        for key in ("id", "threadId", "parentId", "role", "createdAt")
        if key in message
    }
    # Absent stays absent, so ChatMessage fills [] exactly as it does for the full view.
    if "content" in message:
        content = message["content"]
        if isinstance(content, list):
            content = [
                _search_view_tool_call(part) if part["type"] == "tool-call" else part
                for part in content
                if isinstance(part, dict)
                and isinstance(part.get("type"), str)
                and part["type"] in _SEARCH_PART_TYPES
            ]
        out["content"] = content
    attachments = message.get("attachments")
    if isinstance(attachments, list):
        kept = []
        for attachment in attachments:
            if not isinstance(attachment, dict) or not isinstance(attachment.get("content"), list):
                kept.append(attachment)
                continue
            parts = [part for part in attachment["content"] if _search_view_attachment_part(part)]
            if parts:
                kept.append({"content": parts})
        attachments = kept
    if attachments is not None:
        out["attachments"] = attachments
    return out


@router.post("/messages:batch", response_model = ChatMessagesBatchResponse)
def batch_thread_messages(
    payload: ChatMessagesBatchRequest, current_subject: str = Depends(get_current_subject)
):
    """One round-trip per sidebar/search rebuild instead of N. Unknown thread ids return empty lists."""
    by_thread: dict[str, list[ChatMessage]] = {tid: [] for tid in payload.threadIds}
    search_view = payload.view == "search"
    for m in list_chat_messages_for_threads(payload.threadIds, include_metadata = not search_view):
        tid = m["threadId"]
        if tid in by_thread:
            by_thread[tid].append(ChatMessage(**(_search_view_message(m) if search_view else m)))
    return ChatMessagesBatchResponse(messagesByThreadId = by_thread)


@router.post("/messages:counts", response_model = ChatMessageCountsResponse)
def count_thread_messages(
    payload: ChatMessagesBatchRequest, current_subject: str = Depends(get_current_subject)
):
    """Per-thread message counts, without message bodies."""
    return ChatMessageCountsResponse(
        countsByThreadId = count_chat_messages_for_threads(payload.threadIds)
    )


@router.get("/threads/{thread_id}/messages/{message_id}", response_model = ChatMessage)
def get_thread_message(
    thread_id: str,
    message_id: str,
    current_subject: str = Depends(get_current_subject),
):
    if get_chat_thread(thread_id) is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    message = get_chat_message(thread_id, message_id)
    if message is None:
        raise HTTPException(status_code = 404, detail = f"Message {message_id} not found")
    return ChatMessage(**message)


@router.put("/threads/{thread_id}/messages/{message_id}", response_model = ChatMessage)
def save_thread_message(
    thread_id: str,
    message_id: str,
    payload: ChatMessage,
    allow_generation_edit: Annotated[bool, Query(alias = "allowGenerationEdit")] = False,
    current_subject: str = Depends(get_current_subject),
):
    if thread_id != payload.threadId or message_id != payload.id:
        raise HTTPException(status_code = 400, detail = "Message id mismatch")
    if get_chat_thread(thread_id) is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    try:
        saved = upsert_chat_message(
            payload.model_dump(), allow_generation_edit = allow_generation_edit
        )
    except sqlite3.IntegrityError as exc:
        if get_chat_thread(thread_id) is None:
            raise _missing_thread_error(thread_id) from exc
        raise
    except (ChatMessageConflictError, ChatMessageProtectedError) as exc:
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "chat_history.save_message_conflict",
            log = logger,
            headers = _conflict_headers(exc),
        ) from exc
    chat_originals.sweep()
    return ChatMessage(**saved)


@router.put("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)
def replace_thread_messages(
    thread_id: str,
    payload: ChatMessageSyncRequest,
    current_subject: str = Depends(get_current_subject),
):
    mismatched_ids = [message.id for message in payload.messages if message.threadId != thread_id]
    if mismatched_ids:
        preview = ", ".join(mismatched_ids[:5])
        suffix = "" if len(mismatched_ids) <= 5 else f" (+{len(mismatched_ids) - 5} more)"
        raise HTTPException(
            status_code = 400,
            detail = f"Message threadId mismatch: {preview}{suffix}",
        )
    if get_chat_thread(thread_id) is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    messages = [message.model_dump() for message in payload.messages]
    try:
        synced = sync_chat_messages(
            thread_id,
            messages,
            prune_missing = payload.pruneMissing,
            deleted_message_ids = payload.deletedMessageIds,
        )
    except sqlite3.IntegrityError as exc:
        if get_chat_thread(thread_id) is None:
            raise _missing_thread_error(thread_id) from exc
        raise
    except (ChatMessageConflictError, ChatMessageProtectedError) as exc:
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "chat_history.replace_messages_conflict",
            log = logger,
            headers = _conflict_headers(exc),
        ) from exc
    chat_originals.sweep()
    return ChatMessageListResponse(messages = [ChatMessage(**m) for m in synced])


@router.get("/count", response_model = ChatCountResponse)
def count_threads(current_subject: str = Depends(get_current_subject)):
    return ChatCountResponse(count = count_chat_threads())


@router.get("/import-ledger", response_model = ChatImportLedgerResponse)
def get_import_ledger(current_subject: str = Depends(get_current_subject)):
    """Legacy-Dexie import ledger: legacy thread ids already copied into chat tables.

    The frontend checks this on tab open to decide whether to re-run the Dexie -> studio.db import.
    """
    return ChatImportLedgerResponse(threadIds = list_chat_legacy_imports())


@router.post("/import-ledger", response_model = ChatImportLedgerRecordResponse)
def record_import_ledger(
    payload: ChatImportLedgerRecordRequest, current_subject: str = Depends(get_current_subject)
):
    """Mark each legacy thread id as imported. Idempotent."""
    accepted, inserted = upsert_chat_legacy_imports(payload.threadIds)
    return ChatImportLedgerRecordResponse(accepted = accepted, inserted = inserted)


def _snapshot_chat_images() -> Optional[set[str]]:
    """Registry and thumbnail cache are account-scoped, so this bounds the reap to the caller."""
    from core.inference.search_images import snapshot_and_fence_registrations
    return snapshot_and_fence_registrations()


@router.delete("")
async def clear_history(
    request: Request,
    payload: Optional[ChatClearRequest] = None,
    delete_files: bool = False,
    current_subject: str = Depends(get_current_subject),
):
    from starlette.concurrency import run_in_threadpool

    cutoff = _archive_cutoff()
    # Fence pending and legacy ids too so a delayed POST cannot recreate a chat.
    thread_ids = (
        list(payload.ids)
        if payload is not None
        else [thread["id"] for thread in await run_in_threadpool(list_chat_threads)]
    )

    def _clear_rows() -> tuple[list[str], list[str], list[str], bool, Optional[set]]:
        """One threadpool call for clear and snapshot, so no await lets new-chat images get reaped; narrows the race, does not close it."""
        if payload is None:
            cleared, cleared_runs, cleared_chat_runs = clear_chat_history(
                include_chat_generation_runs = True
            )
            return (
                cleared,
                cleared_runs,
                cleared_chat_runs,
                False,
                _snapshot_chat_images(),
            )
        # `replayed` comes from the transaction itself; a pre-read would race.
        cleared, cleared_runs, cleared_chat_runs, replayed = clear_chat_history_with_replay_status(
            payload.ids,
            operation_id = payload.operationId,
            include_chat_generation_runs = True,
        )
        if replayed:
            # A replay reaps only the original clear's snapshot, but may need to finish it.
            return (
                cleared,
                cleared_runs,
                cleared_chat_runs,
                True,
                unreaped_clear_operation_image_ids(payload.operationId),
            )
        snapshot = _snapshot_chat_images()
        # Recorded before the reap runs.
        record_clear_operation_reap_scope(payload.operationId, snapshot)
        return cleared, cleared_runs, cleared_chat_runs, False, snapshot

    # The clear reports what it deleted.
    (
        cleared,
        cleared_runs,
        cleared_chat_runs,
        replayed,
        reapable_image_ids,
    ) = await run_in_threadpool(_clear_rows)
    # A chat started mid-clear was never cancelled and could rebuild the sandbox.
    listed = set(thread_ids)
    late = [thread_id for thread_id in cleared if thread_id not in listed]
    _cancel_active_generations(thread_ids)
    if late:
        _cancel_active_generations(late)
    # By id: the rows went with the threads, so nothing can look them up now.
    _cancel_research_runs(request, cleared_runs)
    _cancel_chat_generation_runs(request, cleared_chat_runs)
    # Same cleanup as DELETE /threads, or cleared chats stay searchable in rag.db.
    await run_in_threadpool(
        _remove_thread_rag_data, list(dict.fromkeys(thread_ids + cleared)), cutoff = cutoff
    )
    await run_in_threadpool(chat_originals.sweep)
    # delete_files off by default, as in DELETE /threads: the files are the user's.
    removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)
    # Reap uses the original clear's snapshot so a replay can't reach newer chats' images.
    if not replayed or reapable_image_ids:
        from core.inference.search_images import clear_cache
        await run_in_threadpool(clear_cache, reapable_image_ids)
        if payload is not None:
            await run_in_threadpool(mark_clear_operation_caches_cleared, payload.operationId)
    return {
        "status": "deleted",
        "deletedThreadIds": cleared,
        "sandboxes_removed": removed,
        "sandboxes_kept": kept,
    }


@router.get("/pins", response_model = ChatPinsResponse, response_model_exclude_unset = True)
def get_pins(current_subject: str = Depends(get_current_subject)):
    pins = get_chat_pins()
    return ChatPinsResponse() if pins is None else ChatPinsResponse(pinnedIds = pins)


@router.post("/pins/migrate", response_model = ChatPinsResponse, response_model_exclude_unset = True)
def migrate_pins(
    payload: ChatPinsMigrationRequest, current_subject: str = Depends(get_current_subject)
):
    pins = migrate_chat_pins(payload.ids)
    return ChatPinsResponse() if pins is None else ChatPinsResponse(pinnedIds = pins)


@router.get("/settings", response_model = ChatSettingsResponse)
def get_settings(current_subject: str = Depends(get_current_subject)):
    return ChatSettingsResponse(settings = list_chat_settings())


@router.post("/settings/compare-and-set", response_model = ConditionalChatSettingsResponse)
def compare_and_set_settings(
    payload: dict[str, Any], current_subject: str = Depends(get_current_subject)
):
    # Raw dict: typed-body validation echoes input and a NaN would make the 422 itself 500.
    try:
        parsed = ConditionalChatSettingsPayload.model_validate(payload)
    except ValidationError as exc:
        raise HTTPException(status_code = 400, detail = safe_validation_errors(exc.errors())) from exc
    try:
        settings, applied = upsert_chat_settings_merge_if_current(
            parsed.expected.model_dump(exclude_unset = True),
            parsed.patch.model_dump(exclude_unset = True),
            parsed.expectedAbsent,
            parsed.expectedAbsentPaths,
            operation_id = parsed.operationId,
            unpinned_chat_ids = parsed.unpinnedChatIds,
            cancelled_operation_ids = parsed.cancelledOperationIds,
        )
        return ConditionalChatSettingsResponse(settings = settings, applied = applied)
    except CorruptSettingsError as exc:
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "chat_history.compare_and_set_settings_conflict",
            log = logger,
        ) from exc


@router.put("/settings", response_model = ChatSettingsResponse)
def put_settings(payload: dict[str, Any], current_subject: str = Depends(get_current_subject)):
    try:
        parsed = ChatSettingsPayload.model_validate(payload)
    except ValidationError as exc:
        # Raw errors echo input; a NaN would make the 400 handler 500.
        raise HTTPException(status_code = 400, detail = safe_validation_errors(exc.errors())) from exc
    # Atomic read + deep-merge + write in one BEGIN IMMEDIATE so concurrent updates don't clobber.
    try:
        return ChatSettingsResponse(
            settings = upsert_chat_settings_merge(parsed.model_dump(exclude_unset = True))
        )
    except CorruptSettingsError as exc:
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "chat_history.put_settings_conflict",
            log = logger,
        ) from exc


class ChatForkRequest(BaseModel):
    # an omitted message selects the tip within the fork transaction.
    messageId: Optional[str] = None
    newThreadId: str
    createdAt: SqliteInt


class ChatForkResponse(BaseModel):
    thread: ChatThread
    messages: list[ChatMessage]
    containerSnapshotWarning: Optional[str] = None


class ChatForkCountResponse(BaseModel):
    count: int


class ChatThreadForkCountsResponse(BaseModel):
    counts: dict[str, int]


def _drop_file_history(thread_id: str) -> None:
    try:
        from core.inference import file_history
        file_history.store().delete_chat(thread_id)
    except Exception:
        logger.warning("Could not remove the file history of %s", thread_id, exc_info = True)


class ChatRewindRequest(BaseModel):
    # The user messages being rewound, from the chosen one to the tip of the selected branch.
    turn_ids: list[Annotated[str, Field(min_length = 1, max_length = 256)]] = Field(max_length = 5000)
    dry_run: bool = False
    force: bool = False


@router.post("/threads/{thread_id}/rewind")
def rewind_thread_files(
    thread_id: str,
    payload: ChatRewindRequest,
    current_subject: str = Depends(get_current_subject),
):
    """Put back the files this chat's tool calls changed during ``turn_ids``. Moving the
    conversation itself is the client's: it edits the chosen message, which keeps the old branch."""
    from core.inference import file_history, tools
    from hub.services.models import account_access
    from state import active_generations

    if get_chat_thread(thread_id) is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    if not payload.dry_run and thread_id in active_generations.active_thread_ids(
        account_access.account_scope()
    ):
        raise HTTPException(
            status_code = 409, detail = "This chat is still generating. Rewind it once it finishes."
        )

    def busy(workdir: str) -> bool:
        with tools._calls_lock:
            return any(os.path.realpath(w) == workdir for w in tools._workdir_calls)

    try:
        report = file_history.store().rewind(
            thread_id,
            payload.turn_ids,
            tools._history_walk,
            dry_run = payload.dry_run,
            force = payload.force,
            busy = busy,
        )
    except file_history.RewindBusy as exc:
        raise HTTPException(status_code = 409, detail = str(exc)) from exc
    if report.undo_turn_id:
        from core import library
        library.invalidate_listing()
    return report.as_dict()


@router.post("/threads/{thread_id}/fork", response_model = ChatForkResponse)
def fork_thread(
    thread_id: str,
    payload: ChatForkRequest,
    current_subject: str = Depends(get_current_subject),
):
    """Fork a thread at `messageId` -- creates a new thread with
    ancestor msgs [root..messageId] copied with fresh ids. Both
    code-exec container ids reset on the fork. OpenAI snapshot is a
    best-effort enhancement; failure surfaces as
    `containerSnapshotWarning` and the fork still succeeds with a
    clean sandbox.
    """
    import uuid

    from hub.services.models import account_access
    from state import active_generations

    source = get_chat_thread(thread_id)
    if source is None:
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")
    # Refuse while generating: the tip is unsettled and a client check races other tabs.
    if thread_id in active_generations.active_thread_ids(account_access.account_scope()):
        raise HTTPException(
            status_code = 409,
            detail = "This chat is still generating. Fork it once it finishes.",
        )
    if payload.messageId is not None and get_chat_message(thread_id, payload.messageId) is None:
        raise HTTPException(
            status_code = 404,
            detail = f"Message {payload.messageId} not found in thread {thread_id}",
        )
    try:
        forked = fork_chat_thread(
            source_thread_id = thread_id,
            branch_message_id = payload.messageId,
            new_thread_id = payload.newThreadId,
            created_at = payload.createdAt,
            id_factory = lambda: str(uuid.uuid4()),
        )
    except ChatForkActiveGenerationError as exc:
        raise HTTPException(status_code = 409, detail = str(exc)) from exc
    except ChatThreadDeletedError as exc:
        raise _deleted_thread_error(payload.newThreadId) from exc
    if forked is None:
        # Source can be deleted concurrently; report 404, not 500.
        raise HTTPException(status_code = 404, detail = f"Thread {thread_id} or fork message not found")
    # Stub: v1 always starts a fresh container and surfaces the same warning for every provider.
    warning: Optional[str] = None
    if source.get("openaiCodeExecContainerId") or source.get("anthropicCodeExecContainerId"):
        warning = "Sandbox starts fresh in fork; files from parent are not carried over."
    created_before = _fork_document_cutoff(
        thread_id, forked.get("forkedFromMessageId"), payload.createdAt
    )
    if not _copy_thread_rag_documents(
        thread_id, payload.newThreadId, created_before = created_before
    ):
        warning = " ".join(
            filter(None, [warning, "Documents attached to the parent chat were not copied."])
        )
    messages = list_chat_messages(payload.newThreadId)
    return ChatForkResponse(
        thread = thread_from_row(forked),
        messages = [ChatMessage(**m) for m in messages],
        containerSnapshotWarning = warning,
    )


@router.get(
    "/threads/{thread_id}/messages/{message_id}/forks",
    response_model = ChatForkCountResponse,
)
def get_fork_count(
    thread_id: str,
    message_id: str,
    current_subject: str = Depends(get_current_subject),
):
    return ChatForkCountResponse(count = count_forks_for_message(thread_id, message_id))


@router.get(
    "/threads/{thread_id}/forks",
    response_model = ChatThreadForkCountsResponse,
)
def get_thread_fork_counts(thread_id: str, current_subject: str = Depends(get_current_subject)):
    """Every fork count of a thread in one read, so a rendered thread costs one request."""
    return ChatThreadForkCountsResponse(counts = fork_counts_for_thread(thread_id))


@router.get("/export", response_model = ChatExportResponse)
def export_history(current_subject: str = Depends(get_current_subject)):
    from datetime import datetime, timezone
    projects, threads, messages = build_chat_history_export()
    return ChatExportResponse(
        exportedAt = datetime.now(timezone.utc).isoformat(),
        version = 1,
        threadCount = len(threads),
        projects = [ChatProject(**project) for project in projects],
        threads = [thread_from_row(thread) for thread in threads],
        messages = [ChatMessage(**message) for message in messages],
    )