All files / src/components/spe SpePowerControls.tsx

83.33% Statements 25/30
83.33% Branches 35/42
60% Functions 3/5
86.2% Lines 25/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 1853x                           3x                                                   28x 28x 28x 28x 28x   28x   28x 28x     2x 2x 2x 2x 2x         2x     2x       2x 1x       1x   1x 1x       2x       28x                                     2x                                                                                                                                                                  
"use client";
 
import { useState } from "react";
import { Loader2, Play, Square } from "lucide-react";
import { fetchApi } from "@/lib/api";
import { IS_STATIC } from "@/lib/static-export";
import {
  formatSpeTime,
  type SpeEntry,
  type SpePowerState,
  type SpeStatusResponse,
} from "@/lib/spe";
import { useT } from "@/lib/i18n/translate";
 
const POWER_CLASSES: Record<SpePowerState, string> = {
  running: "text-(--success-text) border-(--success)/40",
  starting: "text-(--warning-text) border-(--warning)/40",
  stopped: "text-(--text-secondary) border-(--border)",
  unreachable: "text-(--danger-text) border-(--danger)/40",
};
 
interface PowerError {
  error: string;
  command?: string;
}
 
/**
 * A workspace's power state, Start and Stop for the operator and the access
 * body, and while it starts the progress line (ADR-072). `onChange` is the
 * page's `watch()` from useSpeStatus, which polls until the workspace runs.
 */
export function SpePowerControls({
  spe,
  power,
  onChange,
}: {
  spe: SpeEntry;
  power: SpeStatusResponse["power"];
  onChange: () => void;
}) {
  const t = useT("admin");
  const [busy, setBusy] = useState<"start" | "stop" | null>(null);
  const [requested, setRequested] = useState<"start" | "stop" | null>(null);
  const [failure, setFailure] = useState<PowerError | null>(null);
  const [note, setNote] = useState<string | null>(null);
 
  const state: SpePowerState = spe.powerState ?? "unreachable";
  const showProgress =
    state === "starting" || (requested === "start" && state !== "running");
  const mayPower = IS_STATIC || power?.available === true;
 
  async function act(action: "start" | "stop") {
    setBusy(action);
    setFailure(null);
    setNote(null);
    try {
      const r = await fetchApi("/api/admin/spe/power", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, spe: spe.id }),
      });
      const body = (await r.json().catch(() => null)) as
        | (PowerError & { static?: boolean })
        | null;
      Iif (IS_STATIC) {
        setNote(t("Static demo: nothing is started or stopped."));
        return;
      }
      if (!r.ok) {
        setFailure({
          error: body?.error ?? `HTTP ${r.status}`,
          command: body?.command,
        });
        return;
      }
      setRequested(action);
      onChange();
    } catch (e: unknown) {
      setFailure({ error: e instanceof Error ? e.message : String(e) });
    } finally {
      setBusy(null);
    }
  }
 
  return (
    <div
      aria-label={t("Power of {id}", { id: spe.id })}
      className="space-y-1.5 text-xs"
    >
      <div className="flex items-center gap-2 flex-wrap">
        <span
          className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${POWER_CLASSES[state]}`}
        >
          {t("Workspace: {state}", { state: t(state) })}
        </span>
        {spe.armState && (
          <span className="text-[10px] text-(--text-secondary) font-mono">
            ACI {spe.armState}
          </span>
        )}
        {mayPower && (state === "stopped" || state === "unreachable") && (
          <button
            type="button"
            onClick={() => void act("start")}
            disabled={busy !== null}
            aria-label={t("Start {id}", { id: spe.id })}
            className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-(--border) hover:bg-(--surface-2) disabled:opacity-50"
          >
            {busy === "start" ? (
              <Loader2 size={12} className="animate-spin" aria-hidden="true" />
            ) : (
              <Play size={12} aria-hidden="true" />
            )}
            {t("Start")}
          </button>
        )}
        {mayPower && (state === "running" || state === "starting") && (
          <button
            type="button"
            onClick={() => void act("stop")}
            disabled={busy !== null}
            aria-label={t("Stop {id}", { id: spe.id })}
            className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-(--border) hover:bg-(--surface-2) disabled:opacity-50"
          >
            {busy === "stop" ? (
              <Loader2 size={12} className="animate-spin" aria-hidden="true" />
            ) : (
              <Square size={12} aria-hidden="true" />
            )}
            {t("Stop")}
          </button>
        )}
      </div>
      {showProgress && (
        <p
          role="status"
          className="flex items-center gap-1.5 text-(--warning-text)"
        >
          <Loader2 size={12} className="animate-spin" aria-hidden="true" />
          {t(
            "Starting: attesting to Trustee, releasing the key, loading the data; about 3 to 4 minutes",
          )}
        </p>
      )}
      <p className="text-[11px] text-(--text-secondary)">
        {spe.lastQueriedAt
          ? t("Last queried {when}", { when: formatSpeTime(spe.lastQueriedAt) })
          : t("No query recorded yet")}
        {" ยท "}
        {t(
          "Stopped by default, starts on demand, stops itself after 30 minutes without a query (ADR-072)",
        )}
      </p>
      {!mayPower && power?.reason && (
        <p className="text-[11px] text-(--text-secondary)">{t(power.reason)}</p>
      )}
      {note && (
        <p role="note" className="text-[11px] text-(--text-secondary)">
          {note}
        </p>
      )}
      {failure && (
        <div
          role="alert"
          className="text-[11px] text-(--danger-text) bg-(--danger)/10 border border-(--danger)/30 rounded px-2 py-1.5 space-y-1"
        >
          <p>
            {t("Could not change the workspace: {error}", {
              error: failure.error,
            })}
          </p>
          {failure.command && (
            <>
              <p>{t("An owner of the resource group runs once:")}</p>
              <code className="block font-mono break-all text-(--text-primary)">
                {failure.command}
              </code>
            </>
          )}
        </div>
      )}
    </div>
  );
}