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.

10.2 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 assert from "node:assert/strict";
import { readFile, readdir } from "node:fs/promises";
import test from "node:test";

import {
  USER_STOPPED_KEY,
  clearServerStopIntent,
  hasServerStopIntent,
  markServerStopIntent,
} from "../src/hooks/server-stop-intent.ts";

import { readSrc } from "./helpers/kit.ts";

const USE_TAURI_BACKEND = readSrc("hooks/use-tauri-backend.ts");

type Storage = {
  getItem: (key: string) => string | null;
  setItem: (key: string, value: string) => void;
  removeItem: (key: string) => void;
};

function installSessionStorage(): Map<string, string> {
  const store = new Map<string, string>();
  const storage: Storage = {
    getItem: (key) => store.get(key) ?? null,
    setItem: (key, value) => {
      store.set(key, value);
    },
    removeItem: (key) => {
      store.delete(key);
    },
  };
  Object.assign(globalThis, { sessionStorage: storage });
  return store;
}

function installThrowingSessionStorage(): void {
  const boom = () => {
    throw new DOMException("The operation is insecure.", "SecurityError");
  };
  Object.assign(globalThis, {
    sessionStorage: { getItem: boom, setItem: boom, removeItem: boom },
  });
}

function uninstallSessionStorage(): void {
  Reflect.deleteProperty(globalThis, "sessionStorage");
}

test("a fresh session carries no stop intent", () => {
  installSessionStorage();
  assert.equal(hasServerStopIntent(), false);
  uninstallSessionStorage();
});

test("a marked stop reads back, and clearing drops it", () => {
  const store = installSessionStorage();

  markServerStopIntent();
  assert.equal(hasServerStopIntent(), true);
  assert.deepEqual([...store.keys()], [USER_STOPPED_KEY]);

  clearServerStopIntent();
  assert.equal(hasServerStopIntent(), false);
  assert.equal(store.size, 0);
  uninstallSessionStorage();
});

test("marking twice is not two stops to clear", () => {
  installSessionStorage();
  markServerStopIntent();
  markServerStopIntent();
  clearServerStopIntent();
  assert.equal(hasServerStopIntent(), false);
  uninstallSessionStorage();
});

test("storage that throws never reaches the caller", () => {
  installThrowingSessionStorage();

  assert.equal(
    hasServerStopIntent(),
    false,
    "unreadable storage must read as no intent",
  );
  assert.doesNotThrow(() => markServerStopIntent());
  assert.doesNotThrow(() => clearServerStopIntent());

  uninstallSessionStorage();
});

test("storage missing entirely reads as a fresh session", () => {
  uninstallSessionStorage();

  assert.equal(hasServerStopIntent(), false);
  assert.doesNotThrow(() => markServerStopIntent());
  assert.doesNotThrow(() => clearServerStopIntent());
});

test("the marker key belongs to nothing else in the app", async () => {
  // Kept as URLs: a file URL pathname is "/D:/..." on Windows, which readFile misreads.
  const files: URL[] = [];
  async function walk(dir: URL) {
    for (const entry of await readdir(dir, { withFileTypes: true })) {
      const child = new URL(
        `${entry.name}${entry.isDirectory() ? "/" : ""}`,
        dir,
      );
      if (entry.isDirectory()) {
        await walk(child);
      } else if (/\.tsx?$/.test(entry.name)) {
        files.push(child);
      }
    }
  }
  await walk(new URL("../src/", import.meta.url));

  const owners: string[] = [];
  for (const file of files) {
    if ((await readFile(file, "utf8")).includes(`"${USER_STOPPED_KEY}"`)) {
      owners.push(file.pathname);
    }
  }

  assert.deepEqual(
    owners.map((f) => f.slice(f.indexOf("/src/"))),
    ["/src/hooks/server-stop-intent.ts"],
  );
});

test("the hook reaches storage only through the guarded helpers", async () => {
  const hook = USE_TAURI_BACKEND;

  assert.doesNotMatch(
    hook,
    /sessionStorage/,
    "the hook is back to touching sessionStorage directly",
  );
  assert.match(
    hook,
    /import \{\s*clearServerStopIntent,\s*hasServerStopIntent,\s*markServerStopIntent,\s*\} from "\.\/server-stop-intent";/,
  );
});

test("a persisted stop is honored before preflight runs", async () => {
  const hook = USE_TAURI_BACKEND;

  const body = hook.slice(
    hook.indexOf("async function checkInstallAndStart()"),
    hook.indexOf("async function startManagedServer()"),
  );
  const guard = body.indexOf("hasServerStopIntent()");
  const preflight = body.indexOf(
    'invoke<DesktopPreflightResult>("desktop_preflight")',
  );

  assert.ok(guard > 0 && preflight > 0);
  // desktop_preflight has side effects (clears intentional_stop), so the check must come first.
  assert.ok(
    guard < preflight,
    "the stop check moved behind preflight, whose adoption side effects it exists to skip",
  );
  assert.match(
    body.slice(guard, preflight),
    /setBackendStatus\("stopped"\);\s*return;/,
    "the honored stop no longer parks the screen on stopped",
  );
});

test("stopping records the intent before the shutdown it can outlive", async () => {
  const hook = USE_TAURI_BACKEND;
  const body = hook.slice(
    hook.indexOf("async function stopServer()"),
    hook.indexOf("async function startInstall()"),
  );

  // Reaping can block ~15s, so the marker must be written before it; order is load bearing.
  const mark = body.indexOf("markServerStopIntent();\n    try {");
  const invoke = body.indexOf('await invoke("stop_server"');
  assert.ok(
    mark > 0 && invoke > mark,
    "the marker is written after the stop it must survive",
  );

  assert.match(
    body,
    /catch \(e\) \{\s*clearServerStopIntent\(\);\s*throw e;\s*\}/,
    "a failed stop keeps a marker it did not earn",
  );
});

test("an attached server is stopped, not only detached", async () => {
  const hook = USE_TAURI_BACKEND;
  const body = hook.slice(
    hook.indexOf("async function runStopServer()"),
    hook.indexOf("async function startInstall("),
  );

  assert.doesNotMatch(
    body,
    /isExternalServer\)/,
    "the stop branches on render state the tray handler never sees",
  );
  const invoke = body.indexOf('await invoke("stop_server"');
  const detach = body.indexOf("setExternalServerPort(null);");
  assert.ok(
    invoke > 0 && detach > invoke,
    "the app lets go of an attached server without stopping it",
  );
  assert.match(
    body.slice(detach),
    /stopExternalServerPoll\(\);\s*setBackendStatus\("stopped"\);/,
  );
});

test("a second stop cannot run while the first is in flight", async () => {
  const hook = USE_TAURI_BACKEND;

  const tray = hook.slice(hook.indexOf('register<void>("tray-toggle-server"'));
  assert.match(
    tray.slice(0, tray.indexOf("retry();")),
    /statusRef\.current === "running"\)\s*\{\s*stopServer\(\)/,
  );

  const guard = hook.slice(
    hook.indexOf("async function stopServer()"),
    hook.indexOf("async function runStopServer()"),
  );

  assert.match(
    guard,
    /if \(stoppingRef\.current\) return;\s*stoppingRef\.current = true;/,
    "a second stop still runs while the first is in flight",
  );
  assert.match(
    guard,
    /finally \{\s*stoppingRef\.current = false;\s*\}/,
    "a failed stop strands the guard and no later stop can run",
  );
});

test("every deliberate start drops the marker", async () => {
  const hook = USE_TAURI_BACKEND;

  const managed = hook.slice(
    hook.indexOf("async function startManagedServer()"),
    hook.indexOf("async function startRepair()"),
  );
  const clear = managed.indexOf("clearServerStopIntent()");
  const guard = managed.indexOf("if (startingRef.current)");
  assert.ok(
    clear > 0 && guard > clear,
    "a re-entrant start returns with the marker still set",
  );

  const retry = hook.slice(
    hook.indexOf("const retry = useCallback"),
    hook.indexOf("const retryInstall"),
  );
  assert.match(retry, /clearServerStopIntent\(\);/);
  assert.match(retry, /checkInstallAndStart\(\);/);
});

test("a tray stop that fails tells the user why", () => {
  const hook = USE_TAURI_BACKEND;
  const tray = hook.slice(hook.indexOf('register<void>("tray-toggle-server"'));
  assert.match(
    tray.slice(0, tray.indexOf("retry();")),
    /stopServer\(\)\.catch\(\(e\) => \{\s*toast\.error\([^)]*String\(e\)/,
    "the tray drops the reason a stop failed",
  );
});

// The tray listener is registered once at mount, so run the real runStopServer with that
// render's state: not attached, whatever the app is attached to now.
function stopFromMountTimeListener(port: number, stopError?: Error) {
  const hook = USE_TAURI_BACKEND;
  const start = hook.indexOf("  async function runStopServer()");
  const body = hook.slice(start, hook.indexOf("\n  }\n", start) + 4);
  const calls: string[] = [];
  const scope: Record<string, unknown> = {
    isExternalServer: false,
    externalServerPort: null,
    portRef: { current: port },
    startingRef: { current: true },
    importTauriCore: () =>
      Promise.resolve({
        invoke: (command: string, args: { port: number }) => {
          calls.push(`${command}:${args.port}`);
          return stopError ? Promise.reject(stopError) : Promise.resolve(null);
        },
      }),
    setExternalServerPort: (next: number | null) => calls.push(`attached:${next}`),
    stopExternalServerPoll: () => calls.push("stop-poll"),
    markServerStopIntent: () => calls.push("mark-intent"),
    clearServerStopIntent: () => calls.push("clear-intent"),
    setBackendStatus: (status: string) => calls.push(`status:${status}`),
  };
  const source = `${body.replace('await import("@tauri-apps/api/core")', "await importTauriCore()")}
    return runStopServer;`;
  const keys = Object.keys(scope);
  const run = new Function(...keys, source)(...keys.map((key) => scope[key])) as () => Promise<void>;
  return { run, calls };
}

test("the tray's stop on an attached server stops it by port, then leaves attached mode", async () => {
  const stop = stopFromMountTimeListener(8890);
  await stop.run();
  assert.deepEqual(stop.calls, [
    "mark-intent",
    "stop_server:8890",
    "attached:null",
    "stop-poll",
    "status:stopped",
  ]);
});

test("a stop the server refuses keeps the app attached and its health poll running", async () => {
  const stop = stopFromMountTimeListener(8890, new Error("did not stop"));
  await assert.rejects(stop.run(), /did not stop/);
  assert.deepEqual(stop.calls, ["mark-intent", "stop_server:8890", "clear-intent"]);
});