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.

5.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import type { useChatRuntimeStore } from "../stores/chat-runtime-store";

const QUEUED_SETTING_KEYS = [
  "activeGgufVariant",
  "supportsTools",
  "supportsReasoning",
  "reasoningAlwaysOn",
  "reasoningStyle",
  "supportsReasoningOff",
  "reasoningEffortLevels",
  "supportsPreserveThinking",
  "reasoningEnabled",
  "reasoningEffort",
  "preserveThinking",
  "toolsEnabled",
  "codeToolsEnabled",
  "codeToolsDeclinedUnderFullAccess",
  "imageToolsEnabled",
  "mcpEnabledForChat",
  "confirmToolCalls",
  "bypassPermissions",
  "permissionMode",
  "chatFullAccessPreviousMode",
  "sandboxLevel",
  "webFetchToolsEnabled",
  "deepResearchEnabled",
  "researchWebsitePolicy",
  "researchMcpSources",
  "researchModelTimeoutSeconds",
  "ragEnabled",
  "ragSource",
  "ragMode",
  "ragTopK",
  "ragAutoInject",
  "ragAutoInjectMinScore",
  "loadedContextLength",
  // A queued local turn is served by the model it was queued against; keeps GGUF compaction policy.
  "loadedIsGguf",
  "loadedIsMlx",
  "loadedEngine",
  "autoHealToolCalls",
  "nudgeToolCalls",
  "deduplicateToolCalls",
  "maxToolCallsPerMessage",
  "toolCallTimeout",
  "autoCompactEnabled",
  // A queued send keeps the tab-close choice it was sent with, like every setting above.
  "keepRunningWhenTabClosed",
] as const;

type ChatRuntimeState = ReturnType<typeof useChatRuntimeStore.getState>;

export type QueuedChatRunSettings = Pick<
  ChatRuntimeState,
  (typeof QUEUED_SETTING_KEYS)[number]
> & {
  params: ChatRuntimeState["params"];
};

type PendingSettings = {
  id: number;
  threadIds: Set<string>;
  settings: QueuedChatRunSettings;
};

let nextPendingSettingsId = 1;
const pendingSettings: PendingSettings[] = [];

export function snapshotQueuedChatRunSettings(
  state: ChatRuntimeState,
  options?: { deferModelResolution?: boolean },
): QueuedChatRunSettings {
  const snapshot = {
    params: { ...state.params },
  } as QueuedChatRunSettings;
  for (const key of QUEUED_SETTING_KEYS) {
    Object.assign(snapshot, { [key]: state[key] });
  }
  if (options?.deferModelResolution) {
    snapshot.params.checkpoint = "";
    snapshot.activeGgufVariant = null;
  }
  return snapshot;
}

export function resolveDeferredQueuedModelSettings(
  settings: QueuedChatRunSettings,
  resolved: Pick<ChatRuntimeState, "params" | "supportsTools">,
): QueuedChatRunSettings {
  return {
    ...settings,
    params: {
      ...settings.params,
      checkpoint: resolved.params.checkpoint,
    },
    supportsTools: resolved.supportsTools,
  };
}

/** A chat remembers the model it last sent to, so reopening it offers that one back. Compare panes
 *  keep the model they were opened with: their labels and pairing read it. An unknown variant
 *  never clears a saved one for the same model. */
export function shouldPersistRunModel(
  storedThread:
    | {
        modelId?: string | null;
        modelGgufVariant?: string | null;
        pairId?: string | null;
      }
    | null
    | undefined,
  modelId: string,
  modelGgufVariant: string | null,
): boolean {
  if (!storedThread || !modelId || storedThread.pairId) return false;
  if (storedThread.modelId !== modelId) return true;
  return (
    modelGgufVariant != null &&
    modelGgufVariant !== (storedThread.modelGgufVariant ?? null)
  );
}

export function registerQueuedChatRunSettings(
  threadIds: string[],
  settings: QueuedChatRunSettings,
): number {
  const id = nextPendingSettingsId++;
  pendingSettings.push({
    id,
    threadIds: new Set(threadIds),
    settings,
  });
  return id;
}

export function addQueuedChatRunSettingsThreadIds(
  id: number,
  threadIds: string[],
): void {
  const entry = pendingSettings.find((candidate) => candidate.id === id);
  if (!entry) {
    return;
  }
  for (const threadId of threadIds) {
    if (threadId) {
      entry.threadIds.add(threadId);
    }
  }
}

export function discardQueuedChatRunSettings(id: number): void {
  const index = pendingSettings.findIndex((entry) => entry.id === id);
  if (index >= 0) {
    pendingSettings.splice(index, 1);
  }
}

export function discardQueuedChatRunSettingsForThread(
  threadId?: string | null,
): void {
  if (!threadId) {
    return;
  }
  for (let index = pendingSettings.length - 1; index >= 0; index -= 1) {
    if (pendingSettings[index].threadIds.has(threadId)) {
      pendingSettings.splice(index, 1);
    }
  }
}

export function hasQueuedChatRunSettings(threadId?: string | null): boolean {
  return Boolean(
    threadId && pendingSettings.some((entry) => entry.threadIds.has(threadId)),
  );
}

export function consumeQueuedChatRunSettings(
  threadId?: string | null,
): QueuedChatRunSettings | null {
  const index = threadId
    ? pendingSettings.findIndex((entry) => entry.threadIds.has(threadId))
    : -1;
  // Never consume another chat's snapshot: queued chats can start concurrently.
  if (index < 0) {
    return null;
  }
  // Tool calls invoke the adapter repeatedly per run; the owning queue discards it when idle.
  return pendingSettings[index].settings;
}