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.

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

// setLocale may return "superseded"; the sync must still finish or saves pause all session.

import assert from "node:assert/strict";
import test from "node:test";

import { loadWithStubs } from "./helpers/module-stubs.ts";
import { sanitizeCustomization } from "../src/features/settings/stores/appearance-custom-store.ts";
import * as greeting from "../src/features/profile/greeting.ts";

type Slot = {
  value?: unknown;
  deps?: readonly unknown[];
  cleanup?: unknown;
  set?: boolean;
};

function runCleanup(cleanup: unknown): void {
  if (typeof cleanup === "function") (cleanup as () => void)();
}

type Profile = {
  displayName: string;
  nickname: string;
  avatarDataUrl: string | null;
  avatarShape: "circle" | "rounded";
  showGreetingSloth: boolean;
  greetingStyle?: string;
  greetingIcon?: string;
  greetingIconDataUrl?: string | null;
  greetingText?: string;
  greetingImageDataUrl?: string | null;
};

type SavedPayload = {
  version: number;
  profile: Profile;
  appearance: {
    theme: string;
    palette: string;
    language: string | null;
    customization: Record<string, unknown>;
  };
};

const HOOK_URL = new URL(
  "../src/features/profile/hooks/use-personalization-sync.ts",
  import.meta.url,
);

function sameDeps(a: readonly unknown[], b: readonly unknown[]): boolean {
  return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
}

function createReact() {
  const slots: Slot[] = [];
  const effects: (() => void)[] = [];
  let cursor = 0;
  let dirty = false;

  const slot = (): Slot => {
    const existing = slots[cursor];
    if (existing) {
      cursor += 1;
      return existing;
    }
    const created: Slot = {};
    slots[cursor] = created;
    cursor += 1;
    return created;
  };

  const react = {
    useState<T>(initial: T): [T, (next: T) => void] {
      const self = slot();
      if (!self.set) {
        self.value = initial;
        self.set = true;
      }
      return [
        self.value as T,
        (next: T) => {
          if (Object.is(next, self.value)) return;
          self.value = next;
          dirty = true;
        },
      ];
    },
    useRef<T>(initial: T): { current: T } {
      const self = slot();
      if (!self.set) {
        self.value = { current: initial };
        self.set = true;
      }
      return self.value as { current: T };
    },
    useCallback<T>(fn: T, deps: readonly unknown[]): T {
      const self = slot();
      if (!self.deps || !sameDeps(self.deps, deps)) {
        self.value = fn;
        self.deps = deps;
      }
      return self.value as T;
    },
    useEffect(fn: () => unknown, deps: readonly unknown[]): void {
      const self = slot();
      if (self.deps && sameDeps(self.deps, deps)) return;
      self.deps = deps;
      effects.push(() => {
        runCleanup(self.cleanup);
        self.cleanup = fn();
      });
    },
  };

  return {
    react,
    flush(body: () => void): void {
      do {
        cursor = 0;
        dirty = false;
        body();
        while (effects.length) effects.shift()?.();
      } while (dirty);
    },
    unmount(): void {
      for (const self of slots) runCleanup(self.cleanup);
    },
  };
}

function installWindow() {
  const timers = new Map<number, () => void>();
  let nextId = 1;
  Object.assign(globalThis, {
    window: {
      setTimeout(fn: () => void): number {
        const id = nextId;
        nextId += 1;
        timers.set(id, fn);
        return id;
      },
      clearTimeout(id: number): void {
        timers.delete(id);
      },
    },
  });
  return () => {
    const due = [...timers.values()];
    timers.clear();
    for (const fn of due) fn();
  };
}

function settle(): Promise<void> {
  return new Promise((resolve) => setImmediate(resolve));
}

function remotePersonalization(language: string) {
  return {
    version: 3,
    profile: {
      displayName: "",
      nickname: "",
      avatarDataUrl: null,
      avatarShape: "circle" as const,
      ...greeting.DEFAULT_GREETING,
    },
    appearance: {
      theme: "system",
      palette: "standard",
      language,
      customization: {},
    },
    saved: true,
    customizationSaved: true,
    paletteSaved: true,
    greetingSlothSaved: true,
  };
}

function setup(
  localeResult: "superseded" | "cancelled" | "stalled",
  options: {
    localCustomization?: Record<string, unknown>;
    remote?: ReturnType<typeof remotePersonalization> & {
      chatWidthSaved?: boolean;
      sentAttachmentsSaved?: boolean;
      greetingCustomSaved?: boolean;
    };
    localProfile?: Partial<Profile>;
    // Holds the personalization GET open until it resolves.
    remoteGate?: Promise<void>;
  } = {},
) {
  const runTimers = installWindow();
  const host = createReact();
  const saves: SavedPayload[] = [];
  const localeCalls: unknown[] = [];
  let customization = sanitizeCustomization(options.localCustomization);
  const appearanceStore = Object.assign(
    (select: (state: unknown) => unknown) => select({ customization }),
    {
      getState: () => ({
        customization,
        replaceAll: (next: unknown) => {
          customization = sanitizeCustomization(next);
        },
      }),
    },
  );
  let profile: Profile = {
    displayName: "",
    nickname: "",
    avatarDataUrl: null,
    avatarShape: "circle",
    ...greeting.DEFAULT_GREETING,
    ...options.localProfile,
  };
  let preference = "auto";
  let releaseLocale!: () => void;
  const localeSettled = new Promise<void>((resolve) => {
    releaseLocale = resolve;
  });

  const profileStore = Object.assign(
    (select: (state: Profile) => unknown) => select(profile),
    {
      getState: () => profile,
      setState: (next: Partial<Profile>) => {
        profile = { ...profile, ...next };
      },
    },
  );

  // The hook imports these from the settings store, theme store and personalization API modules.
  const settings = {
    isDefaultCustomization: (value: unknown) =>
      Object.keys(value as object).length === 0,
    isPalette: (value: unknown) => typeof value === "string",
    loadPersonalization: async () => {
      await options.remoteGate;
      return options.remote ?? remotePersonalization("de");
    },
    migrateAppearanceMenuDefault: (value: unknown) => value,
    migrateShippedSidebarNavDefault: (value: unknown) => value,
    sanitizeCustomization,
    savePersonalization: (data: SavedPayload) => {
      saves.push(data);
      return Promise.resolve();
    },
    setPalette: () => undefined,
    setTheme: () => undefined,
    useAppearanceCustomStore: appearanceStore,
    usePalette: () => ({ palette: "standard" }),
    useTheme: () => ({ theme: "system" }),
  };
  const { usePersonalizationSync } = loadWithStubs<{
    usePersonalizationSync: (enabled: boolean) => void;
  }>(HOOK_URL, {
    react: host.react,
    "@/features/settings/stores/appearance-custom-store": settings,
    "@/features/settings/stores/theme-store": settings,
    "@/features/settings/api/personalization": settings,
    "@/i18n": {
      DEFAULT_LOCALE_PREFERENCE: "auto",
      LOCALE_INITIALIZATION_TIMEOUT_MS: 2_000,
      getLocalePreference: () => preference,
      isLocalePreference: (value: unknown) => typeof value === "string",
      setLocale: async (value: unknown, options?: { timeoutMs?: number }) => {
        localeCalls.push(value);
        // A catalog request the network accepted but never completed; it rejects nothing, so only
        // the caller asking the store to bound it can end the wait.
        if (localeResult === "stalled") {
          if (typeof options?.timeoutMs !== "number") {
            return new Promise<string>(() => {});
          }
          return "failed";
        }
        await localeSettled;
        if (localeResult === "superseded") preference = "fr";
        return localeResult;
      },
      useLocalePreference: () => preference,
    },
    "../greeting": greeting,
    "../stores/user-profile-store": {
      PROFILE_TEXT_MAX_LENGTH: 200,
      useUserProfileStore: profileStore,
    },
  });

  return {
    host,
    localeCalls,
    releaseLocale,
    runTimers,
    saves,
    customization: () => customization,
    profile: () => profile,
    // What a settings control does: a new customization object in the store.
    edit(next: Record<string, unknown>) {
      customization = sanitizeCustomization({ ...customization, ...next });
    },
    rename(displayName: string) {
      profile = { ...profile, displayName };
    },
    render() {
      host.flush(() => usePersonalizationSync(true));
    },
  };
}

test("a superseded locale hydration does not pause personalization saves", async () => {
  const app = setup("superseded");

  app.render();
  await settle();
  assert.deepEqual(app.localeCalls, ["de"]);

  app.releaseLocale();
  await settle();
  app.render();

  app.rename("Ada");
  app.render();
  app.runTimers();
  await settle();

  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.profile.displayName, "Ada");
  assert.equal(app.saves[0]?.appearance.language, "fr");
});

test("a cancelled locale hydration stays paused, because it never finished", async () => {
  const app = setup("cancelled");

  app.render();
  await settle();
  app.host.unmount();

  app.releaseLocale();
  await settle();
  app.render();
  app.rename("Ada");
  app.render();
  app.runTimers();
  await settle();

  assert.equal(app.saves.length, 0);
});

test("a stalled locale catalog does not pause personalization saves", async () => {
  const app = setup("stalled");

  app.render();
  await settle();
  assert.deepEqual(app.localeCalls, ["de"]);

  app.render();
  app.rename("Ada");
  app.render();
  app.runTimers();
  await settle();

  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.profile.displayName, "Ada");
});

function widthRemote(chatWidthSaved?: boolean, chatWidth?: string) {
  const remote = remotePersonalization("auto");
  return {
    ...remote,
    version: 6,
    chatWidthSaved,
    appearance: {
      ...remote.appearance,
      customization: {
        uiFont: "Georgia",
        ...(chatWidth === undefined ? {} : { chatWidth }),
      },
    },
  };
}

for (const localWidth of ["wide", "full"]) {
  test(`legacy chat width preserves and uploads local ${localWidth}`, async () => {
    const app = setup("stalled", {
      localCustomization: { chatWidth: localWidth, uiFont: "Arial" },
      remote: widthRemote(false, "standard"),
    });
    app.render();
    await settle();
    app.render();

    assert.equal(app.customization().chatWidth, localWidth);
    assert.equal(app.customization().uiFont, "Georgia");
    app.runTimers();
    await settle();
    assert.equal(app.saves.length, 1);
    assert.equal(app.saves[0]?.appearance.customization.chatWidth, localWidth);
    app.host.unmount();
  });
}

for (const remoteWidth of ["standard", "wide", "full"]) {
  test(`saved chat width ${remoteWidth} overrides local without another save`, async () => {
    const app = setup("stalled", {
      localCustomization: {
        chatWidth: remoteWidth === "full" ? "wide" : "full",
      },
      remote: widthRemote(true, remoteWidth),
    });
    app.render();
    await settle();
    app.render();
    assert.equal(app.customization().chatWidth, remoteWidth);
    app.runTimers();
    await settle();
    assert.equal(app.saves.length, 0);
    app.host.unmount();
  });
}

test("an older server without chat width metadata preserves local width", async () => {
  const app = setup("stalled", {
    localCustomization: { chatWidth: "wide" },
    remote: widthRemote(),
  });
  app.render();
  await settle();
  app.render();
  assert.equal(app.customization().chatWidth, "wide");
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.appearance.customization.chatWidth, "wide");
  app.host.unmount();
});

function attachmentsRemote(saved: boolean | undefined, customization: Record<string, string>) {
  const remote = remotePersonalization("auto");
  return {
    ...remote,
    version: 6,
    chatWidthSaved: true,
    sentAttachmentsSaved: saved,
    appearance: {
      ...remote.appearance,
      customization: { chatWidth: "standard", uiFont: "Georgia", ...customization },
    },
  };
}

test("legacy attachment display preserves and uploads the local choice", async () => {
  const app = setup("stalled", {
    localCustomization: { sentAttachments: "chips" },
    remote: attachmentsRemote(false, { sentAttachments: "auto" }),
  });
  app.render();
  await settle();
  app.render();

  assert.equal(app.customization().sentAttachments, "chips");
  assert.equal(app.customization().uiFont, "Georgia");
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.appearance.customization.sentAttachments, "chips");
  app.host.unmount();
});

test("saved attachment display overrides local without another save", async () => {
  const app = setup("stalled", {
    localCustomization: { sentAttachments: "chips" },
    remote: attachmentsRemote(true, { sentAttachments: "list" }),
  });
  app.render();
  await settle();
  app.render();
  assert.equal(app.customization().sentAttachments, "list");
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 0);
  app.host.unmount();
});

test("an older server without attachment display keys preserves the local choice", async () => {
  const app = setup("stalled", {
    localCustomization: { sentAttachments: "list" },
    remote: attachmentsRemote(undefined, {}),
  });
  app.render();
  await settle();
  app.render();
  assert.equal(app.customization().sentAttachments, "list");
  app.host.unmount();
});

test("an edit made while the personalization request is in flight is not overwritten by it", async () => {
  // The server still holds an older size (a save cut short by a reload); the user changes it
  // before that answer arrives.
  let releaseRemote!: () => void;
  const remote = remotePersonalization("auto");
  const app = setup("stalled", {
    localCustomization: { uiFontSize: 12 },
    remote: {
      ...remote,
      version: 6,
      appearance: { ...remote.appearance, customization: { uiFontSize: 20 } },
    },
    remoteGate: new Promise<void>((resolve) => {
      releaseRemote = resolve;
    }),
  });
  app.render();
  await settle();

  app.edit({ uiFontSize: 15 });
  app.render();
  releaseRemote();
  await settle();
  app.render();

  assert.equal(app.customization().uiFontSize, 15);
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.appearance.customization.uiFontSize, 15);
  app.host.unmount();
});

test("without an edit in flight the saved server customization still wins", async () => {
  const remote = remotePersonalization("auto");
  const app = setup("stalled", {
    localCustomization: { uiFontSize: 12 },
    remote: {
      ...remote,
      version: 6,
      appearance: { ...remote.appearance, customization: { uiFontSize: 20 } },
    },
  });
  app.render();
  await settle();
  app.render();

  assert.equal(app.customization().uiFontSize, 20);
  app.host.unmount();
});

const ICON = "data:image/png;base64,AAAA";

test("a server record from before the custom greeting keeps and re-pushes the local one", async () => {
  const app = setup("stalled", {
    localProfile: { greetingIcon: "custom", greetingIconDataUrl: ICON, greetingText: "Hi" },
    remote: remotePersonalization("auto"),
  });
  app.render();
  await settle();
  app.render();

  assert.equal(app.profile().greetingIcon, "custom");
  assert.equal(app.profile().greetingIconDataUrl, ICON);
  assert.equal(app.profile().greetingText, "Hi");
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 1);
  assert.equal(app.saves[0]?.profile.greetingIconDataUrl, ICON);
  app.host.unmount();
});

test("a saved server greeting wins over the local one", async () => {
  const remote = remotePersonalization("auto");
  const app = setup("stalled", {
    localProfile: { greetingText: "Local" },
    remote: {
      ...remote,
      version: 6,
      greetingCustomSaved: true,
      profile: {
        ...remote.profile,
        greetingStyle: "image",
        greetingImageDataUrl: ICON,
      },
    },
  });
  app.render();
  await settle();
  app.render();

  assert.equal(app.profile().greetingStyle, "image");
  assert.equal(app.profile().greetingImageDataUrl, ICON);
  assert.equal(app.profile().greetingText, "");
  app.runTimers();
  await settle();
  assert.equal(app.saves.length, 0);
  app.host.unmount();
});