Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

55.9 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "@/lib/i18n";
import { waitForLocalVmReady } from "@/lib/local-vm-readiness";
import type { LocaleKey } from "@/locales";
import {
  AlertTriangle,
  Check,
  Cloud,
  Loader2,
  Moon,
  RotateCcw,
  Square,
  Trash2,
} from "lucide-react";
import { SettingsSkeletonRows } from "./settings/SettingsStates";
import { Card, CommandLine, LearnMore, SETTINGS_INLINE_INPUT, Segmented, StatusDot } from "./SettingsPrimitives";
import { MacLocalControl } from "./MacLocalControl";
import { Select } from "./Select";
import { cn } from "@/lib/cn";
import { localizeComputerProblem } from "@/lib/computer-messages";
import { computerInventoryRequest, jsonPostRequest, type ComputerApiRequest } from "@/lib/computer-requests";
import { useStore } from "@/state/store";
import { VpsComputersCard } from "./VpsComputersCard"; import { KeysLink } from "./keys/KeysLink"; import { serverFetch } from "@/lib/relay-server";

type Action = "pull" | "run" | "start" | "stop" | "remove" | "recreate";

interface Status {
  platform: string;
  runtime: string | null;
  available: string[];
  daemonUp: boolean;
  image: boolean;
  imageMatches: boolean;
  managed: boolean;
  container: "running" | "stopped" | "missing";
  network: "loopback" | "unsafe" | "unknown";
  security: "hardened" | "unsafe" | "unknown";
  persistence: "durable" | "unsafe" | "unknown";
  desktopReady: boolean;
  ready: boolean;
  problem: string | null;
  image_ref: string;
  base_image_ref: string;
  driver_version: string;
  container_name: string;
  workspace_path: string;
  workspace_guest_path: string;
  viewer_url: string;
  idle_timeout_ms: number;
  stop_reason?: "idle" | null;
  mode: "shared" | "per-bot" | "pool";
  max_instances: number;
  commands: {
    install: string | null;
    runtimeStart: string | null;
    pull: string | null;
    run: string | null;
    start: string | null;
    stop: string | null;
    remove: string | null;
    view: string;
  };
}

export interface LocalVmInventoryInstance {
  botId: string;
  name: string;
  destination: "auto" | "cloud" | "vm" | "local" | "browser" | "off";
  container: "running" | "stopped";
  ready: boolean;
  managed: boolean;
  problem: string | null;
  inUse: boolean;
}

interface LocalVmInventoryPayload {
  instances: LocalVmInventoryInstance[];
  maxInstances: number;
  available: boolean;
  problem: string | null;
}

export interface CloudComputerInventoryInstance {
  boxId: string;
  name: string;
  state: string;
  ownerBotId: string | null;
  ownerName: string | null;
  orphaned: boolean;
  inUse: boolean;
}

export interface CloudComputerInventoryPayload {
  configured: boolean;
  available: boolean;
  problem: string | null;
  instances: CloudComputerInventoryInstance[];
}

type CloudAction = "sleep" | "delete";
type PendingCloudAction = { boxId: string; action: CloudAction } | null;
export type CloudPostActionOverride = "deleted" | "deleting" | "sleeping";
export type CloudPostActionOverrides = Record<string, CloudPostActionOverride>;

const PENDING_CLOUD_DELETE_REFRESH_DELAYS_MS = [1_000, 2_000, 4_000] as const;

function waitForCloudDeleteRefresh(delayMs: number): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, delayMs));
}

export interface VpsComputerInventoryInstance {
  name: string;
  state: "created" | "restarting" | "running" | "removing" | "paused" | "exited" | "dead" | "unknown";
  /** The SSH alias whose host holds this computer. */
  vpsAlias: string;
  ownerBotId: string | null;
  ownerName: string | null;
  orphaned: boolean;
  inUse: boolean;
}

interface VpsComputerInventoryPayload {
  configured: boolean;
  available: boolean;
  /** The default alias first, then each bot's own. */
  vpsAliases: string[];
  problem: string | null;
  instances: VpsComputerInventoryInstance[];
}

const destinationLabelKeys: Record<LocalVmInventoryInstance["destination"], LocaleKey> = {
  auto: "vm.dest.auto",
  cloud: "place.cloud",
  vm: "vm.dest.vm",
  local: "vm.dest.local",
  browser: "vm.dest.browser",
  off: "vm.dest.off",
};

export type ComputerStateKind =
  | "unmanaged"
  | "in-use"
  | "stopped"
  | "running"
  | "attention"
  | "sleeping"
  | "going-to-sleep"
  | "starting"
  | "restarting"
  | "removing"
  | "paused";

const stateLabelKeys: Record<ComputerStateKind, LocaleKey> = {
  unmanaged: "vm.state.notManaged",
  "in-use": "vm.state.inUse",
  stopped: "vm.state.stopped",
  running: "vm.state.running",
  attention: "vm.state.attention",
  sleeping: "vm.state.sleeping",
  "going-to-sleep": "vm.state.goingToSleep",
  starting: "vm.state.starting",
  restarting: "vm.state.restarting",
  removing: "vm.state.removing",
  paused: "vm.state.paused",
};

export function computerStateLabel(kind: ComputerStateKind): string {
  return t(stateLabelKeys[kind]);
}

export function localVmInventoryStateKind(instance: LocalVmInventoryInstance): ComputerStateKind {
  if (!instance.managed) return "unmanaged";
  if (instance.inUse) return "in-use";
  if (instance.container === "stopped") return "stopped";
  if (instance.ready) return "running";
  return "attention";
}

export function localVmInventoryState(instance: LocalVmInventoryInstance): string {
  return computerStateLabel(localVmInventoryStateKind(instance));
}

export function cloudComputerInventoryStateKind(
  instance: CloudComputerInventoryInstance,
): ComputerStateKind {
  if (instance.inUse) return "in-use";
  if (instance.state === "removing") return "removing";
  if (instance.state === "archived") return "sleeping";
  if (instance.state === "archiving") return "going-to-sleep";
  if (["idle", "ready", "running"].includes(instance.state)) return "running";
  if (["init", "provisioning", "provisioned", "cloning"].includes(instance.state)) return "starting";
  return "attention";
}

export function cloudComputerInventoryState(instance: CloudComputerInventoryInstance): string {
  return computerStateLabel(cloudComputerInventoryStateKind(instance));
}

/** Boat's account LIST is eventually consistent: an older snapshot must not undo an action the provider accepted. */
export function reconcileCloudInventorySnapshot(
  incoming: CloudComputerInventoryInstance[],
  previous: CloudComputerInventoryInstance[],
  overrides: CloudPostActionOverrides,
): { instances: CloudComputerInventoryInstance[]; overrides: CloudPostActionOverrides } {
  const nextOverrides = { ...overrides };
  const incomingIds = new Set(incoming.map((instance) => instance.boxId));
  const instances = incoming.flatMap((instance) => {
    const override = overrides[instance.boxId];
    if (override === "deleted") return [];
    if (override === "deleting") return [{ ...instance, state: "removing" }];
    if (override !== "sleeping") return [instance];
    if (instance.state === "archived") {
      delete nextOverrides[instance.boxId];
      return [instance];
    }
    return [{ ...instance, state: "archived" }];
  });

  // A transitioning Boat can briefly disappear from LIST.
  for (const instance of previous) {
    if (overrides[instance.boxId] !== "sleeping" || incomingIds.has(instance.boxId)) continue;
    instances.push({ ...instance, state: "archived" });
  }
  for (const [boxId, override] of Object.entries(overrides)) {
    if ((override === "deleted" || override === "deleting") && !incomingIds.has(boxId)) {
      delete nextOverrides[boxId];
    }
  }
  return { instances, overrides: nextOverrides };
}

/** An empty list proves deletion only when Boat says the read was authoritative. */
export function reconcileCloudInventoryPayload(
  payload: CloudComputerInventoryPayload,
  previous: CloudComputerInventoryInstance[],
  overrides: CloudPostActionOverrides,
): { instances: CloudComputerInventoryInstance[]; overrides: CloudPostActionOverrides } {
  if (payload.configured !== true || payload.available !== true) {
    return { instances: previous, overrides: { ...overrides } };
  }
  return reconcileCloudInventorySnapshot(
    Array.isArray(payload.instances) ? payload.instances : [],
    previous,
    overrides,
  );
}

function cloudComputerCanSleep(instance: CloudComputerInventoryInstance): boolean {
  return ["idle", "ready", "running"].includes(instance.state);
}

export function vpsComputerInventoryStateKind(
  instance: VpsComputerInventoryInstance,
): ComputerStateKind {
  if (instance.inUse) return "in-use";
  if (instance.state === "running") return "running";
  if (instance.state === "restarting") return "restarting";
  if (instance.state === "removing") return "removing";
  if (["created", "exited"].includes(instance.state)) return "stopped";
  if (instance.state === "paused") return "paused";
  return "attention";
}

export function vpsComputerInventoryState(instance: VpsComputerInventoryInstance): string {
  return computerStateLabel(vpsComputerInventoryStateKind(instance));
}

export function vpsComputerShortId(name: string): string {
  const suffix = /-([a-f0-9]{12})$/i.exec(name)?.[1];
  return suffix ? suffix.slice(-8).toLowerCase() : "unknown";
}

export interface ComputerActionPlan {
  confirmation: string | null;
  request: ComputerApiRequest;
}

export function perBotLocalVmDeletePlan(instance: LocalVmInventoryInstance): ComputerActionPlan {
  return {
    confirmation: t("vm.confirm.deleteBotVm", { name: instance.name }),
    request: jsonPostRequest(`/api/bots/${instance.botId}/local-computer/remove`, {}),
  };
}

export function cloudComputerActionPlan(
  action: CloudAction,
  instance: CloudComputerInventoryInstance,
): ComputerActionPlan {
  return {
    confirmation: action === "delete"
      ? t("vm.confirm.deleteCloud", {
          subject: instance.orphaned
            ? t("vm.confirm.orphanCloud")
            : t("vm.confirm.ownedCloud", { name: instance.ownerName ?? "" }),
        })
      : null,
    request: jsonPostRequest(
      `/api/computers/boxes/${encodeURIComponent(instance.boxId)}/${action}`,
      action === "delete" ? { confirmName: instance.name } : {},
    ),
  };
}

export function vpsComputerRemovePlan(instance: VpsComputerInventoryInstance): ComputerActionPlan {
  const shortId = vpsComputerShortId(instance.name);
  return {
    confirmation: t("vm.confirm.removeVps", {
      subject: instance.orphaned
        ? t("vm.confirm.orphanVps", { id: shortId })
        : t("vm.confirm.ownedVps", { name: instance.ownerName ?? "" }),
    }),
    request: jsonPostRequest(`/api/computers/vps/${encodeURIComponent(instance.name)}/remove`, {
      confirmName: instance.name,
      alias: instance.vpsAlias,
    }),
  };
}

export function confirmComputerAction(
  plan: ComputerActionPlan,
  confirm: (message: string) => boolean,
): ComputerApiRequest | null {
  if (plan.confirmation !== null && !confirm(plan.confirmation)) return null;
  return plan.request;
}

export function CloudComputersCard({
  instances,
  configured,
  loading,
  pending,
  error,
  unavailableReason,
  onRefresh,
  onSleep,
  onDelete,
}: {
  instances: CloudComputerInventoryInstance[];
  configured: boolean | null;
  loading: boolean;
  pending: PendingCloudAction;
  error: string | null;
  unavailableReason: string | null;
  onRefresh: () => void;
  onSleep: (instance: CloudComputerInventoryInstance) => void;
  onDelete: (instance: CloudComputerInventoryInstance) => void;
}) {
  return (
    <Card
      title={t("vm.cloud.title")}
      subtitle={t("vm.cloud.subtitle")}
    >
      <div className="flex items-center justify-between gap-3">
        <div className="text-[12px] text-ink-secondary">
          {configured === true
            ? t("vm.cloud.includesOrphans")
            : configured === false
              ? <>{t("vm.cloud.needsKey")} <KeysLink id="box" /></>
              : t("vm.cloud.refreshHint")}
        </div>
        <button
          type="button"
          onClick={onRefresh}
          disabled={loading || pending !== null}
          aria-label={t("vm.cloud.refreshAria")}
          className="settings-quiet -me-1.5 flex shrink-0 cursor-pointer items-center disabled:opacity-40"
        >
          {t("vm.refresh")}
        </button>
      </div>

      {error && <div role="alert" className="mt-2 text-[12px] leading-4 text-danger">{error}</div>}

      <p role="status" aria-live="polite" aria-atomic="true" className="sr-only">
        {loading
          ? t("vm.cloud.checking")
          : unavailableReason
            ? t("vm.cloud.unavailable", { reason: unavailableReason })
            : configured === false
              ? t("vm.cloud.notConnected")
              : instances.length === 1
                ? t("vm.cloud.foundOne")
                : t("vm.cloud.foundMany", { count: instances.length })}
      </p>

      {!(configured === false && !loading && !unavailableReason) && <div
        aria-busy={loading || pending !== null}
        className="mt-3 overflow-hidden rounded-xl border border-hairline/40"
      >
        {loading && instances.length === 0 ? (
          // Loading is two skeleton rows at their final height (§6.11), never a spinner.
          <div role="status" aria-label={t("vm.cloud.checkingList")} className="flex flex-col"><SettingsSkeletonRows /></div>
        ) : unavailableReason ? (
          <div className="flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary">
            <AlertTriangle size={14} className="shrink-0 text-warning" /> {unavailableReason}
          </div>
        ) : configured === false ? (
          <div className="flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary">
            <Cloud size={14} className="shrink-0" /> {t("vm.cloud.notConnected")}
          </div>
        ) : instances.length === 0 ? (
          <div className="px-3 py-4 text-[13px] text-ink-secondary">{t("vm.cloud.noneFound")}</div>
        ) : instances.map((instance, index) => {
          const kind = cloudComputerInventoryStateKind(instance);
          const state = computerStateLabel(kind);
          const isPending = pending?.boxId === instance.boxId;
          const canSleep = cloudComputerCanSleep(instance);
          const isRemoving = kind === "removing";
          return (
            <div
              key={instance.boxId}
              className={cn(
                "flex items-start justify-between gap-3 px-3 py-3",
                index > 0 && "border-t border-hairline/35",
              )}
            >
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="truncate text-[14px] font-medium text-ink">
                    {instance.orphaned ? t("vm.cloud.orphan") : instance.ownerName}
                  </span>
                  <span
                    className={cn(
                      "rounded-full px-2 py-0.5 text-[11px]",
                      instance.inUse || kind === "running"
                        ? "bg-success/15 text-success"
                        : kind === "sleeping" || kind === "going-to-sleep"
                          ? "bg-control text-ink-secondary"
                          : "bg-warning/15 text-warning",
                    )}
                  >
                    {state}
                  </span>
                </div>
                <div className="mt-1 break-all text-[12px] text-ink-secondary">
                  {instance.orphaned ? t("vm.owner.gone") : t("vm.owner.owned")} · {instance.name}
                </div>
                {instance.inUse && (
                  <div className="mt-1 text-[12px] text-ink-secondary">{t("vm.cloud.stopFirst")}</div>
                )}
              </div>
              <div className="flex shrink-0 items-center gap-1.5">
                <button
                  type="button"
                  onClick={() => onSleep(instance)}
                  disabled={loading || instance.inUse || pending !== null || !canSleep}
                  aria-busy={isPending && pending?.action === "sleep" ? true : undefined}
                  title={canSleep ? t("vm.cloud.sleepTitle") : t("vm.cloud.sleepBlocked", { state: state.toLowerCase() })}
                  className="flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:cursor-not-allowed disabled:opacity-40"
                >
                  {isPending && pending?.action === "sleep" ? <Loader2 size={12} className="animate-spin" /> : <Moon size={12} />}
                  {t("vm.cloud.sleep")}
                </button>
                <button
                  type="button"
                  onClick={() => onDelete(instance)}
                  disabled={loading || instance.inUse || pending !== null || isRemoving}
                  aria-busy={isPending && pending?.action === "delete" ? true : undefined}
                  title={t("vm.cloud.deleteTitle")}
                  className="flex items-center gap-1.5 rounded-lg bg-danger/10 px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40"
                >
                  {isPending && pending?.action === "delete" ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}
                  {t("common.delete")}
                </button>
              </div>
            </div>
          );
        })}
      </div>}
    </Card>
  );
}

export function LocalVmInventoryCard({
  instances,
  maxInstances,
  loading,
  deletingBotId,
  error,
  unavailableReason,
  onRefresh,
  onDelete,
}: {
  instances: LocalVmInventoryInstance[];
  maxInstances: number;
  loading: boolean;
  deletingBotId: string | null;
  error: string | null;
  unavailableReason: string | null;
  onRefresh: () => void;
  onDelete: (instance: LocalVmInventoryInstance) => void;
}) {
  return (
    <Card
      title={t("vm.perBot.title")}
      subtitle={t("vm.perBot.subtitle", {
        count: unavailableReason
          ? t("vm.perBot.inventoryUnavailable")
          : t("vm.perBot.created", { count: instances.length, max: maxInstances }),
      })}
    >
      <div className="flex items-center justify-between gap-3">
        <div className="text-[12px] text-ink-secondary">
          {t("vm.perBot.deleteHint")}
        </div>
        <button
          type="button"
          onClick={onRefresh}
          disabled={loading || deletingBotId !== null}
          aria-label={t("vm.perBot.refreshAria")}
          className="settings-quiet flex shrink-0 cursor-pointer items-center disabled:opacity-40"
        >
          {t("vm.refresh")}
        </button>
      </div>

      {error && <div role="alert" className="mt-2 text-[12px] leading-4 text-danger">{error}</div>}

      <p role="status" aria-live="polite" aria-atomic="true" className="sr-only">
        {loading
          ? t("vm.perBot.checking")
          : unavailableReason
            ? t("vm.perBot.unavailable", { reason: unavailableReason })
            : instances.length === 1
              ? t("vm.perBot.foundOne")
              : t("vm.perBot.foundMany", { count: instances.length })}
      </p>

      <div
        aria-busy={loading || deletingBotId !== null}
        className="mt-3 overflow-hidden rounded-xl border border-hairline/40"
      >
        {loading && instances.length === 0 ? (
          // Loading is two skeleton rows at their final height (§6.11), never a spinner.
          <div role="status" aria-label={t("vm.perBot.checkingList")} className="flex flex-col"><SettingsSkeletonRows /></div>
        ) : unavailableReason ? (
          <div className="flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary">
            <AlertTriangle size={14} className="shrink-0 text-warning" /> {unavailableReason}
          </div>
        ) : instances.length === 0 ? (
          <div className="px-3 py-4 text-[13px] text-ink-secondary">{t("vm.perBot.none")}</div>
        ) : instances.map((instance, index) => {
          const state = localVmInventoryState(instance);
          const deleting = deletingBotId === instance.botId;
          const managed = instance.managed === true;
          return (
            <div
              key={instance.botId}
              className={cn(
                "flex items-start justify-between gap-3 px-3 py-3",
                index > 0 && "border-t border-hairline/35",
              )}
            >
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="truncate text-[14px] font-medium text-ink">{instance.name}</span>
                  <span
                    className={cn(
                      "rounded-full px-2 py-0.5 text-[11px]",
                      !managed
                        ? "bg-warning/15 text-warning"
                        : instance.inUse || instance.ready
                          ? "bg-success/15 text-success"
                          : instance.container === "stopped"
                            ? "bg-control text-ink-secondary"
                            : "bg-warning/15 text-warning",
                    )}
                  >
                    {state}
                  </span>
                </div>
                <div className="mt-1 text-[12px] text-ink-secondary">
                  {t("vm.perBot.destination", { destination: t(destinationLabelKeys[instance.destination]) })}
                </div>
                {!managed && (
                  <div className="mt-1 text-[12px] text-warning">
                    {t("vm.perBot.unmanaged")}
                  </div>
                )}
                {managed && instance.problem && !instance.inUse && (
                  <div className="mt-1 text-[12px] text-warning">{localizeComputerProblem(instance.problem)}</div>
                )}
                {managed && instance.inUse && (
                  <div className="mt-1 text-[12px] text-ink-secondary">{t("vm.perBot.stopFirst")}</div>
                )}
              </div>
              {managed && <button
                type="button"
                onClick={() => onDelete(instance)}
                disabled={loading || instance.inUse || deletingBotId !== null}
                aria-busy={deleting || undefined}
                title={
                  instance.inUse
                    ? t("vm.perBot.deleteBlocked")
                    : t("vm.perBot.deleteTitle", { name: instance.name })
                }
                className="flex shrink-0 items-center gap-1.5 rounded-lg bg-danger/10 px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40"
              >
                {deleting ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}
                {t("common.delete")}
              </button>}
            </div>
          );
        })}
      </div>
    </Card>
  );
}

/** A numbered step: the 20 px ink 6% circle centred in the 32 px leading slot, its text at the icon-card edge. */
function Step({ n, title, done, children }: { n: number; title: string; done: boolean; children?: React.ReactNode }) {
  return (
    <div className="flex gap-3" data-vm-step={n}>
      <span className="flex size-8 shrink-0 items-start justify-center pt-0.5">
        <span aria-hidden="true" className="flex size-5 items-center justify-center rounded-full bg-ink/[0.06] text-[12px] font-medium leading-4 text-ink-secondary">
          {done ? <Check size={12} /> : n}
        </span>
      </span>
      <div className="min-w-0 flex-1">
        <div className={cn("text-[14px] leading-5", done ? "text-ink-secondary" : "text-ink")}>{title}</div>
        {!done && children && <div className="mt-2 flex flex-col items-start gap-2 [&>*]:max-w-full">{children}</div>}
      </div>
    </div>
  );
}

function ActionButton({
  action,
  pending,
  children,
  onClick,
  danger = false,
}: {
  action: Action;
  pending: Action | null;
  children: React.ReactNode;
  onClick: () => void;
  danger?: boolean;
}) {
  return (
    <button
      onClick={onClick}
      aria-busy={pending === action}
      disabled={pending !== null}
      data-danger={danger ? "" : undefined}
      className={cn(danger ? "settings-quiet flex cursor-pointer items-center gap-1.5" : "ui-button ui-button-md cursor-pointer rounded-full", "disabled:opacity-50")}
    >
      {pending === action && <Loader2 size={13} className="animate-spin" />}
      {children}
    </button>
  );
}

// Mirrors localVm.idleTimeoutMinutes in server/config.ts; the server is the authority.
const MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 5;
const MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 1_440;
const DEFAULT_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 480;

export function parseLocalVmIdleTimeoutMinutes(value: string): number | null {
  const trimmed = value.trim();
  if (!/^\d+$/.test(trimmed)) return null;
  const minutes = Number(trimmed);
  return minutes >= MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES && minutes <= MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES ? minutes : null;
}

export function LocalVmIdleTimeoutSetting({
  minutes,
  disabled,
  onSave,
}: {
  minutes: number;
  disabled: boolean;
  onSave: (minutes: number) => Promise<void>;
}) {
  const [value, setValue] = useState(String(minutes));
  const [dirty, setDirty] = useState(false);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!dirty) setValue(String(minutes));
  }, [minutes, dirty]);

  const save = async () => {
    if (!dirty || saving) return;
    const parsed = parseLocalVmIdleTimeoutMinutes(value);
    if (parsed === null) {
      setError(t("vm.idle.range"));
      return;
    }
    setSaving(true);
    try {
      await onSave(parsed);
      setValue(String(parsed));
      setDirty(false);
      setError("");
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("vm.idle.error"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="mt-3 flex flex-col gap-1">
      <div className="flex items-center justify-between gap-6">
        <div className="min-w-0">
          <label htmlFor="local-vm-idle-timeout" className="text-[14px] leading-5 text-ink">{t("vm.idle.label")}</label>
          <div id="local-vm-idle-timeout-help" className="text-[13px] leading-[18px] text-ink-secondary">{t("vm.idle.detail")}</div>
        </div>
        <span className="flex shrink-0 items-center gap-2">
          <input
            id="local-vm-idle-timeout"
            type="number"
            min={MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES}
            max={MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES}
            step={1}
            inputMode="numeric"
            value={value}
            disabled={disabled || saving}
            aria-invalid={Boolean(error)}
            aria-describedby={error ? "local-vm-idle-timeout-error local-vm-idle-timeout-help" : "local-vm-idle-timeout-help"}
            onChange={(event) => {
              setValue(event.target.value);
              setDirty(true);
              setError("");
            }}
            onBlur={() => void save()}
            onKeyDown={(event) => {
              if (event.key === "Enter") event.currentTarget.blur();
            }}
            className={cn(SETTINGS_INLINE_INPUT, "w-16 bg-transparent", error && "border-danger/60")}
          />
          <span className="text-[13px] leading-5 text-ink-secondary">{t("vm.idle.minutes")}</span>
        </span>
      </div>
      {error ? (
        <p id="local-vm-idle-timeout-error" role="alert" className="text-[12px] leading-4 text-danger">
          {error}
        </p>
      ) : null}
    </div>
  );
}

/** A command, behind a quiet Show (no native triangle). */
function ShowCommand({ label, command }: { label: string; command: string }) {
  const [open, setOpen] = useState(false);
  return <div className="flex w-full flex-col gap-2">
    <button type="button" aria-expanded={open} className="settings-quiet -ml-1.5 cursor-pointer self-start" onClick={() => setOpen((value) => !value)}>{label}</button>
    {open && <CommandLine command={command} />}
  </div>;
}

/** Safety and storage in two lines, the rest behind Learn more. */
function SafetyLine({ perBot, path }: { perBot: boolean; path: string }) {
  const [more, setMore] = useState(false);
  return <div className="flex flex-col gap-1 text-[13px] leading-[18px] text-ink-secondary">
    <p>{t(perBot ? "vm.safety.perBotShort" : "vm.safety.sharedShort", { path })}{" "}<LearnMore onClick={() => setMore((value) => !value)} /></p>
    {more && <p className="text-[12px] leading-4">{t(perBot ? "vm.safety.perBot" : "vm.safety.shared", { path })}</p>}
  </div>;
}

export function LocalComputerSection({ privateOnly = false }: { privateOnly?: boolean }) {
  const cloudHome = useStore().state.config?.cloudHome === true;
  const [status, setStatus] = useState<Status | null>(null);
  const [loading, setLoading] = useState(true);
  const [pending, setPending] = useState<Action | null>(null);
  const actionController = useRef<AbortController | null>(null);
  useEffect(() => () => actionController.current?.abort(), []);
  const [error, setError] = useState<string | null>(null);
  const [policyPending, setPolicyPending] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [inventory, setInventory] = useState<LocalVmInventoryInstance[]>([]);
  const [inventoryMax, setInventoryMax] = useState(2);
  const [inventoryLoading, setInventoryLoading] = useState(false);
  const [inventoryError, setInventoryError] = useState<string | null>(null);
  const [inventoryUnavailableReason, setInventoryUnavailableReason] = useState<string | null>(null);
  const [deletingBotId, setDeletingBotId] = useState<string | null>(null);
  const [inventoryRefreshKey, setInventoryRefreshKey] = useState(0);
  const [cloudInventory, setCloudInventory] = useState<CloudComputerInventoryInstance[]>([]);
  const [cloudConfigured, setCloudConfigured] = useState<boolean | null>(null);
  const [cloudLoading, setCloudLoading] = useState(true);
  const [cloudError, setCloudError] = useState<string | null>(null);
  const [cloudUnavailableReason, setCloudUnavailableReason] = useState<string | null>(null);
  const [cloudPending, setCloudPending] = useState<PendingCloudAction>(null);
  const [cloudRefreshKey, setCloudRefreshKey] = useState(0);
  const cloudInventoryRef = useRef<CloudComputerInventoryInstance[]>([]);
  const cloudOverridesRef = useRef<CloudPostActionOverrides>({});
  const [vpsInventory, setVpsInventory] = useState<VpsComputerInventoryInstance[]>([]);
  const [vpsConfigured, setVpsConfigured] = useState<boolean | null>(null);
  const [vpsAliases, setVpsAliases] = useState<string[]>([]);
  const [vpsLoading, setVpsLoading] = useState(true);
  const [vpsError, setVpsError] = useState<string | null>(null);
  const [vpsUnavailableReason, setVpsUnavailableReason] = useState<string | null>(null);
  const [vpsRemovingName, setVpsRemovingName] = useState<string | null>(null);
  const [vpsRefreshKey, setVpsRefreshKey] = useState(0);
  const [announcement, setAnnouncement] = useState("");

  const refresh = useCallback(async (signal?: AbortSignal) => {
    const response = await serverFetch(...computerInventoryRequest("status", signal));
    const body = await response.json().catch(() => ({}));
    if (signal?.aborted) return;
    if (!response.ok) throw new Error(body.error ?? t("vm.err.status", { code: response.status }));
    setStatus(body as Status);
    setError(null);
    return body as Status;
  }, []);

  const refreshInventory = useCallback(async (signal?: AbortSignal) => {
    const response = await serverFetch(...computerInventoryRequest("local-vms", signal));
    const body = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(body.error ?? t("vm.err.inventory", { code: response.status }));
    const payload = body as LocalVmInventoryPayload;
    setInventory(payload.instances);
    setInventoryMax(payload.maxInstances);
    setInventoryUnavailableReason(payload.available ? null : (localizeComputerProblem(payload.problem) ?? t("vm.err.runtimeUnavailable")));
    setInventoryError(null);
  }, []);

  const refreshCloudInventory = useCallback(async (signal?: AbortSignal) => {
    const response = await serverFetch(...computerInventoryRequest("cloud", signal));
    const body = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(body.error ?? t("vm.err.cloudInventory", { code: response.status }));
    const payload = body as CloudComputerInventoryPayload;
    const reconciled = reconcileCloudInventoryPayload(
      payload,
      cloudInventoryRef.current,
      cloudOverridesRef.current,
    );
    cloudOverridesRef.current = reconciled.overrides;
    cloudInventoryRef.current = reconciled.instances;
    setCloudInventory(reconciled.instances);
    setCloudConfigured(payload.configured === true);
    setCloudUnavailableReason(
      payload.available || !payload.configured
        ? null
        : (payload.problem ?? t("vm.err.cloudUnavailable")),
    );
    setCloudError(null);
  }, []);

  const refreshVpsInventory = useCallback(async (signal?: AbortSignal) => {
    const response = await serverFetch(...computerInventoryRequest("vps", signal));
    const body = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(body.error ?? t("vm.err.vpsInventory", { code: response.status }));
    const payload = body as VpsComputerInventoryPayload;
    setVpsInventory(Array.isArray(payload.instances) ? payload.instances : []);
    setVpsConfigured(payload.configured === true);
    setVpsAliases(Array.isArray(payload.vpsAliases) ? payload.vpsAliases : []);
    setVpsUnavailableReason(
      payload.available || !payload.configured
        ? null
        : (payload.problem ?? t("vm.err.vpsUnavailable")),
    );
    setVpsError(null);
  }, []);

  useEffect(() => {
    if (cloudHome) return;
    let active = true;
    let timer: number | undefined;
    let controller: AbortController | undefined;
    const poll = async () => {
      controller = new AbortController();
      try {
        await refresh(controller.signal);
      } catch (e) {
        if (active && !(e instanceof DOMException && e.name === "AbortError")) {
          setStatus(null);
          setError(e instanceof Error ? e.message : String(e));
        }
      } finally {
        if (active) {
          setLoading(false);
          timer = window.setTimeout(() => void poll(), 5000);
        }
      }
    };
    void poll();
    return () => {
      active = false;
      controller?.abort();
      if (timer !== undefined) window.clearTimeout(timer);
    };
  }, [cloudHome, refresh, refreshKey]);

  useEffect(() => {
    if (status?.mode !== "per-bot") {
      setInventory([]);
      setInventoryLoading(false);
      setInventoryError(null);
      setInventoryUnavailableReason(null);
      return;
    }
    const controller = new AbortController();
    setInventoryLoading(true);
    void refreshInventory(controller.signal)
      .catch((e) => {
        if (!(e instanceof DOMException && e.name === "AbortError")) {
          setInventoryError(e instanceof Error ? e.message : String(e));
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setInventoryLoading(false);
      });
    return () => controller.abort();
  }, [inventoryRefreshKey, refreshInventory, status?.mode]);

  useEffect(() => {
    if (privateOnly) return;
    const controller = new AbortController();
    setCloudLoading(true);
    void refreshCloudInventory(controller.signal)
      .catch((e) => {
        if (!(e instanceof DOMException && e.name === "AbortError")) {
          setCloudUnavailableReason(e instanceof Error ? e.message : String(e));
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setCloudLoading(false);
      });
    return () => controller.abort();
  }, [cloudRefreshKey, privateOnly, refreshCloudInventory]);

  useEffect(() => {
    if (privateOnly) return;
    const controller = new AbortController();
    setVpsLoading(true);
    void refreshVpsInventory(controller.signal)
      .catch((e) => {
        if (!(e instanceof DOMException && e.name === "AbortError")) {
          setVpsUnavailableReason(e instanceof Error ? e.message : String(e));
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setVpsLoading(false);
      });
    return () => controller.abort();
  }, [privateOnly, refreshVpsInventory, vpsRefreshKey]);

  const post = async (action: Exclude<Action, "recreate">, signal: AbortSignal) => {
    const response = await serverFetch(`/api/local-computer/${action}`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: "{}",
      signal,
    });
    const body = await response.json().catch(() => ({}));
    const errorKeys: Record<Exclude<Action, "recreate">, LocaleKey> = {
      pull: "vm.err.prepare",
      run: "vm.err.create",
      start: "vm.err.start",
      stop: "vm.err.stop",
      remove: "vm.deleteError",
    };
    if (!response.ok) throw new Error(body.error ?? t(errorKeys[action]));
    signal.throwIfAborted();
    setStatus(body as Status);
    return body as Status;
  };

  const confirmAction = (message: string) => window.ogb?.confirm ? window.ogb.confirm(message) : window.confirm(message);

  const act = async (action: Action) => {
    if (pending !== null || actionController.current) return;
    const controller = new AbortController();
    actionController.current = controller;
    setPending(action);
    setError(null);
    try {
      if (action === "remove" && !(await confirmAction(t("vm.confirm.deleteShared")))) return;
      if (action === "recreate" && !(await confirmAction(t("vm.confirm.recreate")))) return;
      let result: Status;
      if (action === "recreate") {
        await post("remove", controller.signal);
        result = await post("run", controller.signal);
      } else {
        result = await post(action, controller.signal);
      }
      if (action === "run" || action === "start" || action === "recreate") {
        result = await waitForLocalVmReady(
          result,
          async () => (await refresh(controller.signal)) ?? result,
          controller.signal,
        );
        if (!result.ready) throw new Error(result.problem ?? t("vm.err.start"));
      }
      await refresh();
      setAnnouncement(
        action === "remove"
          ? t("vm.announce.deleted")
          : action === "stop"
            ? t("vm.announce.stopped")
            : t("vm.announce.updated"),
      );
    } catch (e) {
      if (controller.signal.aborted) return;
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      actionController.current = null;
      if (!controller.signal.aborted) setPending(null);
    }
  };

  const savePolicy = async (mode: Status["mode"], maxInstances: number) => {
    setPolicyPending(true);
    setError(null);
    try {
      const response = await serverFetch("/api/config", {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ localVm: { mode, maxInstances } }),
      });
      const body = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(body.error ?? t("vm.policyError"));
      setStatus((current) => current ? { ...current, mode, max_instances: maxInstances } : current);
      await refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setPolicyPending(false);
    }
  };

  const saveIdleTimeout = async (idleTimeoutMinutes: number) => {
    const response = await serverFetch("/api/config", {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ localVm: { idleTimeoutMinutes } }),
    });
    const body = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(body.error ?? t("vm.idle.error"));
    setStatus((current) => current ? { ...current, idle_timeout_ms: idleTimeoutMinutes * 60_000 } : current);
  };

  const deletePerBotVm = async (instance: LocalVmInventoryInstance) => {
    if (!instance.managed) {
      setInventoryError(t("vm.unmanagedError"));
      return;
    }
    const request = confirmComputerAction(
      perBotLocalVmDeletePlan(instance),
      (message) => window.confirm(message),
    );
    if (!request) return;
    setDeletingBotId(instance.botId);
    setInventoryError(null);
    try {
      const response = await serverFetch(...request);
      const body = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(body.error ?? t("vm.deleteError"));
      await refreshInventory();
      setAnnouncement(t("vm.announce.deletedBot", { name: instance.name }));
    } catch (e) {
      setInventoryError(e instanceof Error ? e.message : String(e));
    } finally {
      setDeletingBotId(null);
    }
  };

  const actOnCloudComputer = async (action: CloudAction, instance: CloudComputerInventoryInstance) => {
    const request = confirmComputerAction(
      cloudComputerActionPlan(action, instance),
      (message) => window.confirm(message),
    );
    if (!request) return;
    setCloudPending({ boxId: instance.boxId, action });
    setCloudError(null);
    setAnnouncement("");
    try {
      const response = await serverFetch(...request);
      const body = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(body.error ?? t(action === "delete" ? "vm.cloud.deleteError" : "vm.cloud.sleepError"));
      const deletionPending = action === "delete" && body?.pending === true;
      cloudOverridesRef.current = {
        ...cloudOverridesRef.current,
        [instance.boxId]: action === "delete"
          ? deletionPending ? "deleting" : "deleted"
          : "sleeping",
      };
      const reconciled = reconcileCloudInventorySnapshot(
        cloudInventoryRef.current,
        cloudInventoryRef.current,
        cloudOverridesRef.current,
      );
      cloudOverridesRef.current = reconciled.overrides;
      cloudInventoryRef.current = reconciled.instances;
      setCloudInventory(reconciled.instances);
      const subject = instance.orphaned
        ? t("vm.announce.orphanCloud")
        : t("vm.confirm.ownedCloud", { name: instance.ownerName ?? "" });
      setAnnouncement(
        deletionPending
          ? `${subject}: ${t("vm.state.removing")}.`
          : t(action === "delete" ? "vm.announce.cloudDeleted" : "vm.announce.cloudSleeping", { subject }),
      );

      if (deletionPending) {
        // Boat may accept a background operation before the computer is gone.
        for (const delayMs of PENDING_CLOUD_DELETE_REFRESH_DELAYS_MS) {
          await waitForCloudDeleteRefresh(delayMs);
          try {
            await refreshCloudInventory();
          } catch {
          }
          if (cloudOverridesRef.current[instance.boxId] !== "deleting") {
            setAnnouncement(t("vm.announce.cloudDeleted", { subject }));
            return;
          }
        }

        const nextOverrides = { ...cloudOverridesRef.current };
        delete nextOverrides[instance.boxId];
        cloudOverridesRef.current = nextOverrides;
        const restored = cloudInventoryRef.current.map((current) =>
          current.boxId === instance.boxId ? { ...current, state: instance.state } : current
        );
        cloudInventoryRef.current = restored;
        setCloudInventory(restored);
        try {
          await refreshCloudInventory();
          if (!cloudInventoryRef.current.some((current) => current.boxId === instance.boxId)) {
            setAnnouncement(t("vm.announce.cloudDeleted", { subject }));
          }
        } catch (refreshError) {
          const detail = refreshError instanceof Error ? refreshError.message : String(refreshError);
          setCloudError(`${subject}: ${t("vm.state.removing")}. ${detail}`);
        }
        return;
      }

      try {
        await refreshCloudInventory();
      } catch (refreshError) {
        const detail = refreshError instanceof Error ? refreshError.message : String(refreshError);
        setCloudError(t(action === "delete" ? "vm.cloud.deletedRefreshError" : "vm.cloud.sleepRefreshError", { subject, detail }));
      }
    } catch (e) {
      setCloudError(e instanceof Error ? e.message : String(e));
    } finally {
      setCloudPending(null);
    }
  };

  const removeVpsComputer = async (instance: VpsComputerInventoryInstance) => {
    const shortId = vpsComputerShortId(instance.name);
    const request = confirmComputerAction(
      vpsComputerRemovePlan(instance),
      (message) => window.confirm(message),
    );
    if (!request) return;
    setVpsRemovingName(instance.name);
    setVpsError(null);
    try {
      const response = await serverFetch(...request);
      const body = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(body.error ?? t("vm.vpsRemoveError"));
      await refreshVpsInventory();
      setAnnouncement(
        t("vm.announce.vpsRemoved", {
          subject: instance.orphaned
            ? t("vm.announce.orphanVps", { id: shortId })
            : t("vm.confirm.ownedVps", { name: instance.ownerName ?? "" }),
        }),
      );
    } catch (e) {
      setVpsError(e instanceof Error ? e.message : String(e));
    } finally {
      setVpsRemovingName(null);
    }
  };

  const c = status?.commands;
  const ready = status?.ready === true;
  const existing = status?.container !== "missing";
  const needsRecreate = Boolean(
    existing &&
      (!status?.imageMatches ||
        !status?.managed ||
        status?.network === "unsafe" ||
        status?.security === "unsafe" ||
        status?.persistence === "unsafe"),
  );
  const unavailable = !loading && !status;
  const host = status?.platform === "darwin" ? t("vm.host.mac") : t("vm.host.computer");
  const perBot = status?.mode === "per-bot";
  const perBotRuntimeUnsupported = perBot && status?.runtime === "container";
  const headerReady = perBot ? Boolean(status?.daemonUp && status?.image && !perBotRuntimeUnsupported) : ready;

  return (
    <>
      <p role="status" aria-live="polite" aria-atomic="true" className="sr-only">{announcement}</p>
      {!privateOnly && <><CloudComputersCard
        instances={cloudInventory}
        configured={cloudConfigured}
        loading={cloudLoading}
        pending={cloudPending}
        error={cloudError}
        unavailableReason={cloudUnavailableReason}
        onRefresh={() => setCloudRefreshKey((key) => key + 1)}
        onSleep={(instance) => void actOnCloudComputer("sleep", instance)}
        onDelete={(instance) => void actOnCloudComputer("delete", instance)}
      />
      <VpsComputersCard
        instances={vpsInventory}
        configured={vpsConfigured}
        aliases={vpsAliases}
        loading={vpsLoading}
        removingName={vpsRemovingName}
        error={vpsError}
        unavailableReason={vpsUnavailableReason}
        onRefresh={() => setVpsRefreshKey((key) => key + 1)}
        onRemove={(instance) => void removeVpsComputer(instance)}
      />
      <MacLocalControl /></>}

      {!cloudHome && <>
      <Card
        title={t("vm.main.title")}
        subtitle={perBot
          ? t("vm.main.perBotSubtitle", { host })
          : t("vm.main.sharedSubtitle", { host })}
      >
        <div className="flex flex-wrap items-center gap-2">
          <span aria-live="polite" className="mr-auto flex items-center text-[13px] leading-[18px] text-ink-secondary">
            {loading ? <Loader2 size={12} className="mr-1.5 animate-spin" /> : <StatusDot tone={headerReady ? "success" : null} />}
            {loading
              ? t("common.checking")
              : unavailable
                ? t("vm.main.statusUnavailable")
                : perBot && headerReady
                  ? t("vm.main.readyPerBot")
                  : perBotRuntimeUnsupported
                    ? t("vm.main.perBotUnsupported")
                  : ready
                    ? t("vm.main.ready")
                    : (status?.problem ?? t("vm.main.notReady"))}
          </span>
          <button
            onClick={() => {
              setLoading(true);
              setRefreshKey((key) => key + 1);
              setInventoryRefreshKey((key) => key + 1);
            }}
            disabled={loading || pending !== null}
            className="settings-quiet cursor-pointer last:-me-1.5 disabled:opacity-40"
          >
            {t("vm.main.recheck")}
          </button>
          {ready && !perBot && (
            <a
              href={status?.viewer_url ?? c?.view}
              target="_blank"
              rel="noreferrer"
              className="settings-quiet cursor-pointer"
            >
              {t("vm.main.watch")}
            </a>
          )}
        </div>
        {error && <div role="alert" className="mt-2 text-[12px] leading-4 text-danger">{error}</div>}
      </Card>

      <Card
        title={t("vm.isolation.title")}
        subtitle={t("vm.isolation.subtitle")}
      >
        <div className="flex justify-end">
          <Segmented label={t("vm.isolation.title")} value={status?.mode === "per-bot" ? "per-bot" : "shared"} disabled={!status || policyPending}
            onChange={(mode) => { if (status) void savePolicy(mode, status.max_instances ?? 2); }}
            options={[{ value: "shared" as const, label: t("vm.isolation.shared") }, { value: "per-bot" as const, label: t("vm.isolation.perBot") }]} />
        </div>
        {perBot && (
          <div className="mt-3 flex items-center justify-between gap-3">
            <div>
              <div className="text-[13px] text-ink">{t("vm.isolation.max")}</div>
              <div className="text-[12px] text-ink-secondary">{t("vm.isolation.maxDetail")}</div>
            </div>
            <Select size="sm"
              aria-label={t("vm.isolation.maxAria")}
              value={status?.max_instances ?? 2}
              disabled={!status || policyPending}
              onChange={(event) => void savePolicy(status?.mode ?? "shared", Number(event.target.value))}
            >
              {[1, 2, 3, 4, 5, 6, 7, 8].map((value) => <option key={value} value={value}>{value}</option>)}
            </Select>
          </div>
        )}
        <LocalVmIdleTimeoutSetting
          minutes={status ? Math.round(status.idle_timeout_ms / 60_000) : DEFAULT_LOCAL_VM_IDLE_TIMEOUT_MINUTES}
          disabled={!status || policyPending}
          onSave={saveIdleTimeout}
        />
        {policyPending && <div className="mt-2 flex items-center gap-1.5 text-[12px] text-ink-secondary"><Loader2 size={12} className="animate-spin" /> {t("vm.saving")}</div>}
      </Card>

      <Card title={t("vm.setup.title")} subtitle={t("vm.setup.subtitle")}>
        <div className="flex flex-col gap-4">
          <Step n={1} title={t("vm.setup.step1")} done={Boolean(status?.runtime)}>
            <div className="text-[13px] leading-relaxed text-ink-secondary">
              {t("vm.setup.step1Detail")}
            </div>
            {c?.install ? (
              <CommandLine command={c.install} />
            ) : (
              <a href="https://podman.io/docs/installation" target="_blank" rel="noreferrer" className="text-[13px] text-accent hover:underline">
                {t("vm.setup.podmanGuide")}
              </a>
            )}
          </Step>

          <Step
            n={2}
            title={
              status?.runtime && !status.daemonUp
                ? t("vm.setup.step2Open", { runtime: status.runtime })
                : t("vm.setup.step2")
            }
            done={Boolean(status?.daemonUp)}
          >
            {!status?.runtime ? null : c?.runtimeStart ? (
              <CommandLine command={c.runtimeStart} />
            ) : (
              <div className="text-[13px] text-ink-secondary">{t("vm.setup.step2Detail")}</div>
            )}
          </Step>

          <Step n={3} title={t("vm.setup.step3")} done={Boolean(status?.image)}>
            {status?.daemonUp && (
              <ActionButton action="pull" pending={pending} onClick={() => void act("pull")}>{t("vm.setup.prepare")}</ActionButton>
            )}
            {c?.pull && <ShowCommand label={t("vm.setup.showPull")} command={c.pull} />}
          </Step>

          <Step
            n={4}
            title={
              perBot
                ? t("vm.setup.step4PerBot")
                : needsRecreate
                  ? t("vm.setup.step4Recreate")
                  : t("vm.setup.step4")
            }
            done={!perBot && ready}
          >
            {perBot ? (
              <div className="text-[13px] leading-relaxed text-ink-secondary">
                {perBotRuntimeUnsupported
                  ? t("vm.setup.applePort")
                  : t("vm.setup.perBotHint")}
              </div>
            ) : needsRecreate ? (
              <>
                <div className="flex gap-2 text-[13px] text-warning">
                  <AlertTriangle size={15} className="mt-0.5 shrink-0" />
                  <span>{status?.problem}</span>
                </div>
                {status?.image ? (
                  <ActionButton action="recreate" pending={pending} onClick={() => void act("recreate")} danger>
                    <RotateCcw size={13} /> {t("vm.setup.recreate")}
                  </ActionButton>
                ) : (
                  <div className="text-[13px] text-ink-secondary">{t("vm.setup.prepareFirst")}</div>
                )}
              </>
            ) : status?.container === "stopped" ? (
              <>
                <p className="text-[13px] text-ink-secondary">{t(status.stop_reason === "idle" ? "vm.stopped.idle" : "vm.stopped.detail")}</p>
                <ActionButton action="start" pending={pending} onClick={() => void act("start")}>{t("vm.setup.start")}</ActionButton>
              </>
            ) : status?.container === "running" ? (
              <div className="flex items-center gap-2 text-[13px] text-ink-secondary"><Loader2 size={13} className="animate-spin" /> {t("vm.setup.waiting")}</div>
            ) : status?.image ? (
              <>
                <ActionButton action="run" pending={pending} onClick={() => void act("run")}>{t("vm.setup.start")}</ActionButton>
                <p className="text-[13px] leading-relaxed text-ink-secondary">{t("vm.setup.idleHint")}</p>
              </>
            ) : null}
            {c?.run && <ShowCommand label={t("vm.setup.showCommand")} command={c.run} />}
          </Step>
        </div>
      </Card>

      {perBot && (
        <LocalVmInventoryCard
          instances={inventory}
          maxInstances={inventoryMax || status?.max_instances || 2}
          loading={inventoryLoading}
          deletingBotId={deletingBotId}
          error={inventoryError}
          unavailableReason={inventoryUnavailableReason}
          onRefresh={() => setInventoryRefreshKey((key) => key + 1)}
          onDelete={(instance) => void deletePerBotVm(instance)}
        />
      )}

      {unavailable && (
        <Card>
          <div className="flex gap-2 text-[13px] text-ink-secondary">
            <AlertTriangle size={15} className="mt-0.5 shrink-0 text-warning" />
            <span>{t("vm.inspectFailed")}</span>
          </div>
        </Card>
      )}

      <Card title={t("vm.safety.title")}>
        <SafetyLine perBot={perBot} path={status?.workspace_guest_path ?? "/home/cua/workspace"} />
        {existing && (
          <div className="flex flex-wrap gap-2">
            {status?.container === "running" && (
              <ActionButton action="stop" pending={pending} onClick={() => void act("stop")}>
                <Square size={12} /> {t("vm.safety.stop")}
              </ActionButton>
            )}
            <ActionButton action="remove" pending={pending} onClick={() => void act("remove")} danger>
              <Trash2 size={12} /> {perBot ? t("vm.safety.deleteLegacy") : t("vm.safety.deleteVm")}
            </ActionButton>
          </div>
        )}
        {/* One detail per line, "Label: value"; only an image's digest may break anywhere, never a word. */}
        <div data-vm-folder="" className="flex flex-col font-mono text-[12px] leading-4 text-ink-secondary">
          {[...t("vm.safety.workspace", {
            path: status?.workspace_path ?? t("vm.safety.notCreated"),
            driver: status?.driver_version ?? "0.37.0",
            image: status?.image_ref ?? t("vm.safety.notPrepared"),
          }).split(" · "), ...(status?.base_image_ref ? [t("vm.safety.baseImage", { image: status.base_image_ref })] : [])].map((detail) => {
            const at = detail.indexOf(": ");
            const value = at < 0 ? detail : detail.slice(at + 2);
            return <span key={detail} className="block">{at < 0 ? null : detail.slice(0, at + 2)}<span className={/[@:]sha256|^sha256|[0-9a-f]{24,}/.test(value) ? "[overflow-wrap:anywhere]" : "break-words"}>{value}</span></span>;
          })}
        </div>
      </Card>
      </>}
    </>
  );
}