import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { deployAwsEnvironment, destroyIncompleteAwsEnvironment, detectAwsEnvironments, followAwsDeployment, onboardAwsUser, pushAwsSavedState, repairAwsEnvironment, unlockAwsState, updateAwsEnvironment, } from "../../../lib/tauri-commands"; import { awsErrorMessage, looksDenied, toAwsError } from "../../../lib/aws-error"; import { clearEc2CapacityCache } from "../../../lib/ec2Capacity"; import type { AwsError, DetectedEnvironment, Ec2Choice, Ec2Compute, EnvironmentScan, HostConnection, LockInfo, ModuleKind, NetworkChoice, PermissionSummary, PolicyFile, UserCompute, } from "../../../lib/types"; import Button from "../../ui/Button"; import Field, { inputClass, selectClass } from "../../ui/Field"; import Modal from "../../ui/Modal"; import StatusIndicator from "../../ui/StatusIndicator"; import AdminBundleModal from "./AdminBundleModal"; import UpdateEnvironmentModal from "./UpdateEnvironmentModal"; import DeployEnvironmentModal from "./DeployEnvironmentModal"; import JoinEnvironmentModal from "./JoinEnvironmentModal"; import DeployProgress, { runKey, useDeployRuns, type DeployRun, type RunKind } from "./DeployProgress"; import PolicyFiles from "./PolicyFiles"; import { COMMON_REGIONS, computeLine, environmentStateKey, formatAge, lockLine, onboardingStateKey, stateLock, stateStatus, UNCONFIRMED_NOTE, } from "./environmentFormat"; /** A typed confirmation: the action runs only once the environment's name is typed. */ function TypedConfirmModal({ title, name, confirmLabel, children, onConfirm, onClose, }: { title: string; name: string; confirmLabel: string; children: ReactNode; /** Resolves to the command's error, or null when done. */ onConfirm: () => Promise; onClose: () => void; }) { const [typed, setTyped] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const confirm = async () => { setBusy(true); setError(null); const err = await onConfirm(); setBusy(false); if (err) setError(err); else onClose(); }; return ( } >
{children} {(id) => ( setTyped(e.target.value)} /> )} {error && (

{awsErrorMessage(error)}

)}
); } type Bundle = { kind: ModuleKind; region: string; environment?: string; ownerId?: string; recordedEc2?: UserCompute | null; }; /** A self-onboarding (or its re-apply) waiting for its EC2 choice. */ type JoinOf = { region: string; name: string; ownerId: string; stateKey: string; recorded: UserCompute | null; reapply: boolean; incomplete: boolean; lastChoice: Ec2Compute | null; }; /** The caller's recorded EC2 capacity in `e`, if any. */ const recordedEc2 = (e: DetectedEnvironment): UserCompute | null => e.onboarding && (e.onboarding.state === "joined" || e.onboarding.state === "incomplete") ? e.onboarding.ec2 : null; /** A row-level key: the same environment name can exist in every region. */ const rowKey = (region: string, name: string) => `${region}:${name}`; /** * A failed new deploy or self-onboarding started here that AWS refused a * permission for: the bundle for an admin is the way on. Only those two * kinds: an environment bundle deploys a *new* environment, so a follow, * repair or update of an existing one is never offered it. */ function deniedRun(r: DeployRun): "environment" | "user_onboard" | null { if (r.kind !== "deploy" && r.kind !== "onboard") return null; if (!r.done || !r.result || r.result.ok) return null; const denied = looksDenied(r.result.summary) || r.events.some((e) => e.level === "error" && looksDenied(e.message)); if (!denied) return null; return r.kind === "deploy" ? "environment" : "user_onboard"; } /** The environment a run's state key belongs to, if any. */ function runEnvironment(stateKey: string): string | null { const m = /^(?:environments|users)\/([^/]+)\//.exec(stateKey); return m ? m[1] : null; } /** * The environments a connection can reach in a region (spec §2): detection, * each environment's state and actions, and deploy/join. Deploy and join are * offered to anyone (AWS has the last word and its refusal is shown); an * unconfirmed tier only adds a note and the bundle-for-an-admin alternative. */ export default function EnvironmentsPanel({ connection, tier, }: { connection: HostConnection; /** The connection's last permission report; absent means unknown (not confirmed as an admin). */ tier?: PermissionSummary; }) { const isAdmin = tier === "environment_admin"; const [open, setOpen] = useState(false); const [region, setRegion] = useState(connection.kind.default_region); const [scan, setScan] = useState(null); const [detecting, setDetecting] = useState(false); const [detectError, setDetectError] = useState(null); const [rowErrors, setRowErrors] = useState>({}); const [pending, setPending] = useState>({}); const [waiting, setWaiting] = useState>(new Set()); const [deployOpen, setDeployOpen] = useState(false); const [repairOf, setRepairOf] = useState(null); const [updateOf, setUpdateOf] = useState<{ name: string; region: string; hours: number } | null>(null); const [destroyOf, setDestroyOf] = useState<{ name: string; region: string } | null>(null); /** An Unlock waiting for its typed confirmation: an environment's lock or the caller's onboarding's. */ const [unlockOf, setUnlockOf] = useState<{ name: string; region: string; stateKey: string; lock: LockInfo | null; onboarding: boolean; } | null>(null); const [bundle, setBundle] = useState(null); const [joinOf, setJoinOf] = useState(null); // The EC2 capacity last chosen per environment in this run of the app: an // onboarding that didn't finish has no record to start from. const lastEc2 = useRef(new Map()); const [copyNote, setCopyNote] = useState(null); const [notAdminOpen, setNotAdminOpen] = useState(false); const request = useRef(0); const followed = useRef(new Set()); const detect = useCallback(async () => { const id = ++request.current; setDetecting(true); setDetectError(null); try { const found = await detectAwsEnvironments(connection.id, region); // A scan reads every user record afresh (a join may have changed the // EC2 capacity): Host settings ask again too. clearEc2CapacityCache(); if (id === request.current) setScan(found); } catch (e) { if (id === request.current) { setScan(null); setDetectError(toAwsError(e)); } } finally { if (id === request.current) setDetecting(false); } }, [connection.id, region]); // A finished run (its result line shown) re-detects. const detectRef = useRef(detect); detectRef.current = detect; const { runs, start, dismiss } = useDeployRuns(() => void detectRef.current()); useEffect(() => { if (open) void detect(); }, [open, detect]); /** Start a run in `runRegion` (always the region of the scan the action came from). */ const launch = useCallback( async ( runRegion: string, envName: string, stateKey: string, kind: RunKind, label: string, run: () => Promise, ) => { const rk = rowKey(runRegion, envName); setRowErrors(({ [rk]: _gone, ...rest }) => rest); setPending((p) => ({ ...p, [rk]: true })); const err = await start(stateKey, runRegion, kind, label, run); setPending(({ [rk]: _gone, ...rest }) => rest); if (err) setRowErrors((r) => ({ ...r, [rk]: err })); return err; }, [start], ); // Reattach to a deploy (or the caller's onboarding) running on this machine; // a re-follow replays its whole log. useEffect(() => { if (!scan) return; const reattach = (name: string, key: string, label: string) => { const seen = runKey(scan.region, key); if (!runs[seen] && !followed.current.has(seen)) { followed.current.add(seen); void launch(scan.region, name, key, "follow", label, () => followAwsDeployment(connection.id, scan.region, key)); } }; for (const e of scan.environments) { if (e.actions.includes("follow")) reattach(e.name, environmentStateKey(e.name), `Deploy of ${e.name}`); if (e.onboarding_actions.includes("follow")) { reattach(e.name, onboardingStateKey(e.name, scan.owner_key), `Joining ${e.name}`); } } }, [scan, runs, launch, connection.id]); const regions = COMMON_REGIONS.includes(connection.kind.default_region) ? COMMON_REGIONS : [connection.kind.default_region, ...COMMON_REGIONS]; const copy = async (file: PolicyFile) => { try { await navigator.clipboard.writeText(file.json); setCopyNote(`${file.name} copied to clipboard.`); } catch (e) { setCopyNote(`Could not copy ${file.name}: ${awsErrorMessage(toAwsError(e))}`); } }; // Rows (and every action on them) belong to the scan they came from. After a // region change the old scan's rows are hidden, and while any detection is in // flight their actions are disabled; actions always target `scan.region`. const current = scan && scan.region === region ? scan : null; const stale = detecting || !current; const deploy = (runRegion: string, name: string, network: NetworkChoice, hours: number) => launch(runRegion, name, environmentStateKey(name), "deploy", `Deploy of ${name}`, () => deployAwsEnvironment(connection.id, runRegion, name, network, hours), ); // Without `hours`, the environment's recorded cap is kept. const repair = (runRegion: string, name: string, network?: NetworkChoice, hours?: number) => launch(runRegion, name, environmentStateKey(name), "repair", `Repair of ${name}`, () => repairAwsEnvironment(connection.id, runRegion, name, network, hours), ); const update = (runRegion: string, name: string, hours: number) => launch(runRegion, name, environmentStateKey(name), "update", `Update of ${name}`, () => updateAwsEnvironment(connection.id, runRegion, name, hours), ); // Join (or, once joined, a change of EC2 capacity): anyone chooses the // capacity and applies it; the modal offers a bundle for an admin instead. const join = (found: EnvironmentScan, e: DetectedEnvironment) => { setJoinOf({ region: found.region, name: e.name, ownerId: found.owner_id, stateKey: onboardingStateKey(e.name, found.owner_key), recorded: recordedEc2(e), reapply: e.onboarding?.state === "joined", incomplete: e.onboarding?.state === "incomplete", lastChoice: lastEc2.current.get(rowKey(found.region, e.name)) ?? null, }); }; const onboardBundle = (region: string, environment: string, ownerId: string, recorded: UserCompute | null) => setBundle({ kind: "user_onboard", region, environment, ownerId, recordedEc2: recorded }); const runJoin = (j: JoinOf, ec2: Ec2Choice) => { const key = rowKey(j.region, j.name); if (ec2.kind === "ec2") { const { kind: _kind, ...c } = ec2; lastEc2.current.set(key, c); } else lastEc2.current.delete(key); return launch(j.region, j.name, j.stateKey, "onboard", `Joining ${j.name}`, () => onboardAwsUser(connection.id, j.region, j.name, ec2)); }; const rowRuns = (name: string) => Object.values(runs).filter((r) => r.region === current?.region && runEnvironment(r.stateKey) === name); const shown = new Set(current?.environments.map((e) => e.name) ?? []); const looseRuns = Object.values(runs).filter( (r) => r.region !== current?.region || !shown.has(runEnvironment(r.stateKey) ?? ""), ); const progress = (r: DeployRun) => { const denied = deniedRun(r); const env = runEnvironment(r.stateKey); const found = current?.region === r.region ? current : null; const target = env && found ? found.environments.find((e) => e.name === env) : undefined; const offer = denied === "environment" ? true : denied === "user_onboard" ? !!(found && target) : false; return (
dismiss(runKey(r.region, r.stateKey))} /> {offer && (

AWS refused a permission this run needs (its message is above). This may need an admin:{" "} {denied === "environment" ? "An admin can deploy the environment for you from a bundle." : "An admin can onboard you from a bundle."}

)}
); }; const envRow = (found: EnvironmentScan, e: DetectedEnvironment) => { const at = found.region; const status = stateStatus(e.state); const lock = stateLock(e.state); const has = (a: DetectedEnvironment["actions"][number]) => e.actions.includes(a); const mine = (a: DetectedEnvironment["actions"][number]) => e.onboarding_actions.includes(a); const onboarding = e.onboarding?.state; const myKey = onboardingStateKey(e.name, found.owner_key); const myLock = e.onboarding && (e.onboarding.state === "incomplete" || e.onboarding.state === "in_progress") ? e.onboarding.lock : null; // Someone else's run holds the state: a re-apply or destroy would only // fail inside its run, so those wait for Unlock. const lockHeld = !!lock && !lock.local_process; // Join re-applies the onboarding: not under a held lock, nor before a // saved state is pushed back. const joinBlocked = (!!myLock && !myLock.local_process) || mine("push_state"); const busy = stale || !!pending[rowKey(at, e.name)]; const rowError = rowErrors[rowKey(at, e.name)]; const isWaiting = waiting.has(rowKey(at, e.name)); return (
  • {e.name} {onboarding === "joined" && } {onboarding === "in_progress" && } {onboarding === "incomplete" && }
    {e.template_version !== null ? `Module version ${e.template_version}` : "Module version unknown"} {e.info && ` · ${e.info.network_mode} network`}
    {lock && (
    {lockLine(lock)} {lock.local_process && " · running on this machine"}
    )} {e.state.state === "unreadable_record" && (
    The environment's record can't be used: {e.state.reason}
    )} {e.state.state === "externally_managed" && (
    Its OpenTofu state isn't in this region's Triple-C state bucket (deployed from a bundle with another bucket, or you can't read it), so it can't be updated from here.
    )} {e.state.state === "incomplete" && (
    {lockHeld ? "The last change didn't finish: its run stopped while holding the state lock. Unlock first, then Repair." : "The last change didn't finish: the deployment has state but no working environment record."}
    )} {has("push_state") && (
    The last run on this machine couldn't save its state (OpenTofu kept it in errored.tfstate). Push it back before anything else runs here.
    )} {onboarding === "incomplete" && (
    {myLock && !myLock.local_process ? `Your last onboarding didn't finish and still holds its state lock (${lockLine(myLock)}). Unlock it, then Join again to finish.` : mine("push_state") ? "Your last onboarding didn't finish and couldn't save its state; push the saved state back, then Join again." : "Your last onboarding didn't finish; Join again to finish it."}
    )} {(onboarding === "joined" || recordedEc2(e)) && (
    EC2 capacity: {(() => { const c = recordedEc2(e); return c ? computeLine(c) : "none (Fargate only)"; })()}
    )} {isWaiting && onboarding !== "joined" && (
    Waiting for an admin to onboard you
    )}
    {has("join") && onboarding !== "joined" && onboarding !== "in_progress" && ( )} {has("join") && onboarding === "joined" && ( )} {mine("follow") && ( )} {mine("push_state") && ( )} {mine("unlock") && ( )} {has("push_state") && ( )} {has("follow") && ( )} {has("update") && ( )} {has("repair") && ( )} {has("unlock") && ( )} {has("destroy") && ( )} {lockHeld && (has("repair") || has("destroy")) && ( Unlock first )}
    {rowError && (

    {awsErrorMessage(rowError)}

    )} {rowRuns(e.name).map(progress)}
  • ); }; const nothingFound = !!current && current.environments.length === 0; return (
    {open && (
    {(id) => ( )}
    {detecting && (

    Detecting…

    )} {detectError && (

    {awsErrorMessage(detectError)}

    )} {current && current.boundary === "no" && (

    This account has no Triple-C permissions boundary yet; deploying creates it first.

    )} {current && current.environments.length > 0 && (
      {current.environments.map((e) => envRow(current, e))}
    )} {nothingFound && (

    No Triple-C environment in {current.region}. {!tier && " Run Check to see what your credentials can do."}

    )} {current && (
    {!isAdmin && (

    {UNCONFIRMED_NOTE}

    )} {!isAdmin && (
    setNotAdminOpen(ev.currentTarget.open)} > Not an admin? Ask one to deploy it
    {copyNote && (

    {copyNote}

    )}
    )}
    )} {looseRuns.map(progress)}
    )} {current && (deployOpen || repairOf) && ( { setDeployOpen(false); setRepairOf(null); }} onDeploy={(name, network, hours) => repairOf ? repair(current.region, name, network, hours) : deploy(current.region, name, network, hours) } onDetect={() => void detect()} onBundle={() => { const at = current.region; setDeployOpen(false); setRepairOf(null); setBundle({ kind: "environment", region: at }); }} /> )} {updateOf && ( setUpdateOf(null)} onUpdate={(hours) => update(updateOf.region, updateOf.name, hours)} /> )} {destroyOf && ( setDestroyOf(null)} onConfirm={() => launch(destroyOf.region, destroyOf.name, environmentStateKey(destroyOf.name), "destroy", `Destroy of ${destroyOf.name}`, () => destroyIncompleteAwsEnvironment(connection.id, destroyOf.region, destroyOf.name), ) } >

    This environment's deployment is incomplete (no valid environment record). OpenTofu removes everything it created for {destroyOf.name} in {destroyOf.region}. This can't be undone.

    )} {unlockOf && ( setUnlockOf(null)} onConfirm={async () => { try { await unlockAwsState(connection.id, unlockOf.region, unlockOf.stateKey); } catch (e) { return toAwsError(e); } void detect(); return null; }} > {(() => { const lock = unlockOf.lock; return lock ? (

    Held by {lock.who || "unknown"} since{" "} {formatAge(lock.age_secs)} ago ({lock.created} {lock.operation && `, ${lock.operation}`}).

    ) : null; })()}

    Unlock only if that deployment has stopped. Removing the lock of a run that is still going lets two runs write the state at once.

    )} {joinOf && ( { const j = joinOf; setJoinOf(null); onboardBundle(j.region, j.name, j.ownerId, j.recorded); }} onJoin={(ec2) => runJoin(joinOf, ec2)} onClose={() => setJoinOf(null)} /> )} {bundle && ( { if (bundle.kind === "user_onboard" && bundle.environment) { const rk = rowKey(bundle.region, bundle.environment); setWaiting((w) => new Set(w).add(rk)); } }} onClose={() => setBundle(null)} /> )}
    ); }