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.

7.3 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

// Re-validate before sending: the backend rejects the whole patch on one bad field.

import type { PersistedChatSettings } from "../api/chat-settings-api";
import type { ResearchMcpSource } from "../types/research";

export const MAX_RESEARCH_MCP_SOURCES = 20;

export function normalizeResearchMcpSources(value: unknown): ResearchMcpSource[] {
  if (!Array.isArray(value)) return [];
  const sources: ResearchMcpSource[] = [];
  const seen = new Set<string>();
  for (const item of value) {
    const serverId = item?.serverId;
    const tool = item?.tool;
    if (
      typeof serverId !== "string" ||
      serverId.length < 1 ||
      serverId.length > 200 ||
      typeof tool !== "string" ||
      tool.length < 1 ||
      tool.length > 500
    ) {
      continue;
    }
    const key = `${serverId}\0${tool}`;
    if (seen.has(key)) continue;
    seen.add(key);
    sources.push({ serverId, tool });
    if (sources.length === MAX_RESEARCH_MCP_SOURCES) break;
  }
  return sources;
}

const MIRRORED_BOOLEAN_KEYS = [
  "reasoningEnabled",
  "toolsEnabled",
  "codeToolsEnabled",
  "imageToolsEnabled",
  "webFetchToolsEnabled",
  "deepResearchEnabled",
  "searchImages",
  "mcpEnabledForChat",
  "confirmToolCalls",
  "ragOcrScanned",
  "ragCaptionFigures",
  "expandQuantizations",
  "showAllQuantizations",
  "fitOnDeviceOnly",
] as const satisfies readonly (keyof PersistedChatSettings)[];

const MIRRORED_ENUM_VALUES = {
  // "full" (Full access) is session-only and never persisted.
  permissionMode: ["ask", "auto", "off"],
  sandboxLevel: ["high", "low"],
  ragMode: ["hybrid", "lexical", "dense"],
  ragAutoInject: ["auto", "on", "off"],
  speculativeType: ["auto", "ngram", "off"],
  gpuMemoryMode: ["auto", "manual"],
} as const satisfies Partial<
  Record<keyof PersistedChatSettings, readonly string[]>
>;

// One year, the ceiling the backend payload and run route enforce.
export const MAX_RESEARCH_MODEL_TIMEOUT_SECONDS = 365 * 24 * 3600;
// 0 is the unlimited sentinel; a stored 1..9 would 400 every run.
export const MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS = 10;

// Must match the backend payload's ge/le bounds.
const MIRRORED_NUMBER_BOUNDS = {
  ragTopK: { min: 1, max: 50, integer: true },
  ragAutoInjectMinScore: { min: 0, max: 1, integer: false },
  researchModelTimeoutSeconds: {
    min: 0,
    minPositive: MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS,
    max: MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
    integer: true,
  },
} as const satisfies Partial<
  Record<
    keyof PersistedChatSettings,
    { min: number; minPositive?: number; max: number; integer: boolean }
  >
>;

export const MIRRORED_SETTING_KEYS = [
  ...MIRRORED_BOOLEAN_KEYS,
  ...(Object.keys(
    MIRRORED_ENUM_VALUES,
  ) as (keyof typeof MIRRORED_ENUM_VALUES)[]),
  ...(Object.keys(
    MIRRORED_NUMBER_BOUNDS,
  ) as (keyof typeof MIRRORED_NUMBER_BOUNDS)[]),
  "researchWebsitePolicy",
  "researchMcpSources",
  "ragSource",
] as const satisfies readonly (keyof PersistedChatSettings)[];

const MAX_RESEARCH_POLICY_DOMAINS = 1000;
const MAX_DOMAIN_LENGTH = 253;
const MAX_RAG_KB_ID_LENGTH = 256;

export function isRecord(value: unknown): value is Record<string, unknown> {
  return value != null && typeof value === "object" && !Array.isArray(value);
}

function sanitizeDomainList(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value
    .filter(
      (entry): entry is string =>
        typeof entry === "string" && entry.length <= MAX_DOMAIN_LENGTH,
    )
    .slice(0, MAX_RESEARCH_POLICY_DOMAINS);
}

function sanitizeResearchWebsitePolicy(
  value: unknown,
): PersistedChatSettings["researchWebsitePolicy"] | undefined {
  if (!isRecord(value)) return undefined;
  return {
    allowedDomains: sanitizeDomainList(value.allowedDomains),
    blockedDomains: sanitizeDomainList(value.blockedDomains),
  };
}

export function sanitizeRagSource(
  value: unknown,
): PersistedChatSettings["ragSource"] | undefined {
  if (!isRecord(value)) return undefined;
  if (value.type === "thread") return { type: "thread" };
  if (
    value.type === "kb" &&
    typeof value.kbId === "string" &&
    value.kbId.length > 0 &&
    value.kbId.length <= MAX_RAG_KB_ID_LENGTH
  ) {
    return { type: "kb", kbId: value.kbId };
  }
  return undefined;
}

export function sanitizeBoundedNumber(
  value: unknown,
  {
    min,
    minPositive,
    max,
    integer,
  }: { min: number; minPositive?: number; max: number; integer: boolean },
): number | undefined {
  if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
  if (integer && !Number.isInteger(value)) return undefined;
  if (minPositive !== undefined && value > min && value < minPositive) {
    return undefined;
  }
  return value >= min && value <= max ? value : undefined;
}

export function assignSanitizedMirroredSettings(
  value: Record<string, unknown>,
  settings: PersistedChatSettings,
): void {
  const target = settings as Record<string, unknown>;
  for (const key of MIRRORED_BOOLEAN_KEYS) {
    if (typeof value[key] === "boolean") target[key] = value[key];
  }
  for (const [key, allowed] of Object.entries(MIRRORED_ENUM_VALUES)) {
    const candidate = value[key];
    if (
      typeof candidate === "string" &&
      (allowed as readonly string[]).includes(candidate)
    ) {
      target[key] = candidate;
    }
  }
  for (const [key, bounds] of Object.entries(MIRRORED_NUMBER_BOUNDS)) {
    const sanitized = sanitizeBoundedNumber(value[key], bounds);
    if (sanitized !== undefined) target[key] = sanitized;
  }
  const researchWebsitePolicy = sanitizeResearchWebsitePolicy(
    value.researchWebsitePolicy,
  );
  if (researchWebsitePolicy) {
    settings.researchWebsitePolicy = researchWebsitePolicy;
  }
  if (Array.isArray(value.researchMcpSources)) {
    settings.researchMcpSources = normalizeResearchMcpSources(
      value.researchMcpSources,
    );
  }
  const ragSource = sanitizeRagSource(value.ragSource);
  if (ragSource) settings.ragSource = ragSource;
}

/** Legacy "true"/"false" values are rejected by the backend, so migrate before backfill. */
export function normalizeStoredRagAutoInject(
  raw: string,
): "auto" | "on" | "off" {
  if (raw === "auto" || raw === "on" || raw === "off") return raw;
  return raw === "false" ? "off" : "auto";
}

/** speculativeType and gpuMemoryMode pair with loaded* shadows; never move just one half. */
export function loadShadowOwnsMirroredSetting(
  key: string,
  shadows: {
    loadedSpeculativeType: string | null;
    loadedGpuMemoryMode: "auto" | "manual" | null;
  },
): boolean {
  if (key === "speculativeType") return shadows.loadedSpeculativeType !== null;
  if (key === "gpuMemoryMode") return shadows.loadedGpuMemoryMode !== null;
  return false;
}

// storage predating the level control holds only the confirm toggle: on -> ask, off -> off.
export function normalizeStoredPermissionMode(
  rawMode: string | null,
  legacyConfirm: boolean | null,
): "ask" | "auto" | "off" {
  if (rawMode === "ask" || rawMode === "auto" || rawMode === "off") {
    return rawMode;
  }
  if (legacyConfirm === null) return "auto";
  return legacyConfirm ? "ask" : "off";
}

export function hasNoMirroredSettings(
  settings: PersistedChatSettings,
): boolean {
  return MIRRORED_SETTING_KEYS.every((key) => settings[key] === undefined);
}