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.

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

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

import type {
  SandboxCapability,
  SandboxSetupJob,
} from "../src/features/chat/api/sandbox-capability.ts";
import type { SandboxStatus } from "../src/features/settings/api/sandbox-isolation.ts";
import {
  setupRowView,
} from "../src/features/settings/tabs/sandbox-tab-state.ts";
import * as tabState from "../src/features/settings/tabs/sandbox-tab-state.ts";
import { readFileSync } from "node:fs";
import {
  loadWithStubs,
  stubJsxRuntime,
  type StubElement,
} from "./helpers/module-stubs.ts";

type Call = { url: string; init?: RequestInit };

type CapabilityApi = {
  loadSandboxCapability: (options?: {
    force?: boolean;
  }) => Promise<SandboxCapability | null>;
  forgetSandboxCapability: () => void;
  cachedSandboxCapability: () => SandboxCapability | null;
  capabilityFromApi: (body: Record<string, unknown>) => SandboxCapability;
  sandboxReady: (capability: SandboxCapability) => boolean;
  startSandboxSetup: (
    operation: string,
    options: { consentDaclFallback?: boolean },
    fallback: string,
  ) => Promise<SandboxSetupJob>;
  loadSandboxSetup: (fallback: string) => Promise<SandboxSetupJob>;
  loadSettledSandboxCapability: (options?: {
    attempts?: number;
    delayMs?: number;
  }) => Promise<SandboxCapability | null>;
};

const json = (body: unknown, status = 200) =>
  new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/json" },
  });

function loadCapabilityApi(
  respond: (call: Call) => Response | Promise<Response>,
) {
  const calls: Call[] = [];
  const api = loadWithStubs<CapabilityApi>(
    new URL("../src/features/chat/api/sandbox-capability.ts", import.meta.url),
    {
      "@/features/auth": {
        authFetch: async (url: string, init?: RequestInit) => {
          const call = { url, init };
          calls.push(call);
          return respond(call);
        },
      },
      "@/lib/format-fastapi-error": {
        readFastApiError: async (response: Response, fallback: string) => {
          const body = (await response.json().catch(() => null)) as {
            detail?: string;
          } | null;
          return body?.detail ?? fallback;
        },
      },
    },
  );
  return { api, calls };
}

const LINUX_UNAVAILABLE = {
  python_os_isolated: false,
  terminal_os_isolated: false,
  backend: "bubblewrap",
  platform: "linux",
  reason: "bwrap: setting up uid map: Permission denied",
  setup_action: "linux-install",
  manual_command: "apt-get install -y apparmor-profiles",
  can_run_setup: true,
};

test("the capability maps to camelCase and is cached between picker opens", async () => {
  const { api, calls } = loadCapabilityApi(() => json(LINUX_UNAVAILABLE));
  const first = await api.loadSandboxCapability();
  assert.deepEqual(first, {
    pythonOsIsolated: false,
    terminalOsIsolated: false,
    backend: "bubblewrap",
    platform: "linux",
    reason: "bwrap: setting up uid map: Permission denied",
    setupAction: "linux-install",
    manualCommand: "apt-get install -y apparmor-profiles",
    canRunSetup: true,
    setupBlocked: null,
    needsConsent: false,
  });
  await api.loadSandboxCapability();
  assert.equal(calls.length, 1);
  await api.loadSandboxCapability({ force: true });
  assert.equal(calls.length, 2);
  assert.equal(calls[1].url, "/api/sandbox/capability?refresh=1");
  assert.equal(api.sandboxReady(first as SandboxCapability), false);
});

test("an older server (404) or a failed check leaves the capability unknown", async () => {
  for (const response of [json({ detail: "Not Found" }, 404), json({}, 500)]) {
    const { api } = loadCapabilityApi(() => response);
    assert.equal(await api.loadSandboxCapability(), null);
  }
  const { api } = loadCapabilityApi(() => {
    throw new Error("offline");
  });
  assert.equal(await api.loadSandboxCapability(), null);
});

test("a setup the server did not name cannot be run, whatever the flag says", async () => {
  const { api } = loadCapabilityApi(() =>
    json({
      ...LINUX_UNAVAILABLE,
      setup_action: "curl-bash",
      can_run_setup: true,
    }),
  );
  const capability = await api.loadSandboxCapability();
  assert.equal(capability?.setupAction, null);
  assert.equal(capability?.canRunSetup, false);
});

test("starting a setup sends only the operation and the consent", async () => {
  const { api, calls } = loadCapabilityApi(() =>
    json({
      id: "s1",
      operation: "windows-setup",
      state: "running",
      output_tail: [],
    }),
  );
  const job = await api.startSandboxSetup(
    "windows-setup",
    { consentDaclFallback: true },
    "fallback",
  );
  assert.equal(calls[0].url, "/api/settings/sandbox/setup");
  assert.equal(calls[0].init?.method, "POST");
  assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {
    operation: "windows-setup",
    consent_dacl_fallback: true,
  });
  assert.equal(job.state, "running");
  assert.equal(job.operation, "windows-setup");
});

test("a refused setup surfaces the server's reason", async () => {
  const { api } = loadCapabilityApi(() =>
    json(
      { detail: "Set up the sandbox from the computer running Unsloth." },
      403,
    ),
  );
  await assert.rejects(
    api.startSandboxSetup("linux-install", {}, "fallback"),
    /computer running Unsloth/,
  );
});

test("Windows consent is asked only while the opt-in is off, and only of who can run it", async () => {
  const windows = {
    ...LINUX_UNAVAILABLE,
    platform: "win32",
    setup_action: "windows-setup",
    needs_consent: true,
  };
  for (const [body, expected] of [
    [windows, true],
    [{ ...windows, needs_consent: false }, false],
    [{ ...windows, can_run_setup: false }, false],
    [{ ...LINUX_UNAVAILABLE, needs_consent: true }, false],
  ] as const) {
    const { api } = loadCapabilityApi(() => json(body));
    assert.equal((await api.loadSandboxCapability())?.needsConsent, expected);
  }
});

test("the runtime-only operation is sent as is and the job note is kept", async () => {
  const { api, calls } = loadCapabilityApi(() =>
    json({
      id: "s2",
      operation: "windows-runtime",
      state: "failed",
      note: "a password is required",
      manual_command: "python install_mxc_prebuilt.py",
    }),
  );
  const job = await api.startSandboxSetup("windows-runtime", {}, "fallback");
  assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {
    operation: "windows-runtime",
    consent_dacl_fallback: false,
  });
  assert.equal(job.note, "a password is required");
  assert.equal(job.manualCommand, "python install_mxc_prebuilt.py");
});

test("a settled read waits out a check that has not answered yet, but not a real no", async () => {
  const pending = { ...LINUX_UNAVAILABLE, backend: "unknown" };
  const ready = {
    ...LINUX_UNAVAILABLE,
    python_os_isolated: true,
    terminal_os_isolated: true,
  };
  let n = 0;
  const { api, calls } = loadCapabilityApi(() =>
    json(n++ < 2 ? pending : ready),
  );
  const settled = await api.loadSettledSandboxCapability({ delayMs: 1 });
  assert.equal(calls.length, 3);
  assert.ok(calls.every((call) => call.url.endsWith("?refresh=1")));
  assert.equal(settled && api.sandboxReady(settled), true);

  const denied = loadCapabilityApi(() => json(LINUX_UNAVAILABLE));
  const no = await denied.api.loadSettledSandboxCapability({ delayMs: 1 });
  assert.equal(denied.calls.length, 1);
  assert.equal(no?.backend, "bubblewrap");

  const stuck = loadCapabilityApi(() => json(pending));
  await stuck.api.loadSettledSandboxCapability({ attempts: 2, delayMs: 1 });
  assert.equal(stuck.calls.length, 2);
});

type PickModule = typeof import("../src/features/chat/sandbox-pick.ts");

const pickModule = loadWithStubs<PickModule>(
  new URL("../src/features/chat/sandbox-pick.ts", import.meta.url),
  {
    "./api/sandbox-capability": {
      loadSettledSandboxCapability: async () => null,
      cachedSandboxCapability: () => null,
      sandboxReady: (c: SandboxCapability) =>
        c.pythonOsIsolated && c.terminalOsIsolated,
      capabilityPending: (c: SandboxCapability) =>
        c.backend === "unknown" &&
        !(c.pythonOsIsolated && c.terminalOsIsolated),
    },
  },
);

function deferred<T>() {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((r) => {
    resolve = r;
  });
  return { promise, resolve };
}

test("switching to Low applies at once and reads nothing", async () => {
  const applied: string[] = [];
  await pickModule.pickSandboxLevel(
    "low",
    (level) => applied.push(level),
    () => assert.fail("no popup for Low"),
    async () => assert.fail("no read for Low"),
  );
  assert.deepEqual(applied, ["low"]);
});

test("switching to High with a working OS sandbox applies it; a known one skips the read", async () => {
  const applied: string[] = [];
  let reads = 0;
  await pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => assert.fail("no popup"),
    async () => {
      reads++;
      return null;
    },
    () => capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
  );
  await pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => assert.fail("no popup"),
    async () => capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
  );
  assert.deepEqual(applied, ["high", "high"]);
  assert.equal(reads, 0);
});

test("switching to High without an OS sandbox opens the popup instead of applying", async () => {
  const applied: string[] = [];
  let popups = 0;
  await pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => popups++,
    async () => capability({ pythonOsIsolated: true }),
  );
  assert.deepEqual(applied, []);
  assert.equal(popups, 1);
});

test("an answer still unknown applies High; the backend still checks every call", async () => {
  const applied: string[] = [];
  await pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => assert.fail("no popup while unknown"),
    async () => capability({ pythonOsIsolated: true, backend: "unknown" }),
  );
  await pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => assert.fail("no popup for an older server"),
    async () => null,
  );
  assert.deepEqual(applied, ["high", "high"]);
});

test("a switch made while a High check is in flight wins over that check", async () => {
  const applied: string[] = [];
  let popups = 0;
  const read = deferred<SandboxCapability | null>();
  const pending = pickModule.pickSandboxLevel(
    "high",
    (level) => applied.push(level),
    () => popups++,
    () => read.promise,
  );
  await pickModule.pickSandboxLevel("low", (level) => applied.push(level), () => popups++);
  read.resolve(capability({ pythonOsIsolated: false }));
  await pending;
  assert.deepEqual(applied, ["low"]);
  assert.equal(popups, 0);
});

type SetupState = typeof import("../src/features/chat/sandbox-setup-state.ts");

const setupState = loadWithStubs<SetupState>(
  new URL("../src/features/chat/sandbox-setup-state.ts", import.meta.url),
  { "@/features/settings": tabState },
);

const capability = (
  overrides: Partial<SandboxCapability> = {},
): SandboxCapability => ({
  pythonOsIsolated: false,
  terminalOsIsolated: false,
  backend: "bubblewrap",
  platform: "linux",
  reason: "denied",
  setupAction: "linux-install",
  manualCommand: "apt-get install -y bubblewrap",
  canRunSetup: true,
  setupBlocked: null,
  needsConsent: false,
  ...overrides,
});

const setupJob = (
  overrides: Partial<SandboxSetupJob> = {},
): SandboxSetupJob => ({
  id: "s1",
  operation: "linux-install",
  state: "running",
  startedAt: 1,
  finishedAt: null,
  exitCode: null,
  outputTail: [],
  steps: [],
  manualCommand: "",
  note: "",
  ...overrides,
});

test("the dialog shows a check in progress before the capability arrives", () => {
  const view = setupState.sandboxSetupView({
    capability: null,
    job: null,
    consent: false,
  });
  assert.equal(view.checking, true);
  assert.equal(view.install, null);
  assert.equal(view.command, "");
});

test("the owner on Linux gets Install sandbox and the command", () => {
  const view = setupState.sandboxSetupView({
    capability: capability(),
    job: null,
    consent: false,
  });
  assert.equal(view.install, "linux");
  assert.equal(view.installDisabled, false);
  assert.equal(view.showConsent, false);
  assert.equal(view.command, "apt-get install -y bubblewrap");
  assert.equal(view.showOwnerOnly, false);
});

test("Windows needs the MXC consent before the setup can start", () => {
  const windows = capability({
    platform: "win32",
    backend: "mxc-processcontainer",
    setupAction: "windows-setup",
    manualCommand: "",
    needsConsent: true,
  });
  const without = setupState.sandboxSetupView({
    capability: windows,
    job: null,
    consent: false,
  });
  assert.equal(without.install, "windows");
  assert.equal(without.showConsent, true);
  assert.equal(without.installDisabled, true);
  assert.equal(without.command, "");
  const withConsent = setupState.sandboxSetupView({
    capability: windows,
    job: null,
    consent: true,
  });
  assert.equal(withConsent.installDisabled, false);
});

test("someone who cannot run the setup gets the command and who can", () => {
  const view = setupState.sandboxSetupView({
    capability: capability({ canRunSetup: false }),
    job: null,
    consent: false,
  });
  assert.equal(view.install, null);
  assert.equal(view.showOwnerOnly, true);
  const macos = setupState.sandboxSetupView({
    capability: capability({
      platform: "darwin",
      setupAction: null,
      canRunSetup: false,
      manualCommand: "",
    }),
    job: null,
    consent: false,
  });
  assert.equal(macos.showOwnerOnly, false);
  assert.equal(macos.install, null);
});

test("another account on Windows gets the owner note without the host's paths", () => {
  const view = setupState.sandboxSetupView({
    capability: capability({
      platform: "win32",
      setupAction: null,
      canRunSetup: false,
      manualCommand: "",
      setupBlocked: "not_owner",
    }),
    job: null,
    consent: false,
  });
  assert.equal(view.command, "");
  assert.equal(view.showOwnerOnly, true);
});

test("the owner here without a way to ask for the password is told to run the command", () => {
  const view = setupState.sandboxSetupView({
    capability: capability({
      canRunSetup: false,
      setupAction: null,
      setupBlocked: "no_elevation",
    }),
    job: null,
    consent: false,
  });
  assert.equal(view.install, null);
  assert.equal(view.showOwnerOnly, false);
  assert.equal(view.showRunInTerminal, true);
  const { api } = loadCapabilityApi(() => json({}));
  assert.equal(
    api.capabilityFromApi({ setup_blocked: "no_elevation" }).setupBlocked,
    "no_elevation",
  );
  assert.equal(
    api.capabilityFromApi({ setup_blocked: "other" }).setupBlocked,
    null,
  );
});

test("a running job disables the button; a failure shows its output and command", () => {
  const running = setupState.sandboxSetupView({
    capability: capability(),
    job: setupJob(),
    consent: false,
  });
  assert.equal(running.running, true);
  assert.equal(running.installDisabled, true);
  const failed = setupState.sandboxSetupView({
    capability: capability(),
    job: setupJob({
      state: "failed",
      exitCode: 100,
      outputTail: ["", "E: Unable to locate package bubblewrap"],
      manualCommand: "apt-get update && apt-get install -y bubblewrap",
    }),
    consent: false,
  });
  assert.equal(failed.result, "failed");
  assert.deepEqual(failed.outputLines, [
    "E: Unable to locate package bubblewrap",
  ]);
  assert.equal(
    failed.command,
    "apt-get update && apt-get install -y bubblewrap",
  );
  const declined = setupState.sandboxSetupView({
    capability: capability(),
    job: setupJob({ state: "declined", exitCode: 126 }),
    consent: false,
  });
  assert.equal(declined.result, "declined");
  assert.equal(declined.command, "apt-get install -y bubblewrap");
});

test("a failed check shows Retry instead of an endless spinner", () => {
  const view = setupState.sandboxSetupView({
    capability: null,
    job: null,
    consent: false,
    loadFailed: true,
  });
  assert.equal(view.checking, false);
  assert.equal(view.loadFailed, true);
  assert.equal(view.install, null);
});

test("Windows skips the consent once the opt-in is on (after a reboot, only preparation)", () => {
  const view = setupState.sandboxSetupView({
    capability: capability({
      platform: "win32",
      setupAction: "windows-setup",
      needsConsent: false,
    }),
    job: null,
    consent: false,
  });
  assert.equal(view.install, "windows");
  assert.equal(view.showConsent, false);
  assert.equal(view.installDisabled, false);
});

test("the server's note shows for a declined or failed setup only", () => {
  const note = "Not authorized, or no authentication agent";
  for (const [state, shown] of [
    ["failed", note],
    ["declined", note],
    ["running", ""],
    ["succeeded", ""],
  ] as const) {
    const view = setupState.sandboxSetupView({
      capability: capability(),
      job: setupJob({ state, note }),
      consent: false,
    });
    assert.equal(view.note, shown, state);
  }
});

const status = (overrides: Partial<SandboxStatus> = {}): SandboxStatus => ({
  platform: "linux",
  python: {
    backend: "bubblewrap",
    available: false,
    reason: "missing",
    limitations: [],
    protectionState: null,
    remediation: "",
  },
  terminal: {
    backend: "bubblewrap",
    available: false,
    reason: "missing",
    limitations: [],
    protectionState: null,
    remediation: "",
  },
  terminalShell: "bash",
  windows: null,
  memory: null,
  setup: {
    action: "linux-install",
    elevation: "sudo",
    manualCommand: "apt-get install -y bubblewrap",
    reason: "bubblewrap is not installed",
    canRun: true,
  },
  checkedAt: 1,
  ...overrides,
});

test("Linux shows Install sandbox with the command; a remote owner only the command", () => {
  const row = setupRowView(status(), null);
  assert.equal(row.show, true);
  assert.equal(row.showInstall, true);
  assert.equal(row.command, "apt-get install -y bubblewrap");
  const remote = setupRowView(
    status({ setup: { ...status().setup!, canRun: false } }),
    null,
  );
  assert.equal(remote.showInstall, false);
  assert.equal(remote.command, "apt-get install -y bubblewrap");
});

test("a working Linux sandbox, an older server and Windows hide the row", () => {
  assert.equal(
    setupRowView(
      status({
        setup: {
          action: null,
          elevation: null,
          manualCommand: "",
          reason: "",
          canRun: false,
        },
      }),
      null,
    ).show,
    false,
  );
  assert.equal(setupRowView(status({ setup: null }), null).show, false);
  assert.equal(setupRowView(status({ platform: "win32" }), null).show, false);
});

test("macOS explains Seatbelt instead of offering an install, and only when it fails", () => {
  const failing = setupRowView(
    status({ platform: "darwin", setup: null }),
    null,
  );
  assert.equal(failing.show, true);
  assert.equal(failing.builtIn, true);
  assert.equal(failing.showInstall, false);
  assert.equal(failing.reason, "missing");
  const working = status({ platform: "darwin", setup: null });
  working.python.available = true;
  working.terminal.available = true;
  assert.equal(setupRowView(working, null).show, false);
});

test("a failed install shows the job's command; a running one keeps the button", () => {
  const failed = setupRowView(
    status(),
    { ...setupJob({ state: "failed" }) },
    "apt-get update && apt-get install -y bubblewrap",
  );
  assert.equal(
    failed.command,
    "apt-get update && apt-get install -y bubblewrap",
  );
  const running = setupRowView(
    status({ setup: { ...status().setup!, canRun: false, manualCommand: "" } }),
    setupJob(),
  );
  assert.equal(running.show, true);
  assert.equal(running.showInstall, true);
  assert.equal(running.installDisabled, true);
});

test("an older capability read that finishes last never replaces a newer one", async () => {
  const replies: Array<(response: Response) => void> = [];
  const { api } = loadCapabilityApi(
    () => new Promise<Response>((resolve) => replies.push(resolve)),
  );
  const older = api.loadSandboxCapability();
  const newer = api.loadSandboxCapability({ force: true });
  await new Promise((resolve) => setTimeout(resolve, 0));
  replies[1](
    json({
      ...LINUX_UNAVAILABLE,
      python_os_isolated: true,
      terminal_os_isolated: true,
    }),
  );
  await newer;
  replies[0](json(LINUX_UNAVAILABLE));
  await older;
  assert.equal(api.cachedSandboxCapability()?.pythonOsIsolated, true);
  const stale = api.loadSandboxCapability({ force: true });
  await new Promise((resolve) => setTimeout(resolve, 0));
  api.forgetSandboxCapability();
  replies[2](json(LINUX_UNAVAILABLE));
  await stale;
  assert.equal(api.cachedSandboxCapability(), null);
});

function sandboxPopup(capabilityNow: SandboxCapability | null) {
  const levels: string[] = [];
  const opened: [string, unknown][] = [];
  const state = { sandboxLevel: "low", setSandboxLevel: (level: string) => levels.push(level) };
  const store = Object.assign(
    (selector: (s: unknown) => unknown) => selector(state),
    { getState: () => state },
  );
  const dialog = loadWithStubs<{
    SandboxSetupDialog: (props: {
      open: boolean;
      onOpenChange: (open: boolean) => void;
    }) => StubElement;
  }>(new URL("../src/features/chat/sandbox-setup-dialog.tsx", import.meta.url), {
    "react/jsx-runtime": stubJsxRuntime(),
    react: {
      // The capability read has answered.
      useState: (initial: unknown) => [initial === null ? capabilityNow : initial, () => {}],
      useRef: (current: unknown) => ({ current }),
      useEffect: () => {},
      useCallback: (fn: unknown) => fn,
    },
    sonner: { toast: { success() {}, error() {} } },
    zustand: {
      create: (init: (set: unknown) => unknown) => {
        const value = init(() => {});
        return Object.assign((selector: (s: unknown) => unknown) => selector(value), {
          getState: () => value,
        });
      },
    },
    "@/components/ui/alert-dialog": {
      AlertDialog: "AlertDialog",
      AlertDialogContent: "AlertDialogContent",
      AlertDialogDescription: "AlertDialogDescription",
      AlertDialogFooter: "AlertDialogFooter",
      AlertDialogHeader: "AlertDialogHeader",
      AlertDialogTitle: "AlertDialogTitle",
    },
    "@/components/ui/button": { Button: "Button" },
    "@/components/ui/checkbox": { Checkbox: "Checkbox" },
    "@/components/ui/spinner": { Spinner: "Spinner" },
    "@/features/settings": {
      useSettingsDialogStore: (selector: (s: unknown) => unknown) =>
        selector({
          openDialog: (tab: string, options?: { scrollTarget?: string }) => {
            opened.push([tab, options?.scrollTarget]);
          },
        }),
    },
    "@/i18n": { useT: () => (key: string) => key },
    "@/lib/copy-to-clipboard": { copyToClipboard: async () => true },
    "./api/sandbox-capability": {
      forgetSandboxCapability() {},
      loadSandboxSetup: async () => setupJob({ state: "idle" as never }),
      loadSettledSandboxCapability: async () => capabilityNow,
      sandboxReady: (c: SandboxCapability) => c.pythonOsIsolated && c.terminalOsIsolated,
      startSandboxSetup: async () => setupJob(),
    },
    "./sandbox-setup-state": setupState,
    "./stores/chat-runtime-store": { useChatRuntimeStore: store },
  });
  const render = () => {
    const closes: boolean[] = [];
    const root = dialog.SandboxSetupDialog({
      open: true,
      onOpenChange: (open) => closes.push(open),
    });
    const inner = root.props.children as StubElement;
    const content = (inner.type as (p: unknown) => StubElement)(inner.props);
    const all: StubElement[] = [];
    const walk = (node: unknown) => {
      if (Array.isArray(node)) return node.forEach(walk);
      if (node && typeof node === "object" && "props" in node) {
        all.push(node as StubElement);
        walk((node as StubElement).props.children);
      }
    };
    walk(content);
    const text = (el: StubElement) =>
      ([] as unknown[]).concat(el.props.children).filter((c) => typeof c === "string").join("");
    const button = (key: string) => {
      const hit = all.find((el) => el.type === "Button" && text(el) === key);
      assert.ok(hit, `no ${key} button`);
      return hit.props.onClick as () => void;
    };
    const title = all.find((el) => el.type === "AlertDialogTitle");
    return { closes, button, title: title ? text(title) : "", texts: all.map(text) };
  };
  return { render, levels, opened };
}

test("the High popup names the missing OS sandbox and offers Install, Learn more and Use Low", async () => {
  const popup = sandboxPopup(capability());
  const view = popup.render();
  assert.equal(view.title, "sandboxSetup.levelTitle");
  view.button("sandboxSetup.install");
  view.button("sandboxSetup.copyCommand");
  assert.ok(!view.texts.includes("sandboxSetup.useAnyway"));

  view.button("sandboxSetup.useLow")();
  assert.deepEqual(popup.levels, ["low"]);
  assert.deepEqual(view.closes, [false]);

  const other = popup.render();
  other.button("settings.sandbox.learnMore")();
  await new Promise((resolve) => setTimeout(resolve, 5));
  assert.deepEqual(other.closes, [false]);
  // #13656: the OS sandbox status and setup, not Permissions, where High was just picked.
  assert.deepEqual(popup.opened, [["sandbox", "sandbox-os"]]);
});

test("the High popup stays short: no probe reason, no command block, a one-line Windows note", () => {
  const noElevation = sandboxPopup(
    capability({ canRunSetup: false, setupAction: null, setupBlocked: "no_elevation" }),
  ).render();
  noElevation.button("sandboxSetup.copyCommand");
  for (const verbose of ["denied", "apt-get install -y bubblewrap", "sandboxSetup.runInTerminal", "sandboxSetup.commandHint"]) {
    assert.ok(!noElevation.texts.includes(verbose), `popup shows ${verbose}`);
  }

  const windows = sandboxPopup(
    capability({ platform: "windows", backend: "mxc-processcontainer", setupAction: "windows-setup", needsConsent: true }),
  ).render();
  windows.button("sandboxSetup.windowsSetup");
  assert.ok(windows.texts.includes("sandboxSetup.windowsNote"));
  assert.ok(!windows.texts.includes("settings.sandbox.disclosure"));
});

test("with nothing to install, the High popup says why instead of showing nothing", () => {
  // #13656: Windows with MXC allowed and prepared but failing its check, ARM64, or a pre-24H2 build.
  const reason = "MXC probe failed: the container did not start";
  const deadEnd = capability({
    platform: "win32",
    backend: "mxc-processcontainer",
    reason,
    setupAction: null,
    manualCommand: "",
    canRunSetup: false,
  });
  const view = setupState.sandboxSetupView({ capability: deadEnd, job: null, consent: false });
  assert.equal(view.install, null);
  assert.equal(view.command, "");
  assert.equal(view.showOwnerOnly, false);
  assert.equal(view.reason, reason);
  assert.ok(sandboxPopup(deadEnd).render().texts.includes(reason));

  for (const offers of [
    capability(),
    capability({ canRunSetup: false, setupAction: null, setupBlocked: "no_elevation" }),
    capability({ platform: "win32", setupAction: null, canRunSetup: false, manualCommand: "", setupBlocked: "not_owner" }),
  ]) {
    assert.equal(
      setupState.sandboxSetupView({ capability: offers, job: null, consent: false }).reason,
      "",
    );
  }
  const readyNow = { ...deadEnd, pythonOsIsolated: true, terminalOsIsolated: true, reason: "passed" };
  assert.equal(
    setupState.sandboxSetupView({ capability: readyNow, job: null, consent: false }).reason,
    "",
  );
  for (const state of ["running", "failed"] as const) {
    assert.equal(
      setupState.sandboxSetupView({ capability: deadEnd, job: setupJob({ state }), consent: false }).reason,
      "",
    );
  }
});

test("an install that makes the OS sandbox pass turns High on", () => {
  const source = readFileSync(
    new URL("../src/features/chat/sandbox-setup-dialog.tsx", import.meta.url),
    "utf8",
  );
  const finish = source.slice(source.indexOf("const finish = useCallback("), source.indexOf("useEffect(() => {\n    if (job?.state"));
  assert.match(finish, /if \(next && sandboxReady\(next\)\) \{\s*if \(useChatRuntimeStore\.getState\(\)\.sandboxLevel === levelAtOpen\.current\) \{\s*setSandboxLevel\("high"\);/);
  assert.doesNotMatch(source, /setPermissionMode/);
});