feat(aws): environments panel — detect, deploy, update, repair, join

EnvironmentsPanel under each AWS connection: region select and detection,
environment rows with state, lock owner/age, module version and the
detected actions (Join, Update, Repair, Destroy, Follow, Unlock), typed
confirmations for Destroy and Unlock, self-onboarding for environment
admins and the onboarding bundle for everyone else (R15).
DeployEnvironmentModal (name rule mirrored from Rust, D4 networks with
cost lines, boundary-first step), AdminBundleModal (D5 bundles) and
DeployProgress, whose hook subscribes before invoking and buffers events
by state key until the op id is known.

awsErrorMessage moves to lib/aws-error; PolicyFiles to its own module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Opus 5.5 committed 2026-11-14 22:50:23 -08:00
1 parent a8b83ca63a
commit cf9b5eab3a
13 files changed
+1965 -90

No files matched your search

+6 -90
View File
@@ -5,50 +5,29 @@ import {
addAwsProfileConnection,
awsConnectionIdentity,
awsConnectionSsoLogin,
awsPolicyDocument,
checkAwsPermissions,
listAwsProfiles,
removeHostConnection,
updateAwsConnection,
} from "../../lib/tauri-commands";
import { toAwsError } from "../../lib/aws-error";
import { awsErrorMessage, toAwsError } from "../../lib/aws-error";
import PolicyFiles from "./hosts/PolicyFiles";
import EnvironmentsPanel from "./hosts/EnvironmentsPanel";
import { COMMON_REGIONS } from "./hosts/environmentFormat";
import type {
AwsError,
HostConnection,
PermissionReport,
PermissionSummary,
PolicyFile,
Tier,
} from "../../lib/types";
import Button from "../ui/Button";
import SegmentedControl from "../ui/SegmentedControl";
import Field, { inputClass, selectClass } from "../ui/Field";
const COMMON_REGIONS = [
"us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1",
"eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1",
"ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "ap-south-1",
"sa-east-1",
];
const OWN_PRINCIPAL_ACTIONS = ["iam:GetRole", "iam:SimulatePrincipalPolicy"];
/** Human-readable copy for a failed AWS command; never raw JSON. */
export function awsErrorMessage(e: AwsError): string {
switch (e.kind) {
case "sso_expired":
return `Your SSO session for profile ${e.profile} has expired.`;
case "profile_not_found":
return `Profile ${e.profile} was not found in your AWS config, or has no credentials.`;
case "keys_missing":
return "The access keys for this connection are missing from the keychain. Remove and re-add the connection.";
case "state_bucket_taken":
return `The state bucket name ${e.bucket} is already taken by another AWS account.`;
default:
return e.message;
}
}
const SUMMARY_LABEL: Record<PermissionSummary, string> = {
environment_admin: "Environment admin",
workspace_user: "Workspace user",
@@ -96,70 +75,6 @@ function ErrorLine({
);
}
/** A tier's policy files, loaded on demand: each one shown and copied on its own. */
function PolicyFiles({
tier,
label,
onCopy,
}: {
tier: Tier;
label: string;
onCopy: (file: PolicyFile) => void;
}) {
const [files, setFiles] = useState<PolicyFile[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = async () => {
setError(null);
try {
setFiles(await awsPolicyDocument(tier));
} catch (e) {
setError(`Could not load the policy: ${awsErrorMessage(toAwsError(e))}`);
}
};
if (!files) {
return (
<div className="space-y-1">
<Button size="sm" onClick={load}>
{label}
</Button>
{error && (
<p role="alert" className="text-xs text-[var(--error)]">
{error}
</p>
)}
</div>
);
}
return (
<div className="space-y-1 text-xs">
<p className="text-[var(--text-secondary)]">
{tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "}
{files.length === 1
? "attach this file as a customer managed policy."
: `Attach all ${files.length} files, each as its own customer managed policy.`}
</p>
{files.map((f) => (
<div key={f.name} className="space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[var(--text-primary)]">{f.name}</span>
<Button size="sm" aria-label={`Copy ${f.name}`} onClick={() => onCopy(f)}>
Copy
</Button>
</div>
<details>
<summary className="cursor-pointer text-[var(--text-secondary)]">Show JSON</summary>
<pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all text-[var(--text-secondary)]">
{f.json}
</pre>
</details>
</div>
))}
</div>
);
}
function PermissionReportView({ report }: { report: PermissionReport }) {
const [copyNote, setCopyNote] = useState<string | null>(null);
const probed = typeof report.method === "object";
@@ -399,6 +314,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
{busy && !editing && !confirmRemove && <p role="status" className="text-xs text-[var(--text-secondary)]">Working…</p>}
{failure && <ErrorLine failure={failure} onSignIn={signIn} signingIn={signingIn} />}
{report && <PermissionReportView report={report} />}
<EnvironmentsPanel connection={host} tier={report?.summary} />
</li>
);
}
@@ -591,7 +507,7 @@ export default function HostsSettings() {
return (
<div className="space-y-3">
<p className="text-xs text-[var(--text-secondary)] leading-snug">
Where project environments run. AWS connections are used to check what your credentials can do.
Where project environments run. AWS connections check what your credentials can do, and find, deploy and join environments.
</p>
<ul className="space-y-2">
<li className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2.5">
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import AdminBundleModal from "./AdminBundleModal";
const invoke = vi.fn();
vi.mock("@tauri-apps/api/core", () => ({
invoke: (cmd: string, args?: unknown) => invoke(cmd, args),
}));
describe("AdminBundleModal", () => {
beforeEach(() => vi.clearAllMocks());
it("saves the bundle and shows the folder and the two commands, with Copy", async () => {
invoke.mockResolvedValue("/home/me/triple-c-onboard-dev");
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });
render(
<AdminBundleModal connectionId="h1" region="eu-west-1" kind="user_onboard" environment="dev" ownerId="AIDAEXAMPLE" onClose={vi.fn()} />,
);
expect(screen.getByRole("dialog", { name: "Onboarding bundle" })).toBeInTheDocument();
expect(screen.getByText(/environment admin/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" }));
expect(await screen.findByText("/home/me/triple-c-onboard-dev")).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", {
connectionId: "h1",
region: "eu-west-1",
kind: "user_onboard",
environment: "dev",
ownerId: "AIDAEXAMPLE",
network: null,
});
const commands = "tofu init -backend-config=backend.hcl\ntofu apply";
expect(screen.getByText((_, el) => el?.tagName === "PRE" && el.textContent === commands)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Copy commands" }));
await waitFor(() => expect(writeText).toHaveBeenCalledWith(commands));
});
it("shows nothing new when the folder picker is dismissed", async () => {
invoke.mockResolvedValue(null);
render(<AdminBundleModal connectionId="h1" region="eu-west-1" kind="permissions_boundary" onClose={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() => expect(invoke).toHaveBeenCalled());
expect(screen.queryByRole("button", { name: "Copy commands" })).toBeNull();
});
it("an environment bundle asks for the name and network", async () => {
invoke.mockResolvedValue("/tmp/env");
render(<AdminBundleModal connectionId="h1" region="eu-west-1" kind="environment" onClose={vi.fn()} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "team" } });
fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" }));
fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", {
connectionId: "h1",
region: "eu-west-1",
kind: "environment",
environment: "team",
ownerId: null,
network: { mode: "private-nat" },
}),
);
});
it("shows a save failure through the AWS error copy", async () => {
invoke.mockRejectedValue({ kind: "sso_expired", profile: "prod-sso" });
render(<AdminBundleModal connectionId="h1" region="eu-west-1" kind="permissions_boundary" onClose={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" }));
expect(await screen.findByText("Your SSO session for profile prod-sso has expired.")).toBeInTheDocument();
});
});
@@ -0,0 +1,152 @@
import { useState } from "react";
import { saveAwsAdminBundle } from "../../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../../lib/aws-error";
import type { AwsError, ModuleKind, NetworkChoice } from "../../../lib/types";
import Button from "../../ui/Button";
import Field, { inputClass } from "../../ui/Field";
import Modal from "../../ui/Modal";
import NetworkFields from "./NetworkFields";
import { DEFAULT_NETWORK, environmentNameError, networkFromDraft, type NetworkDraft } from "./environmentFormat";
const COMMANDS = "tofu init -backend-config=backend.hcl\ntofu apply";
const TITLE: Record<ModuleKind, string> = {
environment: "Environment bundle",
user_onboard: "Onboarding bundle",
permissions_boundary: "Permissions boundary bundle",
};
/**
* An admin request (D5): Triple-C writes the module, `backend.hcl`,
* `terraform.tfvars.json` and a README into a folder picked in Rust, and the
* admin runs the two commands from there.
*/
export default function AdminBundleModal({
connectionId,
region,
kind,
environment,
ownerId,
network,
reason,
onClose,
}: {
connectionId: string;
region: string;
kind: ModuleKind;
/** Fixed environment; when absent for an environment bundle, the user picks it here. */
environment?: string;
ownerId?: string;
network?: NetworkChoice;
/** Why the bundle is needed (e.g. the refusal that led here). */
reason?: string;
onClose: () => void;
}) {
const askEnvironment = kind === "environment" && !environment;
const [name, setName] = useState("main");
const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState<string | null>(null);
const [error, setError] = useState<AwsError | null>(null);
const [copyNote, setCopyNote] = useState<string | null>(null);
const nameError = askEnvironment ? environmentNameError(name) : null;
const picked = askEnvironment ? networkFromDraft(draft) : null;
const ready = !nameError && (!picked || "network" in picked);
const save = async () => {
setSaving(true);
setError(null);
try {
const folder = await saveAwsAdminBundle(connectionId, region, kind, {
environment: askEnvironment ? name : environment,
ownerId,
network: picked && "network" in picked ? picked.network : network,
});
if (folder) setSaved(folder);
} catch (e) {
setError(toAwsError(e));
} finally {
setSaving(false);
}
};
const copy = async () => {
try {
await navigator.clipboard.writeText(COMMANDS);
setCopyNote("Commands copied.");
} catch (e) {
setCopyNote(`Could not copy: ${awsErrorMessage(toAwsError(e))}`);
}
};
return (
<Modal
title={TITLE[kind]}
onClose={onClose}
footer={
<Button size="md" onClick={onClose}>
Close
</Button>
}
>
<div className="space-y-3 text-xs text-[var(--text-secondary)] leading-snug">
{reason && (
<p role="alert" className="text-[var(--warning)]">
Doing this from here was refused: {reason}
</p>
)}
{kind === "environment" && (
<p>
Deploying an environment needs an environment admin. Triple-C writes the OpenTofu module with its
backend settings and variables into a folder; send it to an admin, who deploys it from there.
</p>
)}
{kind === "user_onboard" && (
<p>
Joining {environment} needs your own task role and file system, which an environment admin creates
by applying this bundle. Send them the folder; once it's applied, Detect again shows you as joined.
</p>
)}
{kind === "permissions_boundary" && (
<p>
Every role Triple-C creates is capped by the account's permissions boundary, and creating it needs an
account administrator. Send them this folder.
</p>
)}
<p>The bundle works with OpenTofu or Terraform 1.10 and later. Its README lists every step.</p>
{askEnvironment && (
<div className="space-y-3">
<Field label="Name" hint={nameError ?? undefined}>
{(id) => <input id={id} className={inputClass} value={name} onChange={(e) => setName(e.target.value)} />}
</Field>
<NetworkFields value={draft} onChange={setDraft} error={picked && "error" in picked ? picked.error : null} />
</div>
)}
<Button size="md" variant="primary" onClick={save} disabled={saving || !ready}>
{saving ? "Saving…" : "Save bundle to folder…"}
</Button>
{error && (
<p role="alert" className="text-[var(--error)]">
{awsErrorMessage(error)}
</p>
)}
{saved && (
<div className="space-y-1.5">
<p>
Saved to <code className="font-mono text-[var(--text-primary)] break-all">{saved}</code>
</p>
<p>From that folder, run:</p>
<pre className="font-mono text-[var(--text-primary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 whitespace-pre-wrap">
{COMMANDS}
</pre>
<Button size="sm" onClick={copy}>
Copy commands
</Button>
{copyNote && <p role="status">{copyNote}</p>}
</div>
)}
</div>
</Modal>
);
}
@@ -0,0 +1,156 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import DeployEnvironmentModal from "./DeployEnvironmentModal";
import type { DeployProgress } from "../../../lib/types";
import { conn, env, progress, scan, tofuEvent } from "./testkit";
const invoke = vi.fn();
vi.mock("@tauri-apps/api/core", () => ({
invoke: (cmd: string, args?: unknown) => invoke(cmd, args),
}));
type Handler = (e: { payload: DeployProgress }) => void;
const handlers = new Set<Handler>();
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async (_name: string, handler: Handler) => {
handlers.add(handler);
return () => handlers.delete(handler);
}),
}));
function emit(p: DeployProgress) {
act(() => {
for (const h of [...handlers]) h({ payload: p });
});
}
const BOUNDARY_KEY = "boundary/terraform.tfstate";
function renderModal(over: Partial<Parameters<typeof DeployEnvironmentModal>[0]> = {}) {
const props = {
connectionId: conn.id,
region: "eu-west-1",
scan: scan(),
onClose: vi.fn(),
onDeploy: vi.fn().mockResolvedValue(null),
onDetect: vi.fn(),
...over,
};
render(<DeployEnvironmentModal {...props} />);
return props;
}
describe("DeployEnvironmentModal", () => {
beforeEach(() => {
vi.clearAllMocks();
handlers.clear();
});
it("the public network mode is the default and says it costs nothing", () => {
const props = renderModal();
expect(screen.getByRole("radio", { name: "Public" })).toHaveAttribute("aria-checked", "true");
expect(screen.getByText("$0 — tasks get a public IP, no inbound access")).toBeInTheDocument();
expect(screen.getByText("First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB).")).toBeInTheDocument();
fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" }));
expect(screen.getByText("about $33/month for the NAT gateway")).toBeInTheDocument();
fireEvent.click(screen.getByRole("radio", { name: "Public" }));
expect(screen.getByLabelText("Name")).toHaveValue("main");
fireEvent.click(screen.getByRole("button", { name: "Deploy" }));
expect(props.onDeploy).toHaveBeenCalledWith("main", { mode: "public" });
});
it("validates the name with the backend's rule", () => {
const props = renderModal({ scan: scan({ environments: [env({ name: "main" })] }) });
const deploy = screen.getByRole("button", { name: "Deploy" });
expect(screen.getByText(/already exists/)).toBeInTheDocument();
expect(deploy).toBeDisabled();
for (const bad of ["Dev", "a--b", "dev-", "1dev", "a".repeat(21), ""]) {
fireEvent.change(screen.getByLabelText("Name"), { target: { value: bad } });
expect(deploy).toBeDisabled();
}
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "team-2" } });
expect(deploy).toBeEnabled();
fireEvent.click(deploy);
expect(props.onDeploy).toHaveBeenCalledWith("team-2", { mode: "public" });
});
it("an existing network needs a VPC and two distinct subnets", () => {
const props = renderModal();
fireEvent.click(screen.getByRole("radio", { name: "Existing VPC" }));
const deploy = screen.getByRole("button", { name: "Deploy" });
expect(deploy).toBeDisabled();
fireEvent.change(screen.getByLabelText("VPC ID"), { target: { value: "vpc-0123abcd" } });
fireEvent.change(screen.getByLabelText("Subnet ID 1"), { target: { value: "subnet-0123abcd" } });
fireEvent.change(screen.getByLabelText("Subnet ID 2"), { target: { value: "subnet-0123abcd" } });
expect(deploy).toBeDisabled();
fireEvent.change(screen.getByLabelText("Subnet ID 2"), { target: { value: "subnet-4567abcd" } });
fireEvent.click(screen.getByRole("switch", { name: "Assign a public IP" }));
fireEvent.click(deploy);
expect(props.onDeploy).toHaveBeenCalledWith("main", {
mode: "existing",
vpc_id: "vpc-0123abcd",
subnet_ids: ["subnet-0123abcd", "subnet-4567abcd"],
assign_public_ip: true,
});
});
it("keeps the dialog open and shows the server's refusal", async () => {
const props = renderModal({
onDeploy: vi.fn().mockResolvedValue({ kind: "other", message: "A deployment is starting for environment \"main\"; wait for it" }),
});
fireEvent.click(screen.getByRole("button", { name: "Deploy" }));
expect(await screen.findByText(/A deployment is starting/)).toBeInTheDocument();
expect(props.onClose).not.toHaveBeenCalled();
});
it("deploy modal blocks on a missing boundary and offers to create it", async () => {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "deploy_aws_permissions_boundary") return "b1";
throw new Error(`unexpected ${cmd}`);
});
const props = renderModal({ scan: scan({ boundary: "no" }) });
expect(screen.queryByLabelText("Name")).toBeNull();
expect(screen.queryByRole("button", { name: "Deploy" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Create the permissions boundary (needs an account administrator)" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("deploy_aws_permissions_boundary", { connectionId: "h1", region: "eu-west-1" }),
);
emit(progress({ op_id: "b1", state_key: BOUNDARY_KEY, events: [tofuEvent("Creating boundary")] }));
expect(screen.getByText("Creating boundary")).toBeInTheDocument();
emit(progress({ op_id: "b1", state_key: BOUNDARY_KEY, done: true, cancellable: false, result: { ok: true, exit_code: 0, summary: "Apply complete!" } }));
expect(await screen.findByLabelText("Name")).toBeInTheDocument();
expect(props.onDetect).toHaveBeenCalled();
});
it("opens the boundary bundle when creating the boundary is denied", async () => {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "deploy_aws_permissions_boundary") throw { kind: "access_denied", action: "iam:CreatePolicy", message: "denied iam:CreatePolicy" };
if (cmd === "save_aws_admin_bundle") return "/tmp/b";
throw new Error(`unexpected ${cmd}`);
});
renderModal({ scan: scan({ boundary: "no" }) });
fireEvent.click(screen.getByRole("button", { name: "Create the permissions boundary (needs an account administrator)" }));
const dialog = await screen.findByRole("dialog", { name: "Permissions boundary bundle" });
expect(within(dialog).getByText(/denied iam:CreatePolicy/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", {
connectionId: "h1",
region: "eu-west-1",
kind: "permissions_boundary",
environment: null,
ownerId: null,
network: null,
}),
);
});
it("repairs a named environment and warns that a different network replaces it", () => {
const props = renderModal({ repair: "dev" });
expect(screen.getByRole("dialog", { name: "Repair dev" })).toBeInTheDocument();
expect(screen.queryByLabelText("Name")).toBeNull();
expect(screen.getByText(/different network than the one it was deployed with replaces/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" }));
fireEvent.click(screen.getByRole("button", { name: "Repair" }));
expect(props.onDeploy).toHaveBeenCalledWith("dev", { mode: "private-nat" });
});
});
@@ -0,0 +1,167 @@
import { useState } from "react";
import { deployAwsPermissionsBoundary } from "../../../lib/tauri-commands";
import { awsErrorMessage } from "../../../lib/aws-error";
import type { AwsError, EnvironmentScan, NetworkChoice } from "../../../lib/types";
import Button from "../../ui/Button";
import Field, { inputClass } from "../../ui/Field";
import Modal from "../../ui/Modal";
import AdminBundleModal from "./AdminBundleModal";
import DeployProgress, { useDeployRuns } from "./DeployProgress";
import NetworkFields from "./NetworkFields";
import {
BOUNDARY_STATE_KEY,
DEFAULT_NETWORK,
environmentNameError,
networkFromDraft,
type NetworkDraft,
} from "./environmentFormat";
/**
* Deploy a new environment (name + D4 network), or — with `repair` — pick the
* network for an environment that has no record to take it from. A missing
* permissions boundary is a first step before the form.
*/
export default function DeployEnvironmentModal({
connectionId,
region,
scan,
repair,
onClose,
onDeploy,
onDetect,
}: {
connectionId: string;
region: string;
scan: EnvironmentScan;
/** The environment to repair; absent for a new deploy. */
repair?: string;
onClose: () => void;
/** Starts the run; resolves to the command's error, or null once started. */
onDeploy: (name: string, network: NetworkChoice) => Promise<AwsError | null>;
onDetect: () => void;
}) {
const [name, setName] = useState("main");
const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<AwsError | null>(null);
const [boundaryDone, setBoundaryDone] = useState(false);
const [boundaryError, setBoundaryError] = useState<AwsError | null>(null);
const [bundle, setBundle] = useState<{ reason?: string } | null>(null);
const boundary = useDeployRuns(({ result }) => {
if (result?.ok) setBoundaryDone(true);
onDetect();
});
const boundaryRun = boundary.runs[BOUNDARY_STATE_KEY];
if (bundle) {
return (
<AdminBundleModal
connectionId={connectionId}
region={region}
kind="permissions_boundary"
reason={bundle.reason}
onClose={() => setBundle(null)}
/>
);
}
const needsBoundary = !repair && scan.boundary === "no" && !boundaryDone;
const target = repair ?? name;
const nameError = repair
? null
: environmentNameError(name) ??
(scan.environments.some((e) => e.name === name) ? `An environment named ${name} already exists here.` : null);
const picked = networkFromDraft(draft);
const ready = !nameError && "network" in picked && !submitting;
const createBoundary = async () => {
setBoundaryError(null);
const err = await boundary.start(BOUNDARY_STATE_KEY, region, "Permissions boundary", () =>
deployAwsPermissionsBoundary(connectionId, region),
);
if (err?.kind === "access_denied") setBundle({ reason: awsErrorMessage(err) });
else if (err) setBoundaryError(err);
};
const submit = async () => {
if (!("network" in picked)) return;
setSubmitting(true);
setError(null);
const err = await onDeploy(target, picked.network);
setSubmitting(false);
if (err) setError(err);
else onClose();
};
const verb = repair ? "Repair" : "Deploy";
return (
<Modal
title={repair ? `Repair ${repair}` : "Deploy a new environment"}
description={`In ${region}.`}
onClose={onClose}
footer={
<>
<Button size="md" onClick={onClose}>
Cancel
</Button>
{!needsBoundary && (
<Button size="md" variant="primary" onClick={submit} disabled={!ready}>
{submitting ? `${verb}ing…` : verb}
</Button>
)}
</>
}
>
{needsBoundary ? (
<div className="space-y-3 text-xs text-[var(--text-secondary)] leading-snug">
<p>
This account has no Triple-C permissions boundary yet. Every role an environment creates is capped by
it, so it comes first.
</p>
<div className="flex gap-2 flex-wrap">
<Button
size="md"
variant="primary"
onClick={createBoundary}
disabled={!!boundaryRun && !boundaryRun.done}
>
Create the permissions boundary (needs an account administrator)
</Button>
<Button size="md" onClick={() => setBundle({})}>
Save a bundle for an administrator instead
</Button>
</div>
{boundaryError && (
<p role="alert" className="text-[var(--error)]">
{awsErrorMessage(boundaryError)}
</p>
)}
{boundaryRun && <DeployProgress run={boundaryRun} connectionId={connectionId} />}
</div>
) : (
<div className="space-y-4">
{repair ? (
<p className="text-xs text-[var(--warning)] leading-snug">
{repair} has no record, so Triple-C can't tell which network it was deployed with. Choose the same one:
a different network than the one it was deployed with replaces the network resources (VPC, subnets,
NAT gateway).
</p>
) : (
<Field label="Name" hint={nameError ?? "Lowercase letters, digits and hyphens; up to 20 characters."}>
{(id) => <input id={id} className={inputClass} value={name} onChange={(e) => setName(e.target.value)} />}
</Field>
)}
<NetworkFields value={draft} onChange={setDraft} error={"error" in picked ? picked.error : null} />
<p className="text-xs text-[var(--text-secondary)] leading-snug">
First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB).
</p>
{error && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug">
{awsErrorMessage(error)}
</p>
)}
</div>
)}
</Modal>
);
}
@@ -0,0 +1,281 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import { cancelAwsDeployment } from "../../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../../lib/aws-error";
import {
AWS_DEPLOY_PROGRESS_EVENT,
type AwsError,
type DeployProgress as ProgressPayload,
type TofuEvent,
type TofuOutcome,
} from "../../../lib/types";
import Button from "../../ui/Button";
import Modal from "../../ui/Modal";
import StatusIndicator from "../../ui/StatusIndicator";
/** One OpenTofu run this view is showing: a start, or a follow of one already running. */
export interface DeployRun {
stateKey: string;
region: string;
label: string;
/** Null until the starting command resolves. */
opId: string | null;
events: TofuEvent[];
done: boolean;
cancellable: boolean;
result: TofuOutcome | null;
}
type Subscription = { unlisten: (() => void) | null };
/**
* Runs keyed by state key. `start` subscribes to `aws-deploy-progress` before
* invoking, keeps every event for the state key it started until the op id
* is known (the backend may emit just before the invoke resolves), then keeps
* only that op's events. Resolves to the command's error, or null once started.
*/
export function useDeployRuns(onDone?: (run: { stateKey: string; result: TofuOutcome | null }) => void) {
const [runs, setRuns] = useState<Record<string, DeployRun>>({});
const subs = useRef(new Map<string, Subscription>());
const mounted = useRef(true);
const onDoneRef = useRef(onDone);
onDoneRef.current = onDone;
useEffect(() => {
mounted.current = true;
const all = subs.current;
return () => {
mounted.current = false;
for (const s of all.values()) s.unlisten?.();
all.clear();
};
}, []);
const start = useCallback(
async (stateKey: string, region: string, label: string, run: () => Promise<string>): Promise<AwsError | null> => {
subs.current.get(stateKey)?.unlisten?.();
const sub: Subscription = { unlisten: null };
subs.current.set(stateKey, sub);
const current = () => mounted.current && subs.current.get(stateKey) === sub;
const stop = () => {
sub.unlisten?.();
sub.unlisten = null;
if (subs.current.get(stateKey) === sub) subs.current.delete(stateKey);
};
let opId: string | null = null;
const early: ProgressPayload[] = [];
const apply = (p: ProgressPayload) => {
setRuns((prev) => {
const r = prev[stateKey];
if (!r || r.opId !== p.op_id || r.done) return prev;
return {
...prev,
[stateKey]: {
...r,
events: p.events.length ? [...r.events, ...p.events] : r.events,
done: p.done,
cancellable: p.done ? false : p.cancellable,
result: p.result ?? r.result,
},
};
});
if (p.done) {
stop();
onDoneRef.current?.({ stateKey, result: p.result ?? null });
}
};
setRuns((prev) => ({
...prev,
[stateKey]: { stateKey, region, label, opId: null, events: [], done: false, cancellable: false, result: null },
}));
const unlisten = await listen<ProgressPayload>(AWS_DEPLOY_PROGRESS_EVENT, ({ payload }) => {
if (!current() || payload.state_key !== stateKey) return;
if (opId === null) early.push(payload);
else if (payload.op_id === opId) apply(payload);
});
if (!current()) {
unlisten();
return null;
}
sub.unlisten = unlisten;
try {
opId = await run();
} catch (e) {
stop();
if (mounted.current) {
setRuns((prev) => {
const { [stateKey]: _gone, ...rest } = prev;
return rest;
});
}
return toAwsError(e);
}
if (!current()) return null;
const id = opId;
setRuns((prev) => (prev[stateKey] ? { ...prev, [stateKey]: { ...prev[stateKey], opId: id } } : prev));
for (const p of early.splice(0)) if (p.op_id === id) apply(p);
return null;
},
[],
);
const dismiss = useCallback((stateKey: string) => {
setRuns((prev) => {
if (!prev[stateKey]?.done) return prev;
const { [stateKey]: _gone, ...rest } = prev;
return rest;
});
}, []);
return { runs, start, dismiss };
}
function EventLine({ e }: { e: TofuEvent }) {
const isError = e.level === "error";
return (
<li className="text-xs leading-snug">
{(e.resource || e.action) && (
<span className="mr-1.5">
{e.resource && <span className="font-mono text-[var(--text-primary)]">{e.resource}</span>}
{e.action && <span className="ml-1 text-[var(--text-secondary)]">{e.action}</span>}
</span>
)}
{isError ? (
<>
<span className="font-semibold text-[var(--error)]">Error: </span>
<pre className="whitespace-pre-wrap break-words font-mono text-[var(--error)]">{e.message}</pre>
</>
) : (
<span className="text-[var(--text-secondary)]">{e.message}</span>
)}
</li>
);
}
/** A run's events in order, its final result, and Cancel (after a confirmation). */
export default function DeployProgress({
run,
connectionId,
onDismiss,
}: {
run: DeployRun;
connectionId: string;
onDismiss?: () => void;
}) {
const [confirming, setConfirming] = useState(false);
const [cancelling, setCancelling] = useState(false);
const [cancelError, setCancelError] = useState<AwsError | null>(null);
const listRef = useRef<HTMLOListElement>(null);
useEffect(() => {
const el = listRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [run.events.length]);
const cancel = async () => {
setCancelling(true);
setCancelError(null);
try {
await cancelAwsDeployment(connectionId, run.region, run.stateKey);
setConfirming(false);
} catch (e) {
setCancelError(toAwsError(e));
} finally {
setCancelling(false);
}
};
const status = run.done
? null
: run.opId === null
? { tone: "busy" as const, label: "Starting…" }
: { tone: "busy" as const, label: "Running" };
return (
<section
aria-label={`${run.label} progress`}
className="space-y-1.5 border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 bg-[var(--bg-primary)]"
>
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="flex items-center gap-2 text-xs">
<span className="font-medium text-[var(--text-primary)]">{run.label}</span>
{status && <StatusIndicator tone={status.tone} label={status.label} />}
</div>
<div className="flex gap-1.5">
{!run.done && (
<Button
size="sm"
variant="danger"
disabled={!run.cancellable}
title={run.cancellable ? undefined : "This run can't be cancelled from here"}
onClick={() => setConfirming(true)}
>
Cancel deployment
</Button>
)}
{run.done && onDismiss && (
<Button size="sm" variant="ghost" onClick={onDismiss}>
Dismiss
</Button>
)}
</div>
</div>
{run.events.length > 0 && (
<ol ref={listRef} className="max-h-64 overflow-y-auto space-y-0.5">
{run.events.map((e, i) => (
<EventLine key={i} e={e} />
))}
</ol>
)}
{run.done && run.result && (
<p role="status" className="text-xs">
{run.result.ok ? (
<StatusIndicator tone="ok" label={`Finished${run.result.summary ? `: ${run.result.summary}` : ""}`} />
) : (
<StatusIndicator
tone="error"
label={`Failed (exit ${run.result.exit_code})${run.result.summary ? `: ${run.result.summary}` : ""}`}
/>
)}
</p>
)}
{cancelError && !confirming && (
<p role="alert" className="text-xs text-[var(--error)]">
{awsErrorMessage(cancelError)}
</p>
)}
{confirming && (
<Modal
title="Cancel this deployment?"
onClose={() => setConfirming(false)}
footer={
<>
<Button size="md" onClick={() => setConfirming(false)}>
Keep running
</Button>
<Button size="md" variant="danger" onClick={cancel} disabled={cancelling}>
Cancel deployment
</Button>
</>
}
>
<div className="space-y-2 text-xs text-[var(--text-secondary)] leading-snug">
<p>
OpenTofu stops gracefully and saves its state. Anything it already created stays; Repair or Update
finishes the job later.
</p>
{cancelError && (
<p role="alert" className="text-[var(--error)]">
{awsErrorMessage(cancelError)}
</p>
)}
</div>
</Modal>
)}
</section>
);
}
@@ -0,0 +1,329 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import EnvironmentsPanel from "./EnvironmentsPanel";
import type { DeployProgress, EnvironmentScan } from "../../../lib/types";
import { conn, env, progress, scan, tofuEvent } from "./testkit";
const invoke = vi.fn();
vi.mock("@tauri-apps/api/core", () => ({
invoke: (cmd: string, args?: unknown) => invoke(cmd, args),
}));
type Handler = (e: { payload: DeployProgress }) => void;
const handlers = new Set<Handler>();
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async (_name: string, handler: Handler) => {
handlers.add(handler);
return () => handlers.delete(handler);
}),
}));
function emit(p: DeployProgress) {
act(() => {
for (const h of [...handlers]) h({ payload: p });
});
}
/** Mock the backend: `detect` answers detection; `rest` answers everything else. */
function backend(detect: () => EnvironmentScan, rest: (cmd: string, args: unknown) => unknown = () => {
throw new Error("unexpected");
}) {
invoke.mockImplementation(async (cmd: string, args: unknown) => {
if (cmd === "detect_aws_environments") return detect();
return rest(cmd, args);
});
}
const detectCalls = () => invoke.mock.calls.filter((c) => c[0] === "detect_aws_environments").length;
async function open() {
fireEvent.click(screen.getByRole("button", { name: "Environments" }));
await waitFor(() => expect(detectCalls()).toBeGreaterThan(0));
}
describe("EnvironmentsPanel", () => {
beforeEach(() => {
vi.clearAllMocks();
handlers.clear();
});
it("detects in the connection's default region when opened, and again on a region change", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
expect(detectCalls()).toBe(0);
await open();
expect(invoke).toHaveBeenCalledWith("detect_aws_environments", { connectionId: "h1", region: "eu-west-1" });
fireEvent.change(screen.getByLabelText("Region"), { target: { value: "us-east-1" } });
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("detect_aws_environments", { connectionId: "h1", region: "us-east-1" }),
);
fireEvent.click(await screen.findByRole("button", { name: "Detect again" }));
await waitFor(() => expect(detectCalls()).toBe(3));
});
it("shows deploy as primary when nothing is found and the user is an admin", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
const deploy = await screen.findByRole("button", { name: "Deploy a new environment" });
expect(deploy.className).toContain("--accent-emphasis");
expect(screen.getByText(/No Triple-C environment in eu-west-1/)).toBeInTheDocument();
fireEvent.click(deploy);
expect(screen.getByRole("dialog", { name: "Deploy a new environment" })).toBeInTheDocument();
});
it("deploy is secondary when environments exist", async () => {
backend(() => scan({ environments: [env({ onboarding: { state: "joined" }, actions: [] })] }));
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
const deploy = await screen.findByRole("button", { name: "Deploy a new environment" });
expect(deploy.className).not.toContain("--accent-emphasis");
expect(within(screen.getByTestId("env-dev")).getByText("Joined")).toBeInTheDocument();
});
it("offers an admin bundle instead of deploy for a workspace user with nothing found", async () => {
backend(
() => scan(),
(cmd) => {
if (cmd === "aws_policy_document") return [{ name: "environment-admin.json", json: "{}" }];
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
expect(await screen.findByText(/needs an environment admin/)).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Show the environment-admin policies" }));
expect(await screen.findByText("environment-admin.json")).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "environment_admin" });
fireEvent.click(screen.getByRole("button", { name: "Request an environment from an admin…" }));
const dialog = screen.getByRole("dialog");
expect(within(dialog).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument();
});
it("treats a connection with no permission report as not an admin", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} />);
await open();
expect(await screen.findByRole("button", { name: "Request an environment from an admin…" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull();
});
it("an incomplete environment offers repair and destroy, destroy only after typing its name", async () => {
backend(
() => scan({ environments: [env({ state: { state: "incomplete", lock: null }, actions: ["repair", "destroy"], info: null, onboarding: null, template_version: null })] }),
(cmd) => {
if (cmd === "destroy_incomplete_aws_environment") return "op9";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
const row = await screen.findByTestId("env-dev");
expect(within(row).getByText("Incomplete")).toBeInTheDocument();
expect(within(row).getByRole("button", { name: "Repair dev" })).toBeInTheDocument();
// Repair without a record asks for the network and warns about a change.
fireEvent.click(within(row).getByRole("button", { name: "Repair dev" }));
const repair = screen.getByRole("dialog", { name: "Repair dev" });
expect(within(repair).getByRole("radio", { name: "Public" })).toHaveAttribute("aria-checked", "true");
expect(within(repair).getByText(/different network than the one it was deployed with replaces/)).toBeInTheDocument();
fireEvent.click(within(repair).getByRole("button", { name: "Cancel" }));
fireEvent.click(within(row).getByRole("button", { name: "Destroy dev" }));
const dialog = screen.getByRole("dialog", { name: "Destroy dev" });
const confirm = within(dialog).getByRole("button", { name: "Destroy" });
expect(confirm).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "de" } });
expect(confirm).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "dev" } });
expect(confirm).toBeEnabled();
fireEvent.click(confirm);
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("destroy_incomplete_aws_environment", {
connectionId: "h1",
region: "eu-west-1",
name: "dev",
}),
);
});
it("a stale lock offers unlock with its owner and age", async () => {
const lock = { who: "alice@laptop", created: "2026-11-14T07:00:00Z", operation: "OperationTypeApply", age_secs: 3 * 3600 + 300, local_process: false };
backend(
() => scan({ environments: [env({ state: { state: "incomplete", lock }, actions: ["repair", "unlock"], onboarding: null })] }),
(cmd) => {
if (cmd === "unlock_aws_state") return undefined;
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
const row = await screen.findByTestId("env-dev");
expect(within(row).getByText(/Locked by alice@laptop/)).toBeInTheDocument();
expect(within(row).getByText(/3 h 5 min ago/)).toBeInTheDocument();
expect(within(row).queryByRole("button", { name: "Destroy dev" })).toBeNull();
fireEvent.click(within(row).getByRole("button", { name: "Unlock dev" }));
const dialog = screen.getByRole("dialog", { name: "Unlock dev" });
expect(within(dialog).getByText(/alice@laptop/)).toBeInTheDocument();
expect(within(dialog).getByText(/3 h 5 min ago/)).toBeInTheDocument();
const confirm = within(dialog).getByRole("button", { name: "Unlock" });
expect(confirm).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "dev" } });
fireEvent.click(confirm);
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("unlock_aws_state", {
connectionId: "h1",
region: "eu-west-1",
stateKey: "environments/dev/terraform.tfstate",
}),
);
await waitFor(() => expect(detectCalls()).toBe(2));
});
it("shows the server's refusal when a lock is still held", async () => {
backend(
() => scan({ environments: [env({ state: { state: "incomplete", lock: null }, actions: ["repair", "destroy"], onboarding: null })] }),
(cmd) => {
if (cmd === "repair_aws_environment") throw { kind: "other", message: "The state is locked; Unlock first" };
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
// With a record, Repair runs straight away on the recorded network.
fireEvent.click(await screen.findByRole("button", { name: "Repair dev" }));
expect(await screen.findByText("The state is locked; Unlock first")).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("repair_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev", network: null });
});
it("join onboards an admin and shows progress until done, then re-detects", async () => {
const key = "users/dev/abc123abc123/terraform.tfstate";
let detects = 0;
backend(
() => {
detects += 1;
return scan({ environments: [env({ onboarding: detects > 1 ? { state: "joined" } : { state: "not_joined" } })] });
},
async (cmd) => {
if (cmd === "onboard_aws_user") {
// The backend can emit before the invoke resolves: an old follower's
// line (another op) and this run's first line.
emit(progress({ op_id: "old", state_key: key, events: [tofuEvent("stale line")] }));
emit(progress({ op_id: "op1", state_key: key, events: [tofuEvent("Planning")], cancellable: false }));
return "op1";
}
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
expect(await screen.findByText("Planning")).toBeInTheDocument();
expect(screen.queryByText("stale line")).toBeNull();
expect(invoke).toHaveBeenCalledWith("onboard_aws_user", { connectionId: "h1", region: "eu-west-1", environment: "dev" });
expect(screen.getByRole("button", { name: "Cancel deployment" })).toBeDisabled();
emit(progress({ op_id: "op1", state_key: key, events: [tofuEvent("Creating...", { resource: "aws_iam_role.task", action: "create" })] }));
expect(screen.getByText("aws_iam_role.task")).toBeInTheDocument();
emit(progress({ op_id: "other", state_key: "environments/x/terraform.tfstate", events: [tofuEvent("unrelated")] }));
expect(screen.queryByText("unrelated")).toBeNull();
expect(detectCalls()).toBe(1);
emit(progress({ op_id: "op1", state_key: key, events: [], done: true, cancellable: false, result: { ok: true, exit_code: 0, summary: "Apply complete! Resources: 4 added" } }));
expect(await screen.findByText(/Apply complete! Resources: 4 added/)).toBeInTheDocument();
await waitFor(() => expect(detectCalls()).toBe(2));
expect(await within(screen.getByTestId("env-dev")).findByText("Joined")).toBeInTheDocument();
});
it("a workspace user's join opens the onboarding bundle and waits for an admin", async () => {
backend(
() => scan({ environments: [env()] }),
(cmd) => {
if (cmd === "save_aws_admin_bundle") return "/home/me/onboard-dev";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
const dialog = screen.getByRole("dialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", {
connectionId: "h1",
region: "eu-west-1",
kind: "user_onboard",
environment: "dev",
ownerId: "AIDAEXAMPLEEXAMPLE01",
network: null,
}),
);
expect(invoke.mock.calls.some((c) => c[0] === "onboard_aws_user")).toBe(false);
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
expect(within(screen.getByTestId("env-dev")).getByText("Waiting for an admin to onboard you")).toBeInTheDocument();
});
it("follows a deployment running on this machine when opened, and cancels after confirming", async () => {
const lock = { who: "me@here", created: "x", operation: "OperationTypeApply", age_secs: 60, local_process: true };
backend(
() => scan({ environments: [env({ state: { state: "deploying", lock }, actions: ["follow"], onboarding: null })] }),
async (cmd) => {
if (cmd === "follow_aws_deployment") {
emit(progress({ op_id: "f1", events: [tofuEvent("replayed line")] }));
return "f1";
}
if (cmd === "cancel_aws_deployment") return undefined;
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
expect(await screen.findByText("replayed line")).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("follow_aws_deployment", {
connectionId: "h1",
region: "eu-west-1",
stateKey: "environments/dev/terraform.tfstate",
});
fireEvent.click(screen.getByRole("button", { name: "Cancel deployment" }));
const dialog = screen.getByRole("dialog", { name: "Cancel this deployment?" });
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel deployment" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("cancel_aws_deployment", {
connectionId: "h1",
region: "eu-west-1",
stateKey: "environments/dev/terraform.tfstate",
}),
);
});
it("shows a failed run's errors in full", async () => {
backend(
() => scan({ environments: [env({ state: { state: "update_available" }, actions: ["join", "update"], onboarding: { state: "joined" } })] }),
async (cmd) => {
if (cmd === "update_aws_environment") return "u1";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Update dev" }));
await waitFor(() => expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev" }));
const long = "Error: creating IAM Role (triple-c-dev-task): AccessDenied: User is not authorized to perform iam:CreateRole\n with aws_iam_role.task";
emit(progress({ op_id: "u1", events: [tofuEvent(long, { level: "error", kind: "diagnostic" })] }));
emit(progress({ op_id: "u1", events: [], done: true, cancellable: false, result: { ok: false, exit_code: 1, summary: "Apply failed" } }));
expect(await screen.findByText(/Failed \(exit 1\): Apply failed/)).toBeInTheDocument();
expect(screen.getByText((_, el) => el?.textContent === long && el.tagName === "PRE")).toBeInTheDocument();
});
it("routes a detection failure through the AWS error copy", async () => {
backend(() => {
throw { kind: "state_bucket_taken", bucket: "triple-c-tfstate-123456789012-eu-west-1" };
});
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
expect(
await screen.findByText("The state bucket name triple-c-tfstate-123456789012-eu-west-1 is already taken by another AWS account."),
).toBeInTheDocument();
});
});
@@ -0,0 +1,490 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import {
deployAwsEnvironment,
destroyIncompleteAwsEnvironment,
detectAwsEnvironments,
followAwsDeployment,
onboardAwsUser,
repairAwsEnvironment,
unlockAwsState,
updateAwsEnvironment,
} from "../../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../../lib/aws-error";
import type {
AwsError,
DetectedEnvironment,
EnvironmentScan,
HostConnection,
ModuleKind,
NetworkChoice,
PermissionSummary,
PolicyFile,
} 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 DeployEnvironmentModal from "./DeployEnvironmentModal";
import DeployProgress, { useDeployRuns, type DeployRun } from "./DeployProgress";
import PolicyFiles from "./PolicyFiles";
import {
COMMON_REGIONS,
environmentStateKey,
formatAge,
lockLine,
onboardingStateKey,
stateLock,
stateStatus,
} 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<AwsError | null>;
onClose: () => void;
}) {
const [typed, setTyped] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<AwsError | null>(null);
const confirm = async () => {
setBusy(true);
setError(null);
const err = await onConfirm();
setBusy(false);
if (err) setError(err);
else onClose();
};
return (
<Modal
title={title}
onClose={onClose}
footer={
<>
<Button size="md" onClick={onClose}>
Cancel
</Button>
<Button size="md" variant="danger" onClick={confirm} disabled={typed !== name || busy}>
{confirmLabel}
</Button>
</>
}
>
<div className="space-y-3 text-xs text-[var(--text-secondary)] leading-snug">
{children}
<Field label={`Type ${name} to confirm`}>
{(id) => (
<input id={id} className={inputClass} autoComplete="off" value={typed} onChange={(e) => setTyped(e.target.value)} />
)}
</Field>
{error && (
<p role="alert" className="text-[var(--error)]">
{awsErrorMessage(error)}
</p>
)}
</div>
</Modal>
);
}
type Bundle = { kind: ModuleKind; environment?: string; ownerId?: string };
/** 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 for this caller's tier.
*/
export default function EnvironmentsPanel({
connection,
tier,
}: {
connection: HostConnection;
/** The connection's last permission report; absent means unknown, treated as not 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<EnvironmentScan | null>(null);
const [detecting, setDetecting] = useState(false);
const [detectError, setDetectError] = useState<AwsError | null>(null);
const [rowErrors, setRowErrors] = useState<Record<string, AwsError>>({});
const [pending, setPending] = useState<Record<string, boolean>>({});
const [waiting, setWaiting] = useState<Set<string>>(new Set());
const [deployOpen, setDeployOpen] = useState(false);
const [repairOf, setRepairOf] = useState<string | null>(null);
const [destroyOf, setDestroyOf] = useState<string | null>(null);
const [unlockOf, setUnlockOf] = useState<DetectedEnvironment | null>(null);
const [bundle, setBundle] = useState<Bundle | null>(null);
const [copyNote, setCopyNote] = useState<string | null>(null);
const request = useRef(0);
const followed = useRef(new Set<string>());
const detect = useCallback(async () => {
const id = ++request.current;
setDetecting(true);
setDetectError(null);
try {
const found = await detectAwsEnvironments(connection.id, region);
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]);
const launch = useCallback(
async (envName: string, stateKey: string, label: string, run: () => Promise<string>) => {
setRowErrors(({ [envName]: _gone, ...rest }) => rest);
setPending((p) => ({ ...p, [envName]: true }));
const err = await start(stateKey, region, label, run);
setPending(({ [envName]: _gone, ...rest }) => rest);
if (err) setRowErrors((r) => ({ ...r, [envName]: err }));
return err;
},
[start, region],
);
// Reattach to a deploy running on this machine (a re-follow replays its whole log).
useEffect(() => {
if (!scan) return;
for (const e of scan.environments) {
const key = environmentStateKey(e.name);
const seen = `${scan.region}:${key}`;
if (e.actions.includes("follow") && !runs[key] && !followed.current.has(seen)) {
followed.current.add(seen);
void launch(e.name, key, `Deploy of ${e.name}`, () => followAwsDeployment(connection.id, scan.region, key));
}
}
}, [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))}`);
}
};
const deploy = (name: string, network: NetworkChoice) =>
launch(name, environmentStateKey(name), `Deploy of ${name}`, () =>
deployAwsEnvironment(connection.id, region, name, network),
);
const repair = (name: string, network?: NetworkChoice) =>
launch(name, environmentStateKey(name), `Repair of ${name}`, () =>
repairAwsEnvironment(connection.id, region, name, network),
);
const join = (e: DetectedEnvironment) => {
if (!scan) return;
if (isAdmin) {
void launch(e.name, onboardingStateKey(e.name, scan.owner_key), `Joining ${e.name}`, () =>
onboardAwsUser(connection.id, region, e.name),
);
} else {
setWaiting((w) => new Set(w).add(e.name));
setBundle({ kind: "user_onboard", environment: e.name, ownerId: scan.owner_id });
}
};
const rowRuns = (name: string) =>
Object.values(runs).filter((r) => r.region === region && runEnvironment(r.stateKey) === name);
const shown = new Set(scan?.environments.map((e) => e.name) ?? []);
const looseRuns = Object.values(runs).filter(
(r) => r.region !== region || !shown.has(runEnvironment(r.stateKey) ?? ""),
);
const progress = (r: DeployRun) => (
<DeployProgress
key={`${r.region}:${r.stateKey}`}
run={r}
connectionId={connection.id}
onDismiss={() => dismiss(r.stateKey)}
/>
);
const envRow = (e: DetectedEnvironment) => {
const status = stateStatus(e.state);
const lock = stateLock(e.state);
const has = (a: DetectedEnvironment["actions"][number]) => e.actions.includes(a);
const onboarding = e.onboarding?.state;
const busy = !!pending[e.name];
const rowError = rowErrors[e.name];
return (
<li
key={e.name}
data-testid={`env-${e.name}`}
className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 space-y-1.5"
>
<div className="flex items-start justify-between gap-2 flex-wrap">
<div className="min-w-0 space-y-0.5 text-xs">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[13px] font-medium text-[var(--text-primary)]">{e.name}</span>
<StatusIndicator tone={status.tone} label={status.label} />
{onboarding === "joined" && <StatusIndicator tone="ok" label="Joined" />}
{onboarding === "in_progress" && <StatusIndicator tone="busy" label="Onboarding in progress" />}
{onboarding === "incomplete" && <StatusIndicator tone="error" label="Onboarding incomplete" />}
</div>
<div className="text-[var(--text-secondary)]">
{e.template_version !== null ? `Module version ${e.template_version}` : "Module version unknown"}
{e.info && ` · ${e.info.network_mode} network`}
</div>
{lock && (
<div className="text-[var(--text-secondary)]">
{lockLine(lock)}
{lock.local_process && " · running on this machine"}
</div>
)}
{e.state.state === "unreadable_record" && (
<div className="text-[var(--error)]">The environment's record can't be used: {e.state.reason}</div>
)}
{!isAdmin && waiting.has(e.name) && onboarding !== "joined" && (
<div className="text-[var(--text-secondary)]">Waiting for an admin to onboard you</div>
)}
</div>
<div className="flex gap-1.5 flex-wrap">
{has("join") && onboarding !== "joined" && onboarding !== "in_progress" && (
<Button size="sm" variant="primary" disabled={busy} aria-label={`Join ${e.name}`} onClick={() => join(e)}>
{!isAdmin && waiting.has(e.name) ? "Show onboarding bundle" : "Join"}
</Button>
)}
{has("follow") && (
<Button
size="sm"
disabled={busy}
aria-label={`Follow ${e.name}`}
onClick={() => {
const key = environmentStateKey(e.name);
void launch(e.name, key, `Deploy of ${e.name}`, () => followAwsDeployment(connection.id, region, key));
}}
>
Follow
</Button>
)}
{has("update") && (
<Button
size="sm"
disabled={busy}
aria-label={`Update ${e.name}`}
onClick={() =>
void launch(e.name, environmentStateKey(e.name), `Update of ${e.name}`, () =>
updateAwsEnvironment(connection.id, region, e.name),
)
}
>
Update
</Button>
)}
{has("repair") && (
<Button
size="sm"
disabled={busy}
aria-label={`Repair ${e.name}`}
onClick={() => (e.info ? void repair(e.name) : setRepairOf(e.name))}
>
Repair
</Button>
)}
{has("unlock") && (
<Button size="sm" variant="danger" disabled={busy} aria-label={`Unlock ${e.name}`} onClick={() => setUnlockOf(e)}>
Unlock
</Button>
)}
{has("destroy") && (
<Button size="sm" variant="danger" disabled={busy} aria-label={`Destroy ${e.name}`} onClick={() => setDestroyOf(e.name)}>
Destroy
</Button>
)}
</div>
</div>
{rowError && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug">
{awsErrorMessage(rowError)}
</p>
)}
{rowRuns(e.name).map(progress)}
</li>
);
};
const nothingFound = !!scan && scan.environments.length === 0;
return (
<div className="pt-1.5 space-y-2">
<Button size="sm" variant="ghost" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<span aria-hidden="true">{open ? "▾" : "▸"}</span>
Environments
</Button>
{open && (
<div className="space-y-2 pl-1">
<div className="flex items-end gap-2 flex-wrap">
<Field label="Region">
{(id) => (
<select id={id} className={selectClass} value={region} onChange={(e) => setRegion(e.target.value)}>
{regions.map((r) => (
<option key={r} value={r}>
{r}
</option>
))}
</select>
)}
</Field>
<Button size="md" onClick={() => void detect()} disabled={detecting}>
Detect again
</Button>
</div>
{detecting && (
<p role="status" className="text-xs text-[var(--text-secondary)]">
Detecting…
</p>
)}
{detectError && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug">
{awsErrorMessage(detectError)}
</p>
)}
{scan && isAdmin && scan.boundary === "no" && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
This account has no Triple-C permissions boundary yet; deploying creates it first.
</p>
)}
{scan && scan.environments.length > 0 && <ul className="space-y-1.5">{scan.environments.map(envRow)}</ul>}
{nothingFound && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
No Triple-C environment in {scan.region}.
{!isAdmin &&
" Deploying one needs an environment admin: attach the environment-admin policies to an identity, or send an admin a bundle to deploy."}
{!tier && " Run Check to find out whether you can deploy one yourself."}
</p>
)}
{scan && isAdmin && (
<Button size="md" variant={nothingFound ? "primary" : "secondary"} onClick={() => setDeployOpen(true)}>
Deploy a new environment
</Button>
)}
{nothingFound && !isAdmin && (
<div className="space-y-2">
<PolicyFiles tier="environment_admin" label="Show the environment-admin policies" onCopy={copy} />
<Button size="md" onClick={() => setBundle({ kind: "environment" })}>
Request an environment from an admin…
</Button>
{copyNote && (
<p role="status" className="text-xs text-[var(--text-secondary)]">
{copyNote}
</p>
)}
</div>
)}
{looseRuns.map(progress)}
</div>
)}
{scan && (deployOpen || repairOf) && (
<DeployEnvironmentModal
connectionId={connection.id}
region={region}
scan={scan}
repair={repairOf ?? undefined}
onClose={() => {
setDeployOpen(false);
setRepairOf(null);
}}
onDeploy={repairOf ? (name, network) => repair(name, network) : deploy}
onDetect={() => void detect()}
/>
)}
{destroyOf && (
<TypedConfirmModal
title={`Destroy ${destroyOf}`}
name={destroyOf}
confirmLabel="Destroy"
onClose={() => setDestroyOf(null)}
onConfirm={() =>
launch(destroyOf, environmentStateKey(destroyOf), `Destroy of ${destroyOf}`, () =>
destroyIncompleteAwsEnvironment(connection.id, region, destroyOf),
)
}
>
<p>
{destroyOf} never finished deploying, so OpenTofu removes everything it created for it. This can't be
undone.
</p>
</TypedConfirmModal>
)}
{unlockOf && (
<TypedConfirmModal
title={`Unlock ${unlockOf.name}`}
name={unlockOf.name}
confirmLabel="Unlock"
onClose={() => setUnlockOf(null)}
onConfirm={async () => {
try {
await unlockAwsState(connection.id, region, environmentStateKey(unlockOf.name));
} catch (e) {
return toAwsError(e);
}
void detect();
return null;
}}
>
{(() => {
const lock = stateLock(unlockOf.state);
return lock ? (
<p>
Held by <span className="font-mono text-[var(--text-primary)]">{lock.who || "unknown"}</span> since{" "}
{formatAge(lock.age_secs)} ago ({lock.created}
{lock.operation && `, ${lock.operation}`}).
</p>
) : null;
})()}
<p className="text-[var(--warning)]">
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.
</p>
</TypedConfirmModal>
)}
{bundle && (
<AdminBundleModal
connectionId={connection.id}
region={region}
kind={bundle.kind}
environment={bundle.environment}
ownerId={bundle.ownerId}
onClose={() => setBundle(null)}
/>
)}
</div>
);
}
@@ -0,0 +1,67 @@
import type { NetworkChoice } from "../../../lib/types";
import Field, { SwitchRow, monoInputClass } from "../../ui/Field";
import SegmentedControl from "../../ui/SegmentedControl";
import Toggle from "../../ui/Toggle";
import type { NetworkDraft } from "./environmentFormat";
/** D4's modes and their cost lines. */
const COST: Record<NetworkChoice["mode"], string> = {
public: "$0 — tasks get a public IP, no inbound access",
"private-nat": "about $33/month for the NAT gateway",
existing: "No new network resources — tasks run in your VPC and two subnets in different availability zones",
};
/** The network picker shared by deploy, repair and the environment bundle. */
export default function NetworkFields({
value,
onChange,
error,
}: {
value: NetworkDraft;
onChange: (next: NetworkDraft) => void;
/** Why the existing-VPC fields aren't usable yet. */
error?: string | null;
}) {
const set = (patch: Partial<NetworkDraft>) => onChange({ ...value, ...patch });
return (
<div className="space-y-2">
<div className="text-[13px] font-medium text-[var(--text-primary)]">Network</div>
<SegmentedControl<NetworkChoice["mode"]>
label="Network"
value={value.mode}
onChange={(mode) => set({ mode })}
segments={[
{ value: "public", label: "Public" },
{ value: "private-nat", label: "Private + NAT" },
{ value: "existing", label: "Existing VPC" },
]}
/>
<p className="text-xs text-[var(--text-secondary)] leading-snug">{COST[value.mode]}</p>
{value.mode === "existing" && (
<div className="space-y-2">
<Field label="VPC ID">
{(id) => (
<input id={id} className={monoInputClass} placeholder="vpc-0123456789abcdef0" value={value.vpcId} onChange={(e) => set({ vpcId: e.target.value })} />
)}
</Field>
<Field label="Subnet ID 1">
{(id) => (
<input id={id} className={monoInputClass} placeholder="subnet-…" value={value.subnet1} onChange={(e) => set({ subnet1: e.target.value })} />
)}
</Field>
<Field label="Subnet ID 2">
{(id) => (
<input id={id} className={monoInputClass} placeholder="subnet-…" value={value.subnet2} onChange={(e) => set({ subnet2: e.target.value })} />
)}
</Field>
<SwitchRow
label="Assign a public IP"
hint="Needed when the subnets have no NAT route to the internet. Tasks still get no inbound access."
control={<Toggle label="Assign a public IP" checked={value.assignPublicIp} onChange={(v) => set({ assignPublicIp: v })} />}
/>
{error && <p className="text-xs text-[var(--warning)] leading-snug">{error}</p>}
</div>
)}
</div>
);
}
@@ -0,0 +1,70 @@
import { useState } from "react";
import { awsPolicyDocument } from "../../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../../lib/aws-error";
import type { PolicyFile, Tier } from "../../../lib/types";
import Button from "../../ui/Button";
/** A tier's policy files, loaded on demand: each one shown and copied on its own. */
export default function PolicyFiles({
tier,
label,
onCopy,
}: {
tier: Tier;
label: string;
onCopy: (file: PolicyFile) => void;
}) {
const [files, setFiles] = useState<PolicyFile[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = async () => {
setError(null);
try {
setFiles(await awsPolicyDocument(tier));
} catch (e) {
setError(`Could not load the policy: ${awsErrorMessage(toAwsError(e))}`);
}
};
if (!files) {
return (
<div className="space-y-1">
<Button size="sm" onClick={load}>
{label}
</Button>
{error && (
<p role="alert" className="text-xs text-[var(--error)]">
{error}
</p>
)}
</div>
);
}
return (
<div className="space-y-1 text-xs">
<p className="text-[var(--text-secondary)]">
{tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "}
{files.length === 1
? "attach this file as a customer managed policy."
: `Attach all ${files.length} files, each as its own customer managed policy.`}
</p>
{files.map((f) => (
<div key={f.name} className="space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[var(--text-primary)]">{f.name}</span>
<Button size="sm" aria-label={`Copy ${f.name}`} onClick={() => onCopy(f)}>
Copy
</Button>
</div>
<details>
<summary className="cursor-pointer text-[var(--text-secondary)]">Show JSON</summary>
<pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all text-[var(--text-secondary)]">
{f.json}
</pre>
</details>
</div>
))}
</div>
);
}
@@ -0,0 +1,97 @@
// Pure helpers shared by the environments UI. The name and id rules mirror
// `aws/tofu_modules.rs`; the server re-validates everything.
import type { EnvironmentState, LockInfo, NetworkChoice } from "../../../lib/types";
import type { StatusTone } from "../../ui/StatusIndicator";
export const COMMON_REGIONS = [
"us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1",
"eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1",
"ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "ap-south-1",
"sa-east-1",
];
/** `validate_environment_name`: null when valid, else why not. */
export function environmentNameError(name: string): string | null {
const ok =
/^[a-z][a-z0-9-]{0,19}$/.test(name) && !name.endsWith("-") && !name.includes("--");
return ok
? null
: "Use 1 to 20 lowercase letters, digits and single hyphens, starting with a letter and not ending in a hyphen.";
}
/** `is_aws_id`: the prefix, then 8 or 17 lowercase hex characters. */
export function isAwsId(id: string, prefix: "vpc-" | "subnet-"): boolean {
return new RegExp(`^${prefix}([0-9a-f]{8}|[0-9a-f]{17})$`).test(id);
}
/** The fields behind the network picker, kept as text while the user types. */
export interface NetworkDraft {
mode: NetworkChoice["mode"];
vpcId: string;
subnet1: string;
subnet2: string;
assignPublicIp: boolean;
}
export const DEFAULT_NETWORK: NetworkDraft = {
mode: "public",
vpcId: "",
subnet1: "",
subnet2: "",
assignPublicIp: false,
};
/** The draft as a `NetworkChoice`, or why it can't be one yet. */
export function networkFromDraft(d: NetworkDraft): { network: NetworkChoice } | { error: string } {
if (d.mode === "public") return { network: { mode: "public" } };
if (d.mode === "private-nat") return { network: { mode: "private-nat" } };
const vpc = d.vpcId.trim();
const subnets = [d.subnet1.trim(), d.subnet2.trim()];
if (!isAwsId(vpc, "vpc-")) return { error: "Enter a VPC ID (vpc- and 8 or 17 hex characters)." };
if (!subnets.every((s) => isAwsId(s, "subnet-"))) {
return { error: "Enter two subnet IDs (subnet- and 8 or 17 hex characters), in different availability zones." };
}
if (subnets[0] === subnets[1]) return { error: "The two subnets must be different." };
return { network: { mode: "existing", vpc_id: vpc, subnet_ids: subnets, assign_public_ip: d.assignPublicIp } };
}
export const environmentStateKey = (env: string) => `environments/${env}/terraform.tfstate`;
export const onboardingStateKey = (env: string, ownerKey: string) => `users/${env}/${ownerKey}/terraform.tfstate`;
export const BOUNDARY_STATE_KEY = "boundary/terraform.tfstate";
/** "45 s", "12 min", "3 h 5 min", "2 days". */
export function formatAge(secs: number): string {
if (secs < 60) return `${Math.max(0, Math.floor(secs))} s`;
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins} min`;
const hours = Math.floor(mins / 60);
if (hours < 48) return mins % 60 ? `${hours} h ${mins % 60} min` : `${hours} h`;
return `${Math.floor(hours / 24)} days`;
}
/** "Locked by <who> · <age> ago (<operation>)". */
export function lockLine(lock: LockInfo): string {
const op = lock.operation ? ` (${lock.operation})` : "";
return `Locked by ${lock.who || "unknown"} · ${formatAge(lock.age_secs)} ago${op}`;
}
export function stateStatus(s: EnvironmentState): { tone: StatusTone; label: string } {
switch (s.state) {
case "ready":
return { tone: "ok", label: "Ready" };
case "update_available":
return { tone: "ok", label: "Update available" };
case "deploying":
return { tone: "busy", label: "Deploying" };
case "incomplete":
return { tone: "error", label: "Incomplete" };
case "externally_managed":
return { tone: "ok", label: "Available" };
case "unreadable_record":
return { tone: "error", label: "Unreadable record" };
}
}
export function stateLock(s: EnvironmentState): LockInfo | null {
return s.state === "deploying" || s.state === "incomplete" ? s.lock : null;
}
@@ -0,0 +1,64 @@
// Shared fixtures for the environments UI tests (not a test file itself).
import type {
DeployProgress,
DetectedEnvironment,
EnvironmentInfo,
EnvironmentScan,
HostConnection,
TofuEvent,
} from "../../../lib/types";
export const conn: HostConnection = {
id: "h1",
name: "Prod",
kind: { type: "aws", auth: { method: "profile", name: "prod-sso" }, default_region: "eu-west-1" },
};
export function scan(over: Partial<EnvironmentScan> = {}): EnvironmentScan {
return {
region: "eu-west-1",
account: "123456789012",
owner_id: "AIDAEXAMPLEEXAMPLE01",
owner_key: "abc123abc123",
state_bucket: "yes",
boundary: "yes",
environments: [],
...over,
};
}
export function info(name = "dev"): EnvironmentInfo {
return {
schema: 1,
name,
template_version: 1,
cluster_arn: `arn:aws:ecs:eu-west-1:123456789012:cluster/triple-c-${name}`,
security_group_id: "sg-0123abcd",
subnet_ids: ["subnet-0123abcd", "subnet-4567abcd"],
assign_public_ip: true,
kms_key_arn: "arn:aws:kms:eu-west-1:123456789012:key/k",
log_group: `/triple-c/${name}`,
network_mode: "public",
tenancy: "strict",
};
}
export function env(over: Partial<DetectedEnvironment> = {}): DetectedEnvironment {
return {
name: "dev",
template_version: 1,
state: { state: "ready" },
actions: ["join"],
info: info(over.name ?? "dev"),
onboarding: { state: "not_joined" },
...over,
};
}
export function tofuEvent(message: string, over: Partial<TofuEvent> = {}): TofuEvent {
return { ts: "2026-11-14T10:00:00Z", level: "info", kind: "apply_progress", resource: null, action: null, message, ...over };
}
export function progress(over: Partial<DeployProgress>): DeployProgress {
return { op_id: "op1", state_key: "environments/dev/terraform.tfstate", events: [], done: false, cancellable: true, ...over };
}
+16
View File
@@ -21,3 +21,19 @@ export function toAwsError(e: unknown): AwsError {
}
return { kind: "other", message: typeof e === "string" ? e : e instanceof Error ? e.message : "Unknown error" };
}
/** Human-readable copy for a failed AWS command; never raw JSON. */
export function awsErrorMessage(e: AwsError): string {
switch (e.kind) {
case "sso_expired":
return `Your SSO session for profile ${e.profile} has expired.`;
case "profile_not_found":
return `Profile ${e.profile} was not found in your AWS config, or has no credentials.`;
case "keys_missing":
return "The access keys for this connection are missing from the keychain. Remove and re-add the connection.";
case "state_bucket_taken":
return `The state bucket name ${e.bucket} is already taken by another AWS account.`;
default:
return e.message;
}
}