feat(aws): AWS project settings and the stop guard
Add Project picks Local or an AWS connection, a region and a ready, joined environment, with repositories instead of folders. The Config tab's Host section edits CPU/memory (valid pairs only), architecture, storage, ephemeral size, Spot, idle stop, WIP push and repositories, and can remove the AWS resources or move the project back to this machine. Docker access, VPN, port mappings and the gateway backend are disabled on AWS with the reason; the sandbox shows Off on AWS for now. Stop on an AWS workspace with unsaved work asks first (Push to WIP branch preselected); a failed start shows the task's last log lines; removing an AWS project can delete its saved files, and asks again when its connection is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
51042f5d9e
commit
eb7c6c7b21
25 files changed
+2065
-232
No files matched your search
@@ -1,6 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
|
||||
import AddProjectDialog from "./AddProjectDialog";
|
||||
import { useAppState } from "../../store/appState";
|
||||
import type { AppSettings, EnvironmentScan } from "../../lib/types";
|
||||
import { environment } from "../../test/awsFixtures";
|
||||
|
||||
const add = vi.fn();
|
||||
|
||||
@@ -12,6 +15,11 @@ vi.mock("@tauri-apps/plugin-dialog", () => ({
|
||||
open: vi.fn(async () => null),
|
||||
}));
|
||||
|
||||
const detectAwsEnvironments = vi.fn();
|
||||
vi.mock("../../lib/tauri-commands", () => ({
|
||||
detectAwsEnvironments: (c: string, r: string) => detectAwsEnvironments(c, r),
|
||||
}));
|
||||
|
||||
/** A promise whose resolution this test controls, so `loading` can be held open. */
|
||||
function deferred() {
|
||||
let resolve!: (v: unknown) => void;
|
||||
@@ -116,3 +124,94 @@ describe("AddProjectDialog", () => {
|
||||
expect(submitButton()).toHaveAccessibleDescription("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddProjectDialog on AWS", () => {
|
||||
const scan = (envs: EnvironmentScan["environments"]): EnvironmentScan => ({
|
||||
region: "eu-west-1",
|
||||
account: "111122223333",
|
||||
owner_id: "AROA:alice",
|
||||
owner_key: "abc",
|
||||
state_bucket: "yes",
|
||||
boundary: "yes",
|
||||
environments: envs,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAppState.setState({
|
||||
appSettings: {
|
||||
hosts: [
|
||||
{
|
||||
id: "c1",
|
||||
name: "Work account",
|
||||
kind: { type: "aws", auth: { method: "profile", name: "work" }, default_region: "eu-west-1" },
|
||||
},
|
||||
],
|
||||
} as unknown as AppSettings,
|
||||
});
|
||||
});
|
||||
|
||||
function chooseAws() {
|
||||
fireEvent.change(screen.getByLabelText("Runs on"), { target: { value: "c1" } });
|
||||
}
|
||||
|
||||
it("sends the host, placement and workspace with repositories instead of folders", async () => {
|
||||
detectAwsEnvironments.mockResolvedValue(
|
||||
scan([environment("staging", "deploying", true), environment("dev", "ready", true)]),
|
||||
);
|
||||
add.mockResolvedValue({ id: "p1" });
|
||||
const onClose = vi.fn();
|
||||
render(<AddProjectDialog onClose={onClose} />);
|
||||
chooseAws();
|
||||
expect(screen.getByLabelText("Region")).toHaveValue("eu-west-1");
|
||||
await waitFor(() => expect(screen.getByLabelText("Environment")).toHaveValue("dev"));
|
||||
expect(detectAwsEnvironments).toHaveBeenCalledWith("c1", "eu-west-1");
|
||||
expect(
|
||||
(screen.getByRole("option", { name: /staging/ }) as HTMLOptionElement).disabled,
|
||||
).toBe(true);
|
||||
expect(screen.queryByLabelText("Folder 1 host path")).toBeNull();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
|
||||
fireEvent.change(screen.getByLabelText("Repository 1 URL"), {
|
||||
target: { value: "git@github.com:org/api.git" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Repository 1 branch"), { target: { value: "develop" } });
|
||||
fireEvent.click(submitButton());
|
||||
|
||||
await waitFor(() => expect(add).toHaveBeenCalled());
|
||||
const [name, paths, host] = add.mock.calls[0];
|
||||
expect(name).toBe("api");
|
||||
expect(paths).toEqual([]);
|
||||
expect(host.hostId).toBe("c1");
|
||||
expect(host.awsPlacement).toEqual({ region: "eu-west-1", environment: "dev" });
|
||||
expect(host.aws.repos).toEqual([
|
||||
{ url: "git@github.com:org/api.git", branch: "develop", folder: "api" },
|
||||
]);
|
||||
expect(host.aws).toMatchObject({ cpu: 1024, memory_mib: 4096, wip_push_on_stop: true, task_arn: null });
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("points at Settings → Hosts when no environment is usable", async () => {
|
||||
detectAwsEnvironments.mockResolvedValue(scan([environment("dev", "ready", false)]));
|
||||
render(<AddProjectDialog onClose={vi.fn()} />);
|
||||
chooseAws();
|
||||
expect(await screen.findByText(/Settings → Hosts/)).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Environment")).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
|
||||
fireEvent.click(submitButton());
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(/Choose an environment/);
|
||||
expect(add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the backend's validation message when the add is refused", async () => {
|
||||
detectAwsEnvironments.mockResolvedValue(scan([environment("dev", "update_available", true)]));
|
||||
add.mockRejectedValue('Repository URL "ftp://x": use https://..., ssh://... or git@host:path');
|
||||
render(<AddProjectDialog onClose={vi.fn()} />);
|
||||
chooseAws();
|
||||
await waitFor(() => expect(screen.getByLabelText("Environment")).toHaveValue("dev"));
|
||||
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
|
||||
fireEvent.change(screen.getByLabelText("Repository 1 URL"), { target: { value: "ftp://x" } });
|
||||
fireEvent.click(submitButton());
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(/use https:\/\//);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,15 @@
|
||||
import { useId, useRef, useState } from "react";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { useProjects } from "../../hooks/useProjects";
|
||||
import type { ProjectPath } from "../../lib/types";
|
||||
import type { DetectedEnvironment, HostConnection, ProjectPath, RepoSource } from "../../lib/types";
|
||||
import { detectAwsEnvironments } from "../../lib/tauri-commands";
|
||||
import { awsErrorMessage, toAwsError } from "../../lib/aws-error";
|
||||
import { cleanRepos, defaultAwsWorkspace, environmentSelectable } from "../../lib/awsWorkspace";
|
||||
import { useAppState } from "../../store/appState";
|
||||
import Modal from "../ui/Modal";
|
||||
import Button from "../ui/Button";
|
||||
import { inputClass, monoInputClass } from "../ui/Field";
|
||||
import { inputClass, monoInputClass, selectClass } from "../ui/Field";
|
||||
import { RepoRows, emptyRepo } from "./RepoListEditor";
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
@@ -15,12 +20,36 @@ interface PathEntry {
|
||||
mount_name: string;
|
||||
}
|
||||
|
||||
/** Why an environment can't take a new project, for its disabled option. */
|
||||
function unavailableReason(env: DetectedEnvironment): string {
|
||||
const st = env.state.state;
|
||||
if (st !== "ready" && st !== "update_available") return st.replace(/_/g, " ");
|
||||
return "you have not joined it";
|
||||
}
|
||||
|
||||
type Scan =
|
||||
| { status: "idle" }
|
||||
| { status: "loading" }
|
||||
| { status: "error"; message: string }
|
||||
| { status: "done"; environments: DetectedEnvironment[] };
|
||||
|
||||
function basenameFromPath(p: string): string {
|
||||
return p.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "";
|
||||
}
|
||||
|
||||
/** Stable, so the store selector does not return a new array each render. */
|
||||
const NO_HOSTS: HostConnection[] = [];
|
||||
|
||||
export default function AddProjectDialog({ onClose }: Props) {
|
||||
const { add } = useProjects();
|
||||
const hosts = useAppState((s) => s.appSettings?.hosts ?? NO_HOSTS);
|
||||
const [hostId, setHostId] = useState<string>("");
|
||||
const connection = hosts.find((h) => h.id === hostId) ?? null;
|
||||
const [region, setRegion] = useState("");
|
||||
const [scanRegion, setScanRegion] = useState("");
|
||||
const [scan, setScan] = useState<Scan>({ status: "idle" });
|
||||
const [environment, setEnvironment] = useState("");
|
||||
const [repos, setRepos] = useState<RepoSource[]>([emptyRepo()]);
|
||||
const [name, setName] = useState("");
|
||||
const [pathEntries, setPathEntries] = useState<PathEntry[]>([
|
||||
{ host_path: "", mount_name: "" },
|
||||
@@ -30,6 +59,39 @@ export default function AddProjectDialog({ onClose }: Props) {
|
||||
const nameInputRef = useRef<HTMLInputElement>(null);
|
||||
const formId = useId();
|
||||
|
||||
// Look for environments when the connection or the region (on blur) changes.
|
||||
useEffect(() => {
|
||||
if (!connection || !scanRegion) {
|
||||
setScan({ status: "idle" });
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setScan({ status: "loading" });
|
||||
detectAwsEnvironments(connection.id, scanRegion).then(
|
||||
(found) => {
|
||||
if (cancelled) return;
|
||||
setScan({ status: "done", environments: found.environments });
|
||||
const first = found.environments.find(environmentSelectable);
|
||||
setEnvironment(first?.name ?? "");
|
||||
},
|
||||
(e) => {
|
||||
if (!cancelled) setScan({ status: "error", message: awsErrorMessage(toAwsError(e)) });
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connection, scanRegion]);
|
||||
|
||||
const chooseHost = (id: string) => {
|
||||
setHostId(id);
|
||||
setEnvironment("");
|
||||
const conn = hosts.find((h) => h.id === id);
|
||||
const r = conn?.kind.default_region ?? "";
|
||||
setRegion(r);
|
||||
setScanRegion(r);
|
||||
};
|
||||
|
||||
const handleBrowse = async (index: number) => {
|
||||
const selected = await open({ directory: true, multiple: false });
|
||||
if (typeof selected === "string") {
|
||||
@@ -63,6 +125,33 @@ export default function AddProjectDialog({ onClose }: Props) {
|
||||
setError("Project name is required");
|
||||
return;
|
||||
}
|
||||
if (connection) {
|
||||
if (!environment) {
|
||||
setError("Choose an environment to run the project in");
|
||||
return;
|
||||
}
|
||||
const cleaned = cleanRepos(repos);
|
||||
if (cleaned.some((r) => !r.url)) {
|
||||
setError("Every repository needs a URL");
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await add(name.trim(), [], {
|
||||
hostId: connection.id,
|
||||
awsPlacement: { region: scanRegion, environment },
|
||||
aws: { ...defaultAwsWorkspace(), repos: cleaned },
|
||||
});
|
||||
onClose();
|
||||
} catch (err) {
|
||||
// The backend's validation message (repository URL, folder, …).
|
||||
setError(String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const validPaths: ProjectPath[] = pathEntries
|
||||
.filter((p) => p.host_path.trim())
|
||||
.map((p) => ({
|
||||
@@ -137,62 +226,166 @@ export default function AddProjectDialog({ onClose }: Props) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium mb-1">Folders</span>
|
||||
<div className="space-y-2">
|
||||
{pathEntries.map((entry, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="space-y-1.5 p-2 bg-[var(--bg-primary)] rounded-[var(--radius-control)] border border-[var(--border-color)]"
|
||||
>
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
value={entry.host_path}
|
||||
onChange={(e) => updateEntry(i, "host_path", e.target.value)}
|
||||
placeholder="/path/to/folder"
|
||||
aria-label={`Folder ${i + 1} host path`}
|
||||
className={inputClass}
|
||||
/>
|
||||
<Button size="md" onClick={() => handleBrowse(i)}>
|
||||
Browse
|
||||
</Button>
|
||||
{pathEntries.length > 1 && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
aria-label={`Remove folder ${i + 1}`}
|
||||
onClick={() =>
|
||||
setPathEntries(pathEntries.filter((_, j) => j !== i))
|
||||
}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
|
||||
/workspace/
|
||||
</span>
|
||||
<input
|
||||
value={entry.mount_name}
|
||||
onChange={(e) => updateEntry(i, "mount_name", e.target.value)}
|
||||
placeholder="mount-name"
|
||||
aria-label={`Folder ${i + 1} mount name`}
|
||||
className={monoInputClass}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{hosts.length > 0 && (
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${formId}-host`}
|
||||
className="block text-[13px] font-medium mb-1"
|
||||
>
|
||||
Runs on
|
||||
</label>
|
||||
<select
|
||||
id={`${formId}-host`}
|
||||
value={hostId}
|
||||
onChange={(e) => chooseHost(e.target.value)}
|
||||
className={`w-full ${selectClass}`}
|
||||
>
|
||||
<option value="">This machine (Docker)</option>
|
||||
{hosts.map((h) => (
|
||||
<option key={h.id} value={h.id}>
|
||||
{h.name} (AWS)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<Button
|
||||
className="mt-2"
|
||||
onClick={() =>
|
||||
setPathEntries([...pathEntries, { host_path: "", mount_name: "" }])
|
||||
}
|
||||
>
|
||||
+ Add folder
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connection ? (
|
||||
<>
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${formId}-region`}
|
||||
className="block text-[13px] font-medium mb-1"
|
||||
>
|
||||
Region
|
||||
</label>
|
||||
<input
|
||||
id={`${formId}-region`}
|
||||
value={region}
|
||||
onChange={(e) => setRegion(e.target.value)}
|
||||
onBlur={() => setScanRegion(region.trim())}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
setScanRegion(region.trim());
|
||||
}
|
||||
}}
|
||||
className={monoInputClass}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${formId}-env`}
|
||||
className="block text-[13px] font-medium mb-1"
|
||||
>
|
||||
Environment
|
||||
</label>
|
||||
{scan.status === "loading" && (
|
||||
<p className="text-xs text-[var(--text-secondary)]">
|
||||
Looking for environments in {scanRegion}…
|
||||
</p>
|
||||
)}
|
||||
{scan.status === "error" && (
|
||||
<p className="text-xs text-[var(--error)]">{scan.message}</p>
|
||||
)}
|
||||
{scan.status === "done" && (
|
||||
<>
|
||||
{scan.environments.some(environmentSelectable) ? (
|
||||
<select
|
||||
id={`${formId}-env`}
|
||||
value={environment}
|
||||
onChange={(e) => setEnvironment(e.target.value)}
|
||||
className={`w-full ${selectClass}`}
|
||||
>
|
||||
{scan.environments.map((env) => (
|
||||
<option
|
||||
key={env.name}
|
||||
value={env.name}
|
||||
disabled={!environmentSelectable(env)}
|
||||
>
|
||||
{environmentSelectable(env)
|
||||
? env.name
|
||||
: `${env.name} — ${unavailableReason(env)}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<p className="text-xs text-[var(--text-secondary)]">
|
||||
No environment in {scanRegion} is ready for you to use. Deploy or join
|
||||
one in Settings → Hosts.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium mb-1">Repositories</span>
|
||||
<p className="mb-1.5 text-xs text-[var(--text-secondary)]">
|
||||
Cloned into <span className="font-mono">/workspace/<folder></span> when
|
||||
the workspace starts. Memory, storage and the rest are in the project’s
|
||||
Config tab.
|
||||
</p>
|
||||
<RepoRows rows={repos} onRowsChange={setRepos} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium mb-1">Folders</span>
|
||||
<div className="space-y-2">
|
||||
{pathEntries.map((entry, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="space-y-1.5 p-2 bg-[var(--bg-primary)] rounded-[var(--radius-control)] border border-[var(--border-color)]"
|
||||
>
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
value={entry.host_path}
|
||||
onChange={(e) => updateEntry(i, "host_path", e.target.value)}
|
||||
placeholder="/path/to/folder"
|
||||
aria-label={`Folder ${i + 1} host path`}
|
||||
className={inputClass}
|
||||
/>
|
||||
<Button size="md" onClick={() => handleBrowse(i)}>
|
||||
Browse
|
||||
</Button>
|
||||
{pathEntries.length > 1 && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
aria-label={`Remove folder ${i + 1}`}
|
||||
onClick={() =>
|
||||
setPathEntries(pathEntries.filter((_, j) => j !== i))
|
||||
}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
|
||||
/workspace/
|
||||
</span>
|
||||
<input
|
||||
value={entry.mount_name}
|
||||
onChange={(e) => updateEntry(i, "mount_name", e.target.value)}
|
||||
placeholder="mount-name"
|
||||
aria-label={`Folder ${i + 1} mount name`}
|
||||
className={monoInputClass}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
className="mt-2"
|
||||
onClick={() =>
|
||||
setPathEntries([...pathEntries, { host_path: "", mount_name: "" }])
|
||||
}
|
||||
>
|
||||
+ Add folder
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import ConfirmRemoveModal, { ConfirmForgetAwsModal } from "./ConfirmRemoveModal";
|
||||
|
||||
describe("ConfirmRemoveModal", () => {
|
||||
it("keeps an AWS workspace's saved files unless asked", () => {
|
||||
const onConfirm = vi.fn();
|
||||
render(<ConfirmRemoveModal projectName="api" aws onConfirm={onConfirm} onCancel={vi.fn()} />);
|
||||
const box = screen.getByRole("checkbox", { name: /saved files \(EFS\)/ });
|
||||
expect(box).not.toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
|
||||
fireEvent.click(box);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
|
||||
expect(onConfirm.mock.calls).toEqual([[{ discardData: false }], [{ discardData: true }]]);
|
||||
});
|
||||
|
||||
it("offers no EFS choice for a local project", () => {
|
||||
render(<ConfirmRemoveModal projectName="api" onConfirm={vi.fn()} onCancel={vi.fn()} />);
|
||||
expect(screen.queryByRole("checkbox")).toBeNull();
|
||||
expect(screen.getByText(/mounted in, not copied/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("says what is left in AWS when the connection is gone", () => {
|
||||
const onConfirm = vi.fn();
|
||||
render(
|
||||
<ConfirmForgetAwsModal
|
||||
projectName="api"
|
||||
reason="This project's AWS connection no longer exists"
|
||||
onConfirm={onConfirm}
|
||||
onCancel={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText(/task definitions, its secret and its saved files/)).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove and leave them in AWS" }));
|
||||
expect(onConfirm).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,20 @@
|
||||
import { useState } from "react";
|
||||
import Modal from "../ui/Modal";
|
||||
import Button from "../ui/Button";
|
||||
|
||||
interface Props {
|
||||
projectName: string;
|
||||
onConfirm: () => void;
|
||||
/** An AWS project: its task, task definitions and secret go instead of Docker state. */
|
||||
aws?: boolean;
|
||||
onConfirm: (opts: { discardData: boolean }) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }: Props) {
|
||||
const REMOVE_CLASS =
|
||||
"bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90";
|
||||
|
||||
export default function ConfirmRemoveModal({ projectName, aws = false, onConfirm, onCancel }: Props) {
|
||||
const [discardData, setDiscardData] = useState(false);
|
||||
return (
|
||||
<Modal
|
||||
title="Remove Project"
|
||||
@@ -18,34 +25,98 @@ export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }:
|
||||
<Button size="md" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
onClick={onConfirm}
|
||||
className="bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90"
|
||||
>
|
||||
<Button size="md" onClick={() => onConfirm({ discardData })} className={REMOVE_CLASS}>
|
||||
Remove
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{/*
|
||||
Everything remove_project() destroys, named. It removes the container,
|
||||
*both* named volumes (triple-c-home-{id} and triple-c-claude-config-{id}),
|
||||
the triple-c-snapshot-{id} image and the project's keychain secrets — so
|
||||
an accurate warning has to reach past "the config volume". The last
|
||||
sentence is the reassuring half and matters just as much: project folders
|
||||
are bind mounts from the host and nothing here touches them.
|
||||
*/}
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Are you sure you want to remove{" "}
|
||||
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This deletes
|
||||
its container, both of its volumes and its saved container image — so the home
|
||||
directory, the Claude login and config, installed skills, session transcripts,
|
||||
scheduled tasks and any stored credentials all go with it.
|
||||
</p>
|
||||
{aws ? (
|
||||
<>
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Are you sure you want to remove{" "}
|
||||
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This stops its
|
||||
workspace on AWS and removes its task definitions and its secret (the secret is
|
||||
deleted after AWS’s 7-day recovery window). Work that was not pushed to a
|
||||
remote is lost.
|
||||
</p>
|
||||
<label className="mt-3 flex items-start gap-2 text-[13px] text-[var(--text-primary)]">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={discardData}
|
||||
onChange={(e) => setDiscardData(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
Also delete the workspace’s saved files (EFS)
|
||||
<span className="block text-xs text-[var(--text-secondary)]">
|
||||
The Claude login, history and SSH keys kept between starts. Left in place
|
||||
otherwise.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/*
|
||||
Everything remove_project() destroys, named. It removes the container,
|
||||
*both* named volumes (triple-c-home-{id} and triple-c-claude-config-{id}),
|
||||
the triple-c-snapshot-{id} image and the project's keychain secrets — so
|
||||
an accurate warning has to reach past "the config volume". The last
|
||||
sentence is the reassuring half and matters just as much: project folders
|
||||
are bind mounts from the host and nothing here touches them.
|
||||
*/}
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Are you sure you want to remove{" "}
|
||||
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This deletes
|
||||
its container, both of its volumes and its saved container image — so the home
|
||||
directory, the Claude login and config, installed skills, session transcripts,
|
||||
scheduled tasks and any stored credentials all go with it.
|
||||
</p>
|
||||
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
|
||||
Your project folders on this machine are mounted in, not copied, and are left
|
||||
untouched.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** The second confirm when an AWS project's connection is gone. */
|
||||
export function ConfirmForgetAwsModal({
|
||||
projectName,
|
||||
reason,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
projectName: string;
|
||||
reason: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Modal
|
||||
title="Remove without its AWS resources?"
|
||||
onClose={onCancel}
|
||||
widthClassName="w-[28rem]"
|
||||
footer={
|
||||
<>
|
||||
<Button size="md" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button size="md" onClick={onConfirm} className={REMOVE_CLASS}>
|
||||
Remove and leave them in AWS
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">{reason}</p>
|
||||
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
|
||||
Your project folders on this machine are mounted in, not copied, and are left
|
||||
untouched.
|
||||
Removing <strong className="text-[var(--text-primary)]">{projectName}</strong> now
|
||||
leaves its AWS resources in the account: the task (which may still be running and
|
||||
billed), its task definitions, its secret and its saved files. You would have to
|
||||
remove them in AWS yourself.
|
||||
</p>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
@@ -4,6 +4,8 @@ import { useAppState, homeTabKey } from "../../store/appState";
|
||||
import { useProjectActions } from "../../hooks/useProjectActions";
|
||||
import { ProjectStatusIndicator } from "../ui/StatusIndicator";
|
||||
import { useUnavailable } from "../ui/unavailable";
|
||||
import { isAwsProject } from "../../lib/awsWorkspace";
|
||||
import StopGuardModal from "./StopGuardModal";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
@@ -23,8 +25,13 @@ export default function ProjectRow({ project }: Props) {
|
||||
progress: s.containerProgress[project.id],
|
||||
})),
|
||||
);
|
||||
const { busy, handleStart, handleStop, openClaudeTerminal } =
|
||||
const { busy, handleStart, handleStop, openClaudeTerminal, stopGuard, resolveStopGuard } =
|
||||
useProjectActions(project);
|
||||
const aws = isAwsProject(project);
|
||||
// An AWS project mounts nothing; its clones are what /workspace holds.
|
||||
const folders = aws
|
||||
? (project.aws?.repos ?? []).map((r) => r.folder)
|
||||
: project.paths.map((pp) => pp.mount_name);
|
||||
|
||||
const isSelected =
|
||||
activeTabKey === homeTabKey(project.id) || selectedProjectId === project.id;
|
||||
@@ -64,12 +71,17 @@ export default function ProjectRow({ project }: Props) {
|
||||
<span className="w-[3.75rem] flex-shrink-0" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="mt-0.5 ml-4 space-y-0.5 min-w-0">
|
||||
{project.paths.map((pp, i) => (
|
||||
{aws && (
|
||||
<div className="text-xs text-[var(--text-secondary)] truncate">
|
||||
AWS · {project.aws_placement?.environment ?? "?"} ({project.aws_placement?.region ?? "?"})
|
||||
</div>
|
||||
)}
|
||||
{folders.map((folder, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="text-xs text-[var(--text-secondary)] truncate font-mono"
|
||||
>
|
||||
/workspace/{pp.mount_name}
|
||||
/workspace/{folder}
|
||||
</div>
|
||||
))}
|
||||
<div className="text-xs">
|
||||
@@ -149,6 +161,9 @@ export default function ProjectRow({ project }: Props) {
|
||||
</button>
|
||||
{terminal.reasonNode}
|
||||
</div>
|
||||
{stopGuard && (
|
||||
<StopGuardModal projectName={project.name} work={stopGuard} onChoose={resolveStopGuard} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { RepoSource } from "../../lib/types";
|
||||
import { cleanRepos, repoFolderFromUrl } from "../../lib/awsWorkspace";
|
||||
import Button from "../ui/Button";
|
||||
import { inputClass, monoInputClass } from "../ui/Field";
|
||||
|
||||
export interface RepoRowsProps {
|
||||
rows: RepoSource[];
|
||||
onRowsChange: (rows: RepoSource[]) => void;
|
||||
/** Called when focus leaves a field (save-on-blur editors). */
|
||||
onCommit?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export const emptyRepo = (): RepoSource => ({ url: "", branch: null, folder: "" });
|
||||
|
||||
/** Rows of URL / branch / folder. The folder follows the URL until it is edited. */
|
||||
export function RepoRows({ rows, onRowsChange, onCommit, disabled = false }: RepoRowsProps) {
|
||||
const update = (i: number, patch: Partial<RepoSource>) => {
|
||||
const next = [...rows];
|
||||
next[i] = { ...next[i], ...patch };
|
||||
onRowsChange(next);
|
||||
};
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{rows.map((r, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="space-y-1.5 p-2 bg-[var(--bg-primary)] rounded-[var(--radius-control)] border border-[var(--border-color)]"
|
||||
>
|
||||
<input
|
||||
value={r.url}
|
||||
aria-label={`Repository ${i + 1} URL`}
|
||||
placeholder="git@github.com:org/repo.git or https://…"
|
||||
disabled={disabled}
|
||||
onChange={(e) => {
|
||||
const url = e.target.value;
|
||||
const followed = !r.folder || r.folder === repoFolderFromUrl(r.url);
|
||||
update(i, { url, ...(followed ? { folder: repoFolderFromUrl(url) } : {}) });
|
||||
}}
|
||||
onBlur={onCommit}
|
||||
className={monoInputClass}
|
||||
/>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
value={r.branch ?? ""}
|
||||
aria-label={`Repository ${i + 1} branch`}
|
||||
placeholder="default branch"
|
||||
disabled={disabled}
|
||||
onChange={(e) => update(i, { branch: e.target.value })}
|
||||
onBlur={onCommit}
|
||||
className={`w-40 ${inputClass}`}
|
||||
/>
|
||||
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
|
||||
/workspace/
|
||||
</span>
|
||||
<input
|
||||
value={r.folder}
|
||||
aria-label={`Repository ${i + 1} folder`}
|
||||
placeholder="folder"
|
||||
disabled={disabled}
|
||||
onChange={(e) => update(i, { folder: e.target.value })}
|
||||
onBlur={onCommit}
|
||||
className={monoInputClass}
|
||||
/>
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
disabled={disabled}
|
||||
aria-label={`Remove repository ${i + 1}`}
|
||||
onClick={() => {
|
||||
onRowsChange(rows.filter((_, j) => j !== i));
|
||||
// A removal is a finished edit. The commit is applied after
|
||||
// the rows update renders, so it sees the shorter list.
|
||||
onCommit?.();
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<Button disabled={disabled} onClick={() => onRowsChange([...rows, emptyRepo()])}>
|
||||
+ Add repository
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function sameRepos(a: RepoSource[], b: RepoSource[]): boolean {
|
||||
return (
|
||||
a.length === b.length &&
|
||||
a.every((r, i) => r.url === b[i].url && r.branch === b[i].branch && r.folder === b[i].folder)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Config tab's save-on-blur repository list. Saves when every row that
|
||||
* has anything in it has a URL; the backend's validation message (bad URL,
|
||||
* folder used twice…) comes back through the save's toast.
|
||||
*/
|
||||
export default function RepoListEditor({
|
||||
repos,
|
||||
onSave,
|
||||
disabled = false,
|
||||
}: {
|
||||
repos: RepoSource[];
|
||||
onSave: (repos: RepoSource[]) => Promise<boolean>;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [rows, setRows] = useState<RepoSource[]>(repos);
|
||||
useEffect(() => setRows(repos), [repos]);
|
||||
|
||||
// A commit bumps this; the effect then runs against the rendered rows.
|
||||
const [pending, setPending] = useState(0);
|
||||
useEffect(() => {
|
||||
if (pending === 0) return;
|
||||
const cleaned = cleanRepos(rows);
|
||||
if (cleaned.some((r) => !r.url)) return;
|
||||
if (sameRepos(cleaned, repos)) return;
|
||||
void onSave(cleaned);
|
||||
// Only a commit triggers this; `rows` changing alone does not save.
|
||||
}, [pending]);
|
||||
|
||||
return (
|
||||
<RepoRows
|
||||
rows={rows}
|
||||
onRowsChange={setRows}
|
||||
onCommit={() => setPending((n) => n + 1)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import StopGuardModal from "./StopGuardModal";
|
||||
import type { UnsavedWork } from "../../lib/types";
|
||||
|
||||
const dirty: UnsavedWork = {
|
||||
checked: true,
|
||||
repos: [
|
||||
{ folder: "api", branch: "main", dirty: true, unpushed: 2 },
|
||||
{ folder: "clean", branch: "main", dirty: false, unpushed: 0 },
|
||||
],
|
||||
error: null,
|
||||
};
|
||||
|
||||
describe("StopGuardModal", () => {
|
||||
it("lists the repositories at risk and defaults to pushing", async () => {
|
||||
const onChoose = vi.fn();
|
||||
render(<StopGuardModal projectName="api" work={dirty} onChoose={onChoose} />);
|
||||
expect(screen.getByText("/workspace/api")).toBeInTheDocument();
|
||||
expect(screen.getByText(/uncommitted changes, 2 unpushed commits/)).toBeInTheDocument();
|
||||
expect(screen.queryByText("/workspace/clean")).toBeNull();
|
||||
const push = screen.getByRole("button", { name: "Push to WIP branch and stop" });
|
||||
await waitFor(() => expect(push).toHaveFocus());
|
||||
fireEvent.click(push);
|
||||
expect(onChoose).toHaveBeenCalledWith("push");
|
||||
});
|
||||
|
||||
it("offers Stop anyway and Cancel", () => {
|
||||
const onChoose = vi.fn();
|
||||
render(<StopGuardModal projectName="api" work={dirty} onChoose={onChoose} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Stop anyway" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(onChoose.mock.calls).toEqual([["discard"], [null]]);
|
||||
});
|
||||
|
||||
it("hides Push and says why when the workspace could not be checked", async () => {
|
||||
const onChoose = vi.fn();
|
||||
render(
|
||||
<StopGuardModal
|
||||
projectName="api"
|
||||
work={{ checked: false, repos: [], error: "Triple-C is not connected to the workspace" }}
|
||||
onChoose={onChoose}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: /Push/ })).toBeNull();
|
||||
expect(screen.getByText("Triple-C is not connected to the workspace")).toBeInTheDocument();
|
||||
expect(screen.getByText(/could not check/)).toBeInTheDocument();
|
||||
const stop = screen.getByRole("button", { name: "Stop anyway" });
|
||||
await waitFor(() => expect(stop).toHaveFocus());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useRef } from "react";
|
||||
import type { UnsavedWork, WipChoice } from "../../lib/types";
|
||||
import Modal from "../ui/Modal";
|
||||
import Button from "../ui/Button";
|
||||
|
||||
interface Props {
|
||||
projectName: string;
|
||||
work: UnsavedWork;
|
||||
/** `null` = Cancel. */
|
||||
onChoose: (choice: WipChoice | null) => void;
|
||||
}
|
||||
|
||||
function describeRepo(dirty: boolean, unpushed: number): string {
|
||||
const parts: string[] = [];
|
||||
if (dirty) parts.push("uncommitted changes");
|
||||
if (unpushed > 0) parts.push(`${unpushed} unpushed commit${unpushed === 1 ? "" : "s"}`);
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Asked before an AWS workspace stops when its repositories hold work no
|
||||
* remote has, or when Triple-C could not check. Pushing to a WIP branch is
|
||||
* the default (it has focus); it is not offered when the check could not
|
||||
* run, since the push goes the same way the check did.
|
||||
*/
|
||||
export default function StopGuardModal({ projectName, work, onChoose }: Props) {
|
||||
const pushRef = useRef<HTMLButtonElement>(null);
|
||||
const stopRef = useRef<HTMLButtonElement>(null);
|
||||
const atRisk = work.repos.filter((r) => r.dirty || r.unpushed > 0);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="Unsaved work"
|
||||
onClose={() => onChoose(null)}
|
||||
widthClassName="w-[30rem]"
|
||||
initialFocusRef={work.checked ? pushRef : stopRef}
|
||||
footer={
|
||||
<>
|
||||
<Button size="md" variant="ghost" onClick={() => onChoose(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
ref={stopRef}
|
||||
size="md"
|
||||
variant={work.checked ? "danger" : "primary"}
|
||||
onClick={() => onChoose("discard")}
|
||||
>
|
||||
Stop anyway
|
||||
</Button>
|
||||
{work.checked && (
|
||||
<Button ref={pushRef} size="md" variant="primary" onClick={() => onChoose("push")}>
|
||||
Push to WIP branch and stop
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{work.checked ? (
|
||||
<>
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Stopping <strong className="text-[var(--text-primary)]">{projectName}</strong> ends
|
||||
its workspace. These repositories have work that no remote has yet:
|
||||
</p>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{atRisk.map((r) => (
|
||||
<li key={r.folder} className="text-[13px] text-[var(--text-primary)]">
|
||||
<span className="font-mono">/workspace/{r.folder}</span>{" "}
|
||||
<span className="text-[var(--text-secondary)]">
|
||||
({r.branch}): {describeRepo(r.dirty, r.unpushed)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-3 text-[13px] text-[var(--text-secondary)]">
|
||||
Push to WIP branch saves a snapshot of each repository to a{" "}
|
||||
<span className="font-mono">triple-c/wip/…</span> branch on its remote, without
|
||||
touching your branches. If the push fails, the workspace keeps running.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Triple-C could not check{" "}
|
||||
<strong className="text-[var(--text-primary)]">{projectName}</strong> for unsaved
|
||||
work, so it can’t push it to a WIP branch first.
|
||||
</p>
|
||||
{work.error && (
|
||||
<p
|
||||
role="note"
|
||||
className="mt-2 px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
|
||||
>
|
||||
{work.error}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
|
||||
Uncommitted or unpushed work in the workspace may be lost if you stop it now.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import ModelSection from "./config/ModelSection";
|
||||
import AccessSection from "./config/AccessSection";
|
||||
import RuntimeSection from "./config/RuntimeSection";
|
||||
import MarketplaceSection from "./config/MarketplaceSection";
|
||||
import HostSection from "./config/HostSection";
|
||||
import { isAwsProject } from "../../../lib/awsWorkspace";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
@@ -40,6 +42,9 @@ export default function ConfigTab({ project, save, saveState }: Props) {
|
||||
</div>
|
||||
|
||||
<WorkspaceSection project={project} save={save} disabled={disabled} />
|
||||
{isAwsProject(project) && (
|
||||
<HostSection project={project} save={save} disabled={disabled} />
|
||||
)}
|
||||
<ModelSection project={project} save={save} disabled={disabled} />
|
||||
<AccessSection
|
||||
project={project}
|
||||
|
||||
@@ -9,7 +9,10 @@ import { useContainerMigration } from "../../../hooks/useContainerMigration";
|
||||
import { ProjectStatusIndicator } from "../../ui/StatusIndicator";
|
||||
import Button from "../../ui/Button";
|
||||
import OverflowMenu from "../../ui/OverflowMenu";
|
||||
import ConfirmRemoveModal from "../ConfirmRemoveModal";
|
||||
import ConfirmRemoveModal, { ConfirmForgetAwsModal } from "../ConfirmRemoveModal";
|
||||
import StopGuardModal from "../StopGuardModal";
|
||||
import { isAwsProject } from "../../../lib/awsWorkspace";
|
||||
import type { RemoveProjectOptions } from "../../../lib/types";
|
||||
import ConfirmResetModal from "../ConfirmResetModal";
|
||||
import MigrateContainerModal from "../MigrateContainerModal";
|
||||
import OverviewTab from "./OverviewTab";
|
||||
@@ -58,6 +61,7 @@ export default function ProjectHome({ projectId, active }: Props) {
|
||||
useAppState.getState().clearPendingHomeTab();
|
||||
}, [pendingHomeTab, projectId]);
|
||||
const [confirmRemove, setConfirmRemove] = useState(false);
|
||||
const [forgetAws, setForgetAws] = useState<{ reason: string; discardData: boolean } | null>(null);
|
||||
const [confirmReset, setConfirmReset] = useState(false);
|
||||
const [showMigration, setShowMigration] = useState(false);
|
||||
const { runningSince, progress } = useAppState(
|
||||
@@ -99,6 +103,7 @@ export default function ProjectHome({ projectId, active }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
const aws = isAwsProject(project);
|
||||
const isRunning = project.status === "running";
|
||||
const isTransitioning =
|
||||
project.status === "starting" || project.status === "stopping";
|
||||
@@ -120,6 +125,41 @@ export default function ProjectHome({ projectId, active }: Props) {
|
||||
migration.probeSettled &&
|
||||
!!project.container_id;
|
||||
|
||||
/** Remove the project; an AWS project whose connection is gone asks again. */
|
||||
const removeProject = async (opts: RemoveProjectOptions) => {
|
||||
try {
|
||||
const report = await remove(project.id, opts);
|
||||
if (!projectRemovalIsClean(report)) {
|
||||
const verb = leftoverVerb(report);
|
||||
if (report.retry_scheduled) {
|
||||
useAppState.getState().pushToast({
|
||||
kind: "info",
|
||||
message: `“${project.name}” was removed, but Triple-C could not confirm all its Docker resources were removed`,
|
||||
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed. It will check again the next time it starts.`,
|
||||
});
|
||||
} else {
|
||||
// The pending-cleanup record itself failed to save — no
|
||||
// retry will happen, so this must not promise one.
|
||||
useAppState.getState().pushToast({
|
||||
kind: "error",
|
||||
message: `“${project.name}” was removed, but Triple-C could not confirm its Docker resources were removed`,
|
||||
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed, and could not record this for a retry. You may need to remove ${leftoverPronoun(report)} manually (\`docker rm\` / \`docker rmi\` / \`docker volume rm\`).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (aws && !opts.forgetAwsResources && /connection no longer exists/i.test(String(e))) {
|
||||
setForgetAws({ reason: String(e), discardData: !!opts.discardData });
|
||||
return;
|
||||
}
|
||||
useAppState.getState().pushToast({
|
||||
kind: "error",
|
||||
message: `Could not remove “${project.name}”`,
|
||||
detail: String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`flex flex-col h-full min-h-0 ${active ? "" : "hidden"}`}>
|
||||
{/* Header */}
|
||||
@@ -188,12 +228,13 @@ export default function ProjectHome({ projectId, active }: Props) {
|
||||
{
|
||||
label: "Update container base…",
|
||||
onSelect: () => setShowMigration(true),
|
||||
disabled: !canMigrate,
|
||||
// Docker-only: the backend refuses both for an AWS project.
|
||||
disabled: aws || !canMigrate,
|
||||
},
|
||||
{
|
||||
label: "Reset container…",
|
||||
onSelect: () => setConfirmReset(true),
|
||||
disabled: !isStopped || actions.busy,
|
||||
disabled: aws || !isStopped || actions.busy,
|
||||
danger: true,
|
||||
},
|
||||
{
|
||||
@@ -280,39 +321,33 @@ export default function ProjectHome({ projectId, active }: Props) {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{actions.stopGuard && (
|
||||
<StopGuardModal
|
||||
projectName={project.name}
|
||||
work={actions.stopGuard}
|
||||
onChoose={actions.resolveStopGuard}
|
||||
/>
|
||||
)}
|
||||
{forgetAws && (
|
||||
<ConfirmForgetAwsModal
|
||||
projectName={project.name}
|
||||
reason={forgetAws.reason}
|
||||
onCancel={() => setForgetAws(null)}
|
||||
onConfirm={() => {
|
||||
const { discardData } = forgetAws;
|
||||
setForgetAws(null);
|
||||
void removeProject({ discardData, forgetAwsResources: true });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{confirmRemove && (
|
||||
<ConfirmRemoveModal
|
||||
projectName={project.name}
|
||||
aws={aws}
|
||||
onCancel={() => setConfirmRemove(false)}
|
||||
onConfirm={async () => {
|
||||
onConfirm={({ discardData }) => {
|
||||
setConfirmRemove(false);
|
||||
try {
|
||||
const report = await remove(project.id);
|
||||
if (!projectRemovalIsClean(report)) {
|
||||
const verb = leftoverVerb(report);
|
||||
if (report.retry_scheduled) {
|
||||
useAppState.getState().pushToast({
|
||||
kind: "info",
|
||||
message: `“${project.name}” was removed, but Triple-C could not confirm all its Docker resources were removed`,
|
||||
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed. It will check again the next time it starts.`,
|
||||
});
|
||||
} else {
|
||||
// The pending-cleanup record itself failed to save — no
|
||||
// retry will happen, so this must not promise one.
|
||||
useAppState.getState().pushToast({
|
||||
kind: "error",
|
||||
message: `“${project.name}” was removed, but Triple-C could not confirm its Docker resources were removed`,
|
||||
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed, and could not record this for a retry. You may need to remove ${leftoverPronoun(report)} manually (\`docker rm\` / \`docker rmi\` / \`docker volume rm\`).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
useAppState.getState().pushToast({
|
||||
kind: "error",
|
||||
message: `Could not remove “${project.name}”`,
|
||||
detail: String(e),
|
||||
});
|
||||
}
|
||||
void removeProject({ discardData });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -7,6 +7,7 @@ import Field, { ConfigGroup, inputClass } from "../../../ui/Field";
|
||||
import CaCertPathInput from "../../../settings/CaCertPathInput";
|
||||
import EnvVarsEditor from "../../EnvVarsEditor";
|
||||
import PortMappingsEditor from "../../PortMappingsEditor";
|
||||
import { NOT_ON_AWS, isAwsProject } from "../../../../lib/awsWorkspace";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
@@ -161,16 +162,22 @@ export default function AccessSection({
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
|
||||
Port mappings
|
||||
</span>
|
||||
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
|
||||
Expose container ports on the host so you can reach dev servers running inside
|
||||
the sandbox.
|
||||
</p>
|
||||
<PortMappingsEditor
|
||||
portMappings={project.port_mappings ?? []}
|
||||
disabled={disabled}
|
||||
disabledReason={disabledReason}
|
||||
onSave={(mappings) => save({ port_mappings: mappings })}
|
||||
/>
|
||||
{isAwsProject(project) ? (
|
||||
<p className="mt-0.5 text-xs text-[var(--text-disabled)] leading-snug">{NOT_ON_AWS}</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
|
||||
Expose container ports on the host so you can reach dev servers running inside
|
||||
the sandbox.
|
||||
</p>
|
||||
<PortMappingsEditor
|
||||
portMappings={project.port_mappings ?? []}
|
||||
disabled={disabled}
|
||||
disabledReason={disabledReason}
|
||||
onSave={(mappings) => save({ port_mappings: mappings })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ConfigGroup>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
|
||||
import RuntimeSection from "./RuntimeSection";
|
||||
import AccessSection from "./AccessSection";
|
||||
import WorkspaceSection from "./WorkspaceSection";
|
||||
import ModelSection from "./ModelSection";
|
||||
import HostSection from "./HostSection";
|
||||
import { awsProject, localProject } from "../../../../test/awsFixtures";
|
||||
import type { AuthBridgeStatus, Project } from "../../../../lib/types";
|
||||
|
||||
const OFF_BRIDGE: AuthBridgeStatus = { enabled: false, active_ports: [], conflicts: [] };
|
||||
const removeAwsResources = vi.fn();
|
||||
|
||||
vi.mock("../../../../lib/tauri-commands", () => ({
|
||||
getAuthBridgeStatus: vi.fn(async () => OFF_BRIDGE),
|
||||
setAuthBridgeEnabled: vi.fn(),
|
||||
inspectCaCertPath: vi.fn(async () => null),
|
||||
removeAwsResources: (id: string, discard: boolean) => removeAwsResources(id, discard),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => {}) }));
|
||||
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: vi.fn(async () => null) }));
|
||||
|
||||
const save = vi.fn().mockResolvedValue(true);
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
function toggle(name: string) {
|
||||
return screen.getByRole("switch", { name });
|
||||
}
|
||||
|
||||
describe("AWS project config", () => {
|
||||
it("locks Docker access, VPN and the sandbox on AWS, saying why", () => {
|
||||
render(<RuntimeSection project={awsProject()} save={save} disabled={false} />);
|
||||
for (const name of ["Allow container spawning", "VPN support", "Sandbox mode"]) {
|
||||
expect(toggle(name)).toBeDisabled();
|
||||
expect(toggle(name)).toHaveAttribute("aria-checked", "false");
|
||||
}
|
||||
expect(screen.getAllByText("Not available on AWS (Fargate)")).toHaveLength(2);
|
||||
expect(screen.getByText(/Off on AWS for now/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("leaves those options alone for a local project", () => {
|
||||
render(<RuntimeSection project={localProject()} save={save} disabled={false} />);
|
||||
expect(toggle("VPN support")).not.toBeDisabled();
|
||||
expect(toggle("Sandbox mode")).toHaveAttribute("aria-checked", "true");
|
||||
expect(screen.queryByText("Not available on AWS (Fargate)")).toBeNull();
|
||||
});
|
||||
|
||||
it("replaces port mappings and folders on AWS", () => {
|
||||
render(<AccessSection project={awsProject()} save={save} disabled={false} />);
|
||||
expect(screen.getByText("Not available on AWS (Fargate)")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Expose container ports/)).toBeNull();
|
||||
|
||||
render(<WorkspaceSection project={awsProject()} save={save} disabled={false} />);
|
||||
expect(screen.queryByText("Folders")).toBeNull();
|
||||
expect(screen.getByText(/mounts no folders/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables the gateway backend and warns about local model URLs on AWS", () => {
|
||||
render(<ModelSection project={awsProject({ backend: "ollama" })} save={save} disabled={false} />);
|
||||
const gateway = screen.getByRole("option", { name: /OpenAI Compatible/ }) as HTMLOptionElement;
|
||||
expect(gateway.disabled).toBe(true);
|
||||
expect(gateway.textContent).toMatch(/Not available on AWS/);
|
||||
expect(screen.getByText(/must be reachable from the AWS task/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("HostSection", () => {
|
||||
const renderHost = (p: Project = awsProject(), disabled = false) =>
|
||||
render(<HostSection project={p} save={save} disabled={disabled} />);
|
||||
|
||||
it("saves a CPU change with a memory size valid for it", async () => {
|
||||
renderHost(); // 1024 CPU / 4096 MiB
|
||||
fireEvent.change(screen.getByLabelText("CPU"), { target: { value: "256" } });
|
||||
await waitFor(() => expect(save).toHaveBeenCalled());
|
||||
const aws = save.mock.calls[0][0].aws;
|
||||
expect([aws.cpu, aws.memory_mib]).toEqual([256, 2048]);
|
||||
});
|
||||
|
||||
it("saves a valid memory size and refuses an invalid one", async () => {
|
||||
renderHost();
|
||||
const mem = screen.getByLabelText("Memory (MiB)");
|
||||
fireEvent.change(mem, { target: { value: "5000" } });
|
||||
fireEvent.blur(mem);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(/5000 MiB of memory is not valid with 1024/);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(mem, { target: { value: "8192" } });
|
||||
fireEvent.blur(mem);
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save.mock.calls[0][0].aws).toMatchObject({ cpu: 1024, memory_mib: 8192 });
|
||||
expect(screen.queryByRole("alert")).toBeNull();
|
||||
});
|
||||
|
||||
it("warns that Ephemeral storage loses the login and history", () => {
|
||||
const p = awsProject();
|
||||
p.aws = { ...p.aws!, storage: "ephemeral" };
|
||||
renderHost(p);
|
||||
expect(screen.getByText(/Claude login and history are lost when the workspace stops/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/EFS .* coming later/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saves repository edits on blur", async () => {
|
||||
renderHost();
|
||||
fireEvent.click(screen.getByRole("button", { name: "+ Add repository" }));
|
||||
const url = screen.getByLabelText("Repository 2 URL");
|
||||
fireEvent.change(url, { target: { value: "git@github.com:org/web.git" } });
|
||||
fireEvent.blur(url);
|
||||
await waitFor(() => expect(save).toHaveBeenCalled());
|
||||
expect(save.mock.calls[0][0].aws.repos).toEqual([
|
||||
{ url: "https://example.com/org/api.git", branch: null, folder: "api" },
|
||||
{ url: "git@github.com:org/web.git", branch: null, folder: "web" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes AWS resources after a confirm, and only then allows moving to this machine", async () => {
|
||||
const p = awsProject();
|
||||
p.aws = { ...p.aws!, task_definition_arn: "arn:td:1" };
|
||||
removeAwsResources.mockResolvedValue({ ...p, aws: { ...p.aws, task_definition_arn: null } });
|
||||
renderHost(p);
|
||||
const move = screen.getByRole("button", { name: "Run on this machine instead" });
|
||||
expect(move).toHaveAttribute("aria-disabled", "true");
|
||||
fireEvent.click(move);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove AWS resources…" }));
|
||||
const dialog = screen.getByRole("dialog");
|
||||
fireEvent.click(within(dialog).getByRole("checkbox"));
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));
|
||||
await waitFor(() => expect(removeAwsResources).toHaveBeenCalledWith(p.id, true));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,419 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { AwsWorkspaceConfig, HostConnection, Project, RepoSource } from "../../../../lib/types";
|
||||
import * as commands from "../../../../lib/tauri-commands";
|
||||
import { useAppState } from "../../../../store/appState";
|
||||
import {
|
||||
EPHEMERAL_WARNING,
|
||||
FARGATE_CPUS,
|
||||
defaultAwsWorkspace,
|
||||
formatCpu,
|
||||
formatMemory,
|
||||
memoryError,
|
||||
memoryOptions,
|
||||
nearestMemory,
|
||||
} from "../../../../lib/awsWorkspace";
|
||||
import Button from "../../../ui/Button";
|
||||
import Modal from "../../../ui/Modal";
|
||||
import Toggle from "../../../ui/Toggle";
|
||||
import SegmentedControl from "../../../ui/SegmentedControl";
|
||||
import Field, { ConfigGroup, SwitchRow, inputClass, selectClass } from "../../../ui/Field";
|
||||
import RepoListEditor from "../../RepoListEditor";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
save: (patch: Partial<Project>) => Promise<boolean>;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_IDLE_MINUTES = 60;
|
||||
|
||||
/**
|
||||
* Where an AWS project runs and what its Fargate task looks like. Only shown
|
||||
* for AWS projects; a local project's host is chosen when it is added.
|
||||
*/
|
||||
/** Stable, so the store selector does not return a new array each render. */
|
||||
const NO_HOSTS: HostConnection[] = [];
|
||||
|
||||
export default function HostSection({ project, save, disabled }: Props) {
|
||||
const aws: AwsWorkspaceConfig = project.aws ?? defaultAwsWorkspace();
|
||||
const hosts = useAppState((s) => s.appSettings?.hosts ?? NO_HOSTS);
|
||||
const connection = hosts.find((h) => h.id === project.host_id);
|
||||
|
||||
const [memory, setMemory] = useState(String(aws.memory_mib));
|
||||
const [memoryProblem, setMemoryProblem] = useState<string | null>(null);
|
||||
const [ephemeral, setEphemeral] = useState(String(aws.ephemeral_gib));
|
||||
const [ephemeralProblem, setEphemeralProblem] = useState<string | null>(null);
|
||||
const [idle, setIdle] = useState(String(aws.idle_stop_minutes ?? DEFAULT_IDLE_MINUTES));
|
||||
const [idleProblem, setIdleProblem] = useState<string | null>(null);
|
||||
const [confirmRemoveResources, setConfirmRemoveResources] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMemory(String(aws.memory_mib));
|
||||
setEphemeral(String(aws.ephemeral_gib));
|
||||
setIdle(String(aws.idle_stop_minutes ?? DEFAULT_IDLE_MINUTES));
|
||||
}, [aws.memory_mib, aws.ephemeral_gib, aws.idle_stop_minutes]);
|
||||
|
||||
const saveAws = (patch: Partial<AwsWorkspaceConfig>) => save({ aws: { ...aws, ...patch } });
|
||||
|
||||
const hasResources = !!(aws.task_arn || aws.access_point_id || aws.task_definition_arn);
|
||||
|
||||
const commitMemory = () => {
|
||||
const value = Number(memory);
|
||||
const problem = memoryError(aws.cpu, value);
|
||||
setMemoryProblem(problem);
|
||||
if (problem || value === aws.memory_mib) return;
|
||||
void saveAws({ memory_mib: value });
|
||||
};
|
||||
|
||||
const commitEphemeral = () => {
|
||||
const value = Number(ephemeral);
|
||||
const ok = Number.isInteger(value) && value >= 21 && value <= 200;
|
||||
setEphemeralProblem(ok ? null : "Ephemeral storage must be 21 to 200 GiB");
|
||||
if (ok && value !== aws.ephemeral_gib) void saveAws({ ephemeral_gib: value });
|
||||
};
|
||||
|
||||
const commitIdle = () => {
|
||||
const value = Number(idle);
|
||||
const ok = Number.isInteger(value) && value >= 5 && value <= 1440;
|
||||
setIdleProblem(ok ? null : "Idle stop must be 5 to 1440 minutes");
|
||||
if (ok && value !== aws.idle_stop_minutes) void saveAws({ idle_stop_minutes: value });
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfigGroup
|
||||
title="Host"
|
||||
description="This project runs as an AWS Fargate task. Changes apply on its next start."
|
||||
>
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[13px]">
|
||||
<dt className="text-[var(--text-secondary)]">Connection</dt>
|
||||
<dd className="text-[var(--text-primary)]">
|
||||
{connection?.name ?? (
|
||||
<span className="text-[var(--warning)]">
|
||||
Removed — add it again in Settings → Hosts to start this project
|
||||
</span>
|
||||
)}
|
||||
</dd>
|
||||
<dt className="text-[var(--text-secondary)]">Region</dt>
|
||||
<dd className="font-mono text-[var(--text-primary)]">{project.aws_placement?.region}</dd>
|
||||
<dt className="text-[var(--text-secondary)]">Environment</dt>
|
||||
<dd className="font-mono text-[var(--text-primary)]">
|
||||
{project.aws_placement?.environment}
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Field label="CPU">
|
||||
{(id) => (
|
||||
<select
|
||||
id={id}
|
||||
value={aws.cpu}
|
||||
disabled={disabled}
|
||||
className={selectClass}
|
||||
onChange={(e) => {
|
||||
const cpu = Number(e.target.value);
|
||||
const memory_mib = memoryError(cpu, aws.memory_mib)
|
||||
? nearestMemory(cpu, aws.memory_mib)
|
||||
: aws.memory_mib;
|
||||
setMemoryProblem(null);
|
||||
void saveAws({ cpu, memory_mib });
|
||||
}}
|
||||
>
|
||||
{FARGATE_CPUS.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{formatCpu(c)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</Field>
|
||||
<Field
|
||||
label="Memory (MiB)"
|
||||
hint={(() => {
|
||||
const opts = memoryOptions(aws.cpu);
|
||||
return `${formatMemory(opts[0])} to ${formatMemory(opts[opts.length - 1])} with ${formatCpu(aws.cpu)}.`;
|
||||
})()}
|
||||
>
|
||||
{(id) => (
|
||||
<>
|
||||
<input
|
||||
id={id}
|
||||
inputMode="numeric"
|
||||
value={memory}
|
||||
disabled={disabled}
|
||||
list={`${id}-options`}
|
||||
aria-invalid={memoryProblem ? true : undefined}
|
||||
onChange={(e) => setMemory(e.target.value)}
|
||||
onBlur={commitMemory}
|
||||
onKeyDown={(e) => e.key === "Enter" && commitMemory()}
|
||||
className={`w-32 ${inputClass}`}
|
||||
/>
|
||||
<datalist id={`${id}-options`}>
|
||||
{memoryOptions(aws.cpu).map((m) => (
|
||||
<option key={m} value={m} />
|
||||
))}
|
||||
</datalist>
|
||||
</>
|
||||
)}
|
||||
</Field>
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
|
||||
Architecture
|
||||
</span>
|
||||
<SegmentedControl
|
||||
label="Architecture"
|
||||
value={aws.arch}
|
||||
disabled={disabled}
|
||||
onChange={(arch) => void saveAws({ arch })}
|
||||
segments={[
|
||||
{ value: "x86_64", label: "x86_64" },
|
||||
{ value: "arm64", label: "ARM64 (Graviton)" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{memoryProblem && (
|
||||
<p role="alert" className="text-xs text-[var(--error)]">
|
||||
{memoryProblem}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
|
||||
Storage
|
||||
</span>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<SegmentedControl
|
||||
label="Storage"
|
||||
value={aws.storage}
|
||||
disabled={disabled}
|
||||
onChange={(storage) => void saveAws({ storage })}
|
||||
segments={[
|
||||
{ value: "ephemeral", label: "Ephemeral", caution: true },
|
||||
{ value: "hybrid", label: "Hybrid" },
|
||||
]}
|
||||
/>
|
||||
<span className="text-xs text-[var(--text-disabled)]">
|
||||
EFS (everything persists) — coming later
|
||||
</span>
|
||||
</div>
|
||||
{aws.storage === "ephemeral" ? (
|
||||
<p
|
||||
role="note"
|
||||
className="mt-2 px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
|
||||
>
|
||||
{EPHEMERAL_WARNING} Push your work to a remote before stopping.
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-1 text-xs text-[var(--text-secondary)]">
|
||||
The Claude login, history and SSH keys are kept on EFS between starts; everything
|
||||
else, repositories included, starts fresh.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Field
|
||||
label="Ephemeral storage (GiB)"
|
||||
hint="The task's local disk: 21 to 200 GiB. Repositories and builds live here."
|
||||
>
|
||||
{(id) => (
|
||||
<input
|
||||
id={id}
|
||||
inputMode="numeric"
|
||||
value={ephemeral}
|
||||
disabled={disabled}
|
||||
aria-invalid={ephemeralProblem ? true : undefined}
|
||||
onChange={(e) => setEphemeral(e.target.value)}
|
||||
onBlur={commitEphemeral}
|
||||
className={`w-24 ${inputClass}`}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
{ephemeralProblem && (
|
||||
<p role="alert" className="text-xs text-[var(--error)]">
|
||||
{ephemeralProblem}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<SwitchRow
|
||||
label="Spot"
|
||||
hint="Runs on spare capacity at up to 70% off. AWS may reclaim it with two minutes' notice; the work-in-progress push below still runs."
|
||||
control={
|
||||
<Toggle
|
||||
label="Spot"
|
||||
checked={aws.spot}
|
||||
disabled={disabled}
|
||||
onChange={(spot) => void saveAws({ spot })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SwitchRow
|
||||
label="Stop when idle"
|
||||
hint="Stops the workspace after this many minutes with no terminal activity, no running Claude and no scheduled job."
|
||||
control={
|
||||
<Toggle
|
||||
label="Stop when idle"
|
||||
checked={aws.idle_stop_minutes !== null}
|
||||
disabled={disabled}
|
||||
onChange={(on) =>
|
||||
void saveAws({ idle_stop_minutes: on ? Number(idle) || DEFAULT_IDLE_MINUTES : null })
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{aws.idle_stop_minutes !== null && (
|
||||
<Field label="Idle minutes" hint="5 to 1440.">
|
||||
{(id) => (
|
||||
<input
|
||||
id={id}
|
||||
inputMode="numeric"
|
||||
value={idle}
|
||||
disabled={disabled}
|
||||
aria-invalid={idleProblem ? true : undefined}
|
||||
onChange={(e) => setIdle(e.target.value)}
|
||||
onBlur={commitIdle}
|
||||
className={`w-24 ${inputClass}`}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
{idleProblem && (
|
||||
<p role="alert" className="text-xs text-[var(--error)]">
|
||||
{idleProblem}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<SwitchRow
|
||||
label="Push work in progress when the workspace stops"
|
||||
hint="On any stop (idle, Spot, or from AWS), each repository's uncommitted and unpushed work is pushed to a triple-c/wip/… branch on its remote."
|
||||
control={
|
||||
<Toggle
|
||||
label="Push work in progress when the workspace stops"
|
||||
checked={aws.wip_push_on_stop}
|
||||
disabled={disabled}
|
||||
onChange={(wip_push_on_stop) => void saveAws({ wip_push_on_stop })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="pt-2 border-t border-[var(--border-color)]">
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
|
||||
Repositories
|
||||
</span>
|
||||
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
|
||||
Cloned into <span className="font-mono">/workspace/<folder></span> when the
|
||||
workspace starts, with the project’s SSH key or Git token.
|
||||
</p>
|
||||
<RepoListEditor
|
||||
repos={aws.repos}
|
||||
disabled={disabled}
|
||||
onSave={(repos: RepoSource[]) => saveAws({ repos })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-[var(--border-color)] flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
unavailable={disabled || !hasResources}
|
||||
unavailableReason={
|
||||
disabled
|
||||
? "Stop the project first."
|
||||
: "This project has no AWS resources to remove."
|
||||
}
|
||||
onClick={() => setConfirmRemoveResources(true)}
|
||||
>
|
||||
Remove AWS resources…
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
unavailable={disabled || hasResources}
|
||||
unavailableReason={
|
||||
disabled
|
||||
? "Stop the project first."
|
||||
: "Remove the workspace's AWS resources first, so nothing is left running or billed."
|
||||
}
|
||||
onClick={() => void save({ host_id: null, aws_placement: null, aws: null })}
|
||||
>
|
||||
Run on this machine instead
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{confirmRemoveResources && (
|
||||
<RemoveAwsResourcesModal
|
||||
project={project}
|
||||
onClose={() => setConfirmRemoveResources(false)}
|
||||
/>
|
||||
)}
|
||||
</ConfigGroup>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoveAwsResourcesModal({ project, onClose }: { project: Project; onClose: () => void }) {
|
||||
const [discardData, setDiscardData] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const confirm = async () => {
|
||||
if (running) return;
|
||||
setRunning(true);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await commands.removeAwsResources(project.id, discardData);
|
||||
useAppState.getState().updateProjectInList(updated);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="Remove AWS resources"
|
||||
onClose={onClose}
|
||||
widthClassName="w-[28rem]"
|
||||
footer={
|
||||
<>
|
||||
<Button size="md" variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
unavailable={running}
|
||||
unavailableReason="Removing…"
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
{running ? "Removing…" : "Remove"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-[13px] text-[var(--text-secondary)]">
|
||||
Removes <strong className="text-[var(--text-primary)]">{project.name}</strong>’s
|
||||
task definitions and secret from AWS (the secret after a 7-day recovery window) and
|
||||
keeps the project, so it can run somewhere else. Its next start on AWS sets them up
|
||||
again.
|
||||
</p>
|
||||
<label className="mt-3 flex items-start gap-2 text-[13px] text-[var(--text-primary)]">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={discardData}
|
||||
onChange={(e) => setDiscardData(e.target.checked)}
|
||||
/>
|
||||
<span>Also delete the workspace’s saved files (EFS)</span>
|
||||
</label>
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="mt-3 px-2 py-1.5 text-xs text-[var(--error)] bg-[var(--error-muted)] border border-[var(--error)]/30 rounded-[var(--radius-control)]"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,11 @@ import Field, {
|
||||
selectClass,
|
||||
} from "../../../ui/Field";
|
||||
import Toggle from "../../../ui/Toggle";
|
||||
import { NOT_ON_AWS, isAwsProject } from "../../../../lib/awsWorkspace";
|
||||
|
||||
/** P6: an AWS workspace can reach a local model only over the network. */
|
||||
const LOCAL_MODEL_ON_AWS =
|
||||
"This project runs on AWS: the URL must be reachable from the AWS task, so host.docker.internal and this machine's LAN addresses will not work.";
|
||||
|
||||
/** Bedrock fields held in the OS keychain, never serialized back to us. */
|
||||
const BEDROCK_SECRET_KEYS = [
|
||||
@@ -181,6 +186,8 @@ export default function ModelSection({ project, save, disabled }: Props) {
|
||||
// that predates it, should still pick the shared token up.
|
||||
const useSharedToken = project.use_shared_auth_token !== false;
|
||||
|
||||
const aws = isAwsProject(project);
|
||||
|
||||
const handleBackendChange = (mode: Backend) => {
|
||||
const patch: Partial<Project> = { backend: mode };
|
||||
if (mode === "bedrock" && !project.bedrock_config)
|
||||
@@ -212,10 +219,25 @@ export default function ModelSection({ project, save, disabled }: Props) {
|
||||
<option value="bedrock">Bedrock</option>
|
||||
<option value="ollama">Ollama</option>
|
||||
<option value="llama_cpp">llama.cpp</option>
|
||||
<option value="open_ai_compatible">OpenAI Compatible</option>
|
||||
<option value="open_ai_compatible" disabled={aws}>
|
||||
{aws ? `OpenAI Compatible (gateway) — ${NOT_ON_AWS}` : "OpenAI Compatible"}
|
||||
</option>
|
||||
</select>
|
||||
)}
|
||||
</Field>
|
||||
{aws && project.backend === "open_ai_compatible" && (
|
||||
<p role="note" className="text-xs text-[var(--warning)]">
|
||||
OpenAI Compatible (gateway): {NOT_ON_AWS}. Choose another backend.
|
||||
</p>
|
||||
)}
|
||||
{aws && (project.backend === "ollama" || project.backend === "llama_cpp") && (
|
||||
<p
|
||||
role="note"
|
||||
className="px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
|
||||
>
|
||||
{LOCAL_MODEL_ON_AWS}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Only Anthropic reads CLAUDE_CODE_OAUTH_TOKEN; the other backends
|
||||
authenticate through their own credentials entirely. */}
|
||||
|
||||
@@ -5,6 +5,7 @@ import PermissionModeControl, { permissionModePatch } from "../../PermissionMode
|
||||
import ClaudeInstructionsEditor from "../../ClaudeInstructionsEditor";
|
||||
import ClaudeCodeSettingsEditor from "../../ClaudeCodeSettingsEditor";
|
||||
import AuthBridgeRow from "./AuthBridgeRow";
|
||||
import { NOT_ON_AWS, SANDBOX_OFF_ON_AWS, isAwsProject } from "../../../../lib/awsWorkspace";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
@@ -19,6 +20,7 @@ export default function RuntimeSection({
|
||||
disabled,
|
||||
disabledReason,
|
||||
}: Props) {
|
||||
const aws = isAwsProject(project);
|
||||
return (
|
||||
<>
|
||||
<ConfigGroup
|
||||
@@ -34,12 +36,16 @@ export default function RuntimeSection({
|
||||
|
||||
<SwitchRow
|
||||
label="Sandbox mode"
|
||||
hint="Claude Code's bash sandbox (bubblewrap filesystem and network isolation). Triple-C is the source of truth: toggling this overrides any manual /sandbox configuration in the container's settings.json on next start."
|
||||
hint={
|
||||
aws
|
||||
? `${SANDBOX_OFF_ON_AWS}: Claude Code's bash sandbox has not been verified on Fargate yet, so an AWS workspace runs with it off whatever this says.`
|
||||
: "Claude Code's bash sandbox (bubblewrap filesystem and network isolation). Triple-C is the source of truth: toggling this overrides any manual /sandbox configuration in the container's settings.json on next start."
|
||||
}
|
||||
control={
|
||||
<Toggle
|
||||
label="Sandbox mode"
|
||||
checked={project.sandbox_mode_enabled}
|
||||
disabled={disabled}
|
||||
checked={aws ? false : project.sandbox_mode_enabled}
|
||||
disabled={disabled || aws}
|
||||
onChange={(v) => save({ sandbox_mode_enabled: v })}
|
||||
/>
|
||||
}
|
||||
@@ -47,12 +53,16 @@ export default function RuntimeSection({
|
||||
|
||||
<SwitchRow
|
||||
label="Allow container spawning"
|
||||
hint="Mounts the Docker socket so Claude can build and run Docker containers from inside the sandbox."
|
||||
hint={
|
||||
aws
|
||||
? NOT_ON_AWS
|
||||
: "Mounts the Docker socket so Claude can build and run Docker containers from inside the sandbox."
|
||||
}
|
||||
control={
|
||||
<Toggle
|
||||
label="Allow container spawning"
|
||||
checked={project.allow_docker_access}
|
||||
disabled={disabled}
|
||||
checked={aws ? false : project.allow_docker_access}
|
||||
disabled={disabled || aws}
|
||||
onChange={(v) => save({ allow_docker_access: v })}
|
||||
/>
|
||||
}
|
||||
@@ -60,12 +70,12 @@ export default function RuntimeSection({
|
||||
|
||||
<SwitchRow
|
||||
label="VPN support"
|
||||
hint="Grants NET_ADMIN and the /dev/net/tun device so a VPN client (PIA, WireGuard, OpenVPN) can build a tunnel inside the container. Without it a client installs and runs but its connection hangs until it times out. Anything in the container can then reconfigure the container's own network stack; the host's is untouched. Changing this recreates the container on its next start — the home and .claude volumes are preserved."
|
||||
hint={aws ? NOT_ON_AWS : "Grants NET_ADMIN and the /dev/net/tun device so a VPN client (PIA, WireGuard, OpenVPN) can build a tunnel inside the container. Without it a client installs and runs but its connection hangs until it times out. Anything in the container can then reconfigure the container's own network stack; the host's is untouched. Changing this recreates the container on its next start — the home and .claude volumes are preserved."}
|
||||
control={
|
||||
<Toggle
|
||||
label="VPN support"
|
||||
checked={project.vpn_support_enabled}
|
||||
disabled={disabled}
|
||||
checked={aws ? false : project.vpn_support_enabled}
|
||||
disabled={disabled || aws}
|
||||
onChange={(v) => save({ vpn_support_enabled: v })}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { open } from "@tauri-apps/plugin-dialog";
|
||||
import type { Project, ProjectPath } from "../../../../lib/types";
|
||||
import Button from "../../../ui/Button";
|
||||
import Field, { ConfigGroup, inputClass, monoInputClass } from "../../../ui/Field";
|
||||
import { isAwsProject } from "../../../../lib/awsWorkspace";
|
||||
|
||||
interface Props {
|
||||
project: Project;
|
||||
@@ -73,7 +74,11 @@ export default function WorkspaceSection({ project, save, disabled }: Props) {
|
||||
return (
|
||||
<ConfigGroup
|
||||
title="Workspace"
|
||||
description="What this sandbox is called and which host folders it can see."
|
||||
description={
|
||||
isAwsProject(project)
|
||||
? "What this sandbox is called."
|
||||
: "What this sandbox is called and which host folders it can see."
|
||||
}
|
||||
>
|
||||
<Field
|
||||
label="Project name"
|
||||
@@ -101,96 +106,104 @@ export default function WorkspaceSection({ project, save, disabled }: Props) {
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
|
||||
Folders
|
||||
</span>
|
||||
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
|
||||
Each host folder is mounted at <span className="font-mono">/workspace/<name></span>{" "}
|
||||
inside the container.
|
||||
{isAwsProject(project) ? (
|
||||
<p className="text-xs text-[var(--text-secondary)] leading-snug">
|
||||
This project runs on AWS, so it mounts no folders from this machine: its
|
||||
repositories are cloned into <span className="font-mono">/workspace</span>. Edit them
|
||||
under Host below.
|
||||
</p>
|
||||
) : (
|
||||
<div>
|
||||
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
|
||||
Folders
|
||||
</span>
|
||||
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
|
||||
Each host folder is mounted at <span className="font-mono">/workspace/<name></span>{" "}
|
||||
inside the container.
|
||||
</p>
|
||||
|
||||
<div className="space-y-3">
|
||||
{paths.map((pp, i) => (
|
||||
<div key={i} className="flex flex-col gap-1.5 sm:flex-row sm:items-center">
|
||||
<input
|
||||
value={pp.host_path}
|
||||
aria-label={`Folder ${i + 1} host path`}
|
||||
onChange={(e) => {
|
||||
const updated = [...paths];
|
||||
updated[i] = { ...updated[i], host_path: e.target.value };
|
||||
setPaths(updated);
|
||||
}}
|
||||
onBlur={() => saveIfComplete()}
|
||||
placeholder="/path/to/folder"
|
||||
disabled={disabled}
|
||||
className={`flex-1 min-w-0 ${inputClass}`}
|
||||
/>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="md"
|
||||
disabled={disabled}
|
||||
onClick={async () => {
|
||||
const selected = await open({ directory: true, multiple: false });
|
||||
if (typeof selected === "string") {
|
||||
const updated = [...paths];
|
||||
const basename =
|
||||
selected.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "";
|
||||
updated[i] = {
|
||||
host_path: selected,
|
||||
mount_name: updated[i].mount_name || basename,
|
||||
};
|
||||
setPaths(updated);
|
||||
persist(updated);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
<span className="text-xs text-[var(--text-secondary)] font-mono flex-shrink-0">
|
||||
/workspace/
|
||||
</span>
|
||||
<div className="space-y-3">
|
||||
{paths.map((pp, i) => (
|
||||
<div key={i} className="flex flex-col gap-1.5 sm:flex-row sm:items-center">
|
||||
<input
|
||||
value={pp.mount_name}
|
||||
aria-label={`Folder ${i + 1} mount name`}
|
||||
value={pp.host_path}
|
||||
aria-label={`Folder ${i + 1} host path`}
|
||||
onChange={(e) => {
|
||||
const updated = [...paths];
|
||||
updated[i] = { ...updated[i], mount_name: e.target.value };
|
||||
updated[i] = { ...updated[i], host_path: e.target.value };
|
||||
setPaths(updated);
|
||||
}}
|
||||
onBlur={() => saveIfComplete()}
|
||||
placeholder="name"
|
||||
placeholder="/path/to/folder"
|
||||
disabled={disabled}
|
||||
className={`w-40 ${monoInputClass}`}
|
||||
className={`flex-1 min-w-0 ${inputClass}`}
|
||||
/>
|
||||
{paths.length > 1 && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
disabled={disabled}
|
||||
aria-label={`Remove folder ${i + 1}`}
|
||||
onClick={() => {
|
||||
const updated = paths.filter((_, j) => j !== i);
|
||||
setPaths(updated);
|
||||
persist(updated);
|
||||
onClick={async () => {
|
||||
const selected = await open({ directory: true, multiple: false });
|
||||
if (typeof selected === "string") {
|
||||
const updated = [...paths];
|
||||
const basename =
|
||||
selected.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "";
|
||||
updated[i] = {
|
||||
host_path: selected,
|
||||
mount_name: updated[i].mount_name || basename,
|
||||
};
|
||||
setPaths(updated);
|
||||
persist(updated);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
Browse
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xs text-[var(--text-secondary)] font-mono flex-shrink-0">
|
||||
/workspace/
|
||||
</span>
|
||||
<input
|
||||
value={pp.mount_name}
|
||||
aria-label={`Folder ${i + 1} mount name`}
|
||||
onChange={(e) => {
|
||||
const updated = [...paths];
|
||||
updated[i] = { ...updated[i], mount_name: e.target.value };
|
||||
setPaths(updated);
|
||||
}}
|
||||
onBlur={() => saveIfComplete()}
|
||||
placeholder="name"
|
||||
disabled={disabled}
|
||||
className={`w-40 ${monoInputClass}`}
|
||||
/>
|
||||
{paths.length > 1 && (
|
||||
<Button
|
||||
size="md"
|
||||
variant="danger"
|
||||
disabled={disabled}
|
||||
aria-label={`Remove folder ${i + 1}`}
|
||||
onClick={() => {
|
||||
const updated = paths.filter((_, j) => j !== i);
|
||||
setPaths(updated);
|
||||
persist(updated);
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className="mt-2"
|
||||
disabled={disabled}
|
||||
onClick={() => setPaths([...paths, { host_path: "", mount_name: "" }])}
|
||||
>
|
||||
+ Add folder
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
className="mt-2"
|
||||
disabled={disabled}
|
||||
onClick={() => setPaths([...paths, { host_path: "", mount_name: "" }])}
|
||||
>
|
||||
+ Add folder
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</ConfigGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
|
||||
import { useUnavailable } from "./unavailable";
|
||||
|
||||
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
|
||||
@@ -19,6 +19,8 @@ interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
unavailable?: boolean;
|
||||
/** Why the button cannot be used. Required for `unavailable` to say anything. */
|
||||
unavailableReason?: string;
|
||||
/** React 19 passes `ref` as a prop; it lands on the `<button>` via `rest`. */
|
||||
ref?: Ref<HTMLButtonElement>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { useProjectActions } from "./useProjectActions";
|
||||
import { useAppState } from "../store/appState";
|
||||
import { awsProject, localProject } from "../test/awsFixtures";
|
||||
import type { UnsavedWork } from "../lib/types";
|
||||
|
||||
const start = vi.fn();
|
||||
const stop = vi.fn();
|
||||
const checkUnsavedWork = vi.fn();
|
||||
const awsTaskLog = vi.fn();
|
||||
|
||||
vi.mock("./useProjects", () => ({
|
||||
useProjects: () => ({ start, stop, rebuild: vi.fn() }),
|
||||
}));
|
||||
vi.mock("./useTerminal", () => ({
|
||||
useTerminal: () => ({ open: vi.fn(), sendInput: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@tauri-apps/plugin-dialog", () => ({ save: vi.fn() }));
|
||||
vi.mock("../lib/tauri-commands", () => ({
|
||||
checkUnsavedWork: (id: string) => checkUnsavedWork(id),
|
||||
awsTaskLog: (id: string, n: number) => awsTaskLog(id, n),
|
||||
downloadContainerBackup: vi.fn(),
|
||||
}));
|
||||
|
||||
const clean: UnsavedWork = { checked: true, repos: [], error: null };
|
||||
const dirty: UnsavedWork = {
|
||||
checked: true,
|
||||
repos: [{ folder: "api", branch: "main", dirty: true, unpushed: 0 }],
|
||||
error: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAppState.setState({ toasts: [] } as never);
|
||||
});
|
||||
|
||||
const toasts = () => (useAppState.getState() as unknown as { toasts: { message: string; detail?: string }[] }).toasts;
|
||||
|
||||
describe("useProjectActions stop guard", () => {
|
||||
it("stops an AWS workspace with nothing unsaved straight away", async () => {
|
||||
checkUnsavedWork.mockResolvedValue(clean);
|
||||
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
|
||||
await act(async () => {
|
||||
await result.current.handleStop();
|
||||
});
|
||||
expect(stop).toHaveBeenCalledWith("p1");
|
||||
expect(result.current.stopGuard).toBeNull();
|
||||
});
|
||||
|
||||
it("asks first when there is unsaved work, then stops with the choice", async () => {
|
||||
checkUnsavedWork.mockResolvedValue(dirty);
|
||||
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
|
||||
await act(async () => {
|
||||
await result.current.handleStop();
|
||||
});
|
||||
expect(stop).not.toHaveBeenCalled();
|
||||
expect(result.current.stopGuard).toEqual(dirty);
|
||||
await act(async () => {
|
||||
await result.current.resolveStopGuard("push");
|
||||
});
|
||||
expect(stop).toHaveBeenCalledWith("p1", "push");
|
||||
expect(result.current.stopGuard).toBeNull();
|
||||
});
|
||||
|
||||
it("asks (without a push) when the check itself fails, and Cancel stops nothing", async () => {
|
||||
checkUnsavedWork.mockRejectedValue("Project p1 not found");
|
||||
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
|
||||
await act(async () => {
|
||||
await result.current.handleStop();
|
||||
});
|
||||
expect(result.current.stopGuard?.checked).toBe(false);
|
||||
await act(async () => {
|
||||
await result.current.resolveStopGuard(null);
|
||||
});
|
||||
expect(stop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("toasts a failed push or StopTask and leaves the project as it was", async () => {
|
||||
checkUnsavedWork.mockResolvedValue(dirty);
|
||||
stop.mockRejectedValue("Pushing unsaved work failed (exit 1), so the workspace was not stopped:\npush denied");
|
||||
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
|
||||
await act(async () => {
|
||||
await result.current.handleStop();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.resolveStopGuard("push");
|
||||
});
|
||||
expect(toasts().at(-1)?.detail).toMatch(/push denied/);
|
||||
});
|
||||
|
||||
it("never asks for a local project", async () => {
|
||||
const { result } = renderHook(() => useProjectActions(localProject({ status: "running" })));
|
||||
await act(async () => {
|
||||
await result.current.handleStop();
|
||||
});
|
||||
expect(checkUnsavedWork).not.toHaveBeenCalled();
|
||||
expect(stop).toHaveBeenCalledWith("p1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("useProjectActions start", () => {
|
||||
it("adds the task's last log lines to an AWS start failure", async () => {
|
||||
start.mockRejectedValue("The task stopped: Essential container exited");
|
||||
awsTaskLog.mockResolvedValue(["entrypoint: clone failed", "bye"]);
|
||||
const { result } = renderHook(() => useProjectActions(awsProject()));
|
||||
await act(async () => {
|
||||
await result.current.handleStart();
|
||||
});
|
||||
expect(awsTaskLog).toHaveBeenCalledWith("p1", 30);
|
||||
expect(toasts().at(-1)?.detail).toMatch(/Last log lines:\nentrypoint: clone failed\nbye/);
|
||||
});
|
||||
|
||||
it("does not read the log twice when the error already carries it", async () => {
|
||||
start.mockRejectedValue("failed\nLast log lines:\nx");
|
||||
const { result } = renderHook(() => useProjectActions(awsProject()));
|
||||
await act(async () => {
|
||||
await result.current.handleStart();
|
||||
});
|
||||
expect(awsTaskLog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import type { Project } from "../lib/types";
|
||||
import type { Project, UnsavedWork, WipChoice } from "../lib/types";
|
||||
import { isAwsProject, stopGuardNeeded } from "../lib/awsWorkspace";
|
||||
import * as commands from "../lib/tauri-commands";
|
||||
import { formatBytes } from "../lib/formatBytes";
|
||||
import { describeResetLeftovers, resetLeftoverPronoun } from "../lib/resetOutcome";
|
||||
@@ -8,6 +9,9 @@ import { useAppState } from "../store/appState";
|
||||
import { useProjects } from "./useProjects";
|
||||
import { useTerminal } from "./useTerminal";
|
||||
|
||||
/** How many task log lines a failed AWS start shows. */
|
||||
const TASK_LOG_LINES = 30;
|
||||
|
||||
/**
|
||||
* Lifecycle + terminal actions for one project, shared by the sidebar row and
|
||||
* Project Home so both surfaces behave identically. Failures raise a toast
|
||||
@@ -29,13 +33,17 @@ export function useProjectActions(project: Project) {
|
||||
);
|
||||
|
||||
const run = useCallback(
|
||||
async <T,>(label: string, fn: () => Promise<T>): Promise<T | undefined> => {
|
||||
async <T,>(
|
||||
label: string,
|
||||
fn: () => Promise<T>,
|
||||
explain?: (e: unknown) => Promise<string>,
|
||||
): Promise<T | undefined> => {
|
||||
setBusy(true);
|
||||
setContainerProgress(project.id, null);
|
||||
try {
|
||||
return await fn();
|
||||
} catch (e) {
|
||||
fail(`${label} failed for “${project.name}”`, e);
|
||||
fail(`${label} failed for “${project.name}”`, explain ? await explain(e) : e);
|
||||
return undefined;
|
||||
} finally {
|
||||
setContainerProgress(project.id, null);
|
||||
@@ -45,13 +53,63 @@ export function useProjectActions(project: Project) {
|
||||
[fail, project.id, project.name, setContainerProgress],
|
||||
);
|
||||
|
||||
const handleStart = useCallback(
|
||||
() => run("Start", () => start(project.id)),
|
||||
[run, start, project.id],
|
||||
const aws = isAwsProject(project);
|
||||
|
||||
/** An AWS start failure gets the task's last log lines, unless the error has them. */
|
||||
const withTaskLog = useCallback(
|
||||
async (e: unknown): Promise<string> => {
|
||||
const text = String(e);
|
||||
if (text.includes("Last log lines")) return text;
|
||||
try {
|
||||
const lines = await commands.awsTaskLog(project.id, TASK_LOG_LINES);
|
||||
if (lines.length > 0) return `${text}\n\nLast log lines:\n${lines.join("\n")}`;
|
||||
} catch {
|
||||
// The log is a courtesy; the start error is what matters.
|
||||
}
|
||||
return text;
|
||||
},
|
||||
[project.id],
|
||||
);
|
||||
|
||||
const handleStop = useCallback(
|
||||
() => run("Stop", () => stop(project.id)),
|
||||
const handleStart = useCallback(
|
||||
() => run("Start", () => start(project.id), aws ? withTaskLog : undefined),
|
||||
[run, start, project.id, aws, withTaskLog],
|
||||
);
|
||||
|
||||
/**
|
||||
* The stop guard's question, set while it is asked: an AWS workspace with
|
||||
* work no remote has (or one that could not be checked) is not stopped
|
||||
* until the user picks Push, Stop anyway or Cancel.
|
||||
*/
|
||||
const [stopGuard, setStopGuard] = useState<UnsavedWork | null>(null);
|
||||
|
||||
const handleStop = useCallback(async () => {
|
||||
// A force stop of a transition skips the question: there is nothing
|
||||
// reliable to ask yet.
|
||||
if (aws && project.status === "running") {
|
||||
setBusy(true);
|
||||
let work: UnsavedWork;
|
||||
try {
|
||||
work = await commands.checkUnsavedWork(project.id);
|
||||
} catch (e) {
|
||||
work = { checked: false, repos: [], error: String(e) };
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
if (stopGuardNeeded(work)) {
|
||||
setStopGuard(work);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return run("Stop", () => stop(project.id));
|
||||
}, [aws, project.status, project.id, run, stop]);
|
||||
|
||||
const resolveStopGuard = useCallback(
|
||||
(choice: WipChoice | null) => {
|
||||
setStopGuard(null);
|
||||
if (choice === null) return undefined;
|
||||
return run("Stop", () => stop(project.id, choice));
|
||||
},
|
||||
[run, stop, project.id],
|
||||
);
|
||||
|
||||
@@ -184,6 +242,8 @@ Reset again, or remove ${resetLeftoverPronoun(outcome)} manually once stopped.`,
|
||||
backingUp,
|
||||
handleStart,
|
||||
handleStop,
|
||||
stopGuard,
|
||||
resolveStopGuard,
|
||||
handleReset,
|
||||
handleBackup,
|
||||
openClaudeTerminal,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useAppState } from "../store/appState";
|
||||
import * as commands from "../lib/tauri-commands";
|
||||
import type { ProjectPath, ProjectStatus } from "../lib/types";
|
||||
import type { NewProjectHost, ProjectPath, ProjectStatus, RemoveProjectOptions, WipChoice } from "../lib/types";
|
||||
|
||||
export function useProjects() {
|
||||
const {
|
||||
@@ -31,8 +31,8 @@ export function useProjects() {
|
||||
}, [setProjects]);
|
||||
|
||||
const add = useCallback(
|
||||
async (name: string, paths: ProjectPath[]) => {
|
||||
const project = await commands.addProject(name, paths);
|
||||
async (name: string, paths: ProjectPath[], host?: NewProjectHost) => {
|
||||
const project = await commands.addProject(name, paths, host);
|
||||
// Refresh from backend to avoid stale closure issues
|
||||
const list = await commands.listProjects();
|
||||
setProjects(list);
|
||||
@@ -43,8 +43,8 @@ export function useProjects() {
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
async (id: string) => {
|
||||
const report = await commands.removeProject(id);
|
||||
async (id: string, opts?: RemoveProjectOptions) => {
|
||||
const report = await commands.removeProject(id, opts);
|
||||
removeProjectFromList(id);
|
||||
return report;
|
||||
},
|
||||
@@ -124,9 +124,9 @@ export function useProjects() {
|
||||
);
|
||||
|
||||
const stop = useCallback(
|
||||
(id: string) =>
|
||||
(id: string, wip?: WipChoice) =>
|
||||
withOptimisticStatus(id, "stopping", async () => {
|
||||
await commands.stopProjectContainer(id);
|
||||
await commands.stopProjectContainer(id, wip);
|
||||
const list = await commands.listProjects();
|
||||
setProjects(list);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
cleanRepos,
|
||||
environmentSelectable,
|
||||
memoryError,
|
||||
memoryOptions,
|
||||
nearestMemory,
|
||||
repoFolderFromUrl,
|
||||
stopGuardNeeded,
|
||||
} from "./awsWorkspace";
|
||||
import { environment } from "../test/awsFixtures";
|
||||
|
||||
describe("awsWorkspace", () => {
|
||||
it("knows Fargate's valid CPU/memory pairs", () => {
|
||||
expect(memoryOptions(256)).toEqual([512, 1024, 1536, 2048]);
|
||||
expect(memoryError(1024, 4096)).toBeNull();
|
||||
expect(memoryError(256, 4096)).toMatch(/not valid with 256/);
|
||||
expect(memoryError(8192, 17000)).toMatch(/steps of 4096/);
|
||||
expect(memoryError(300, 1024)).toMatch(/not a Fargate CPU/);
|
||||
expect(nearestMemory(256, 4096)).toBe(2048);
|
||||
expect(nearestMemory(16384, 4096)).toBe(32768);
|
||||
});
|
||||
|
||||
it("derives a clone folder from a URL", () => {
|
||||
expect(repoFolderFromUrl("https://github.com/org/api.git")).toBe("api");
|
||||
expect(repoFolderFromUrl("git@github.com:org/web-app.git")).toBe("web-app");
|
||||
expect(repoFolderFromUrl("ssh://h/x/y z/")).toBe("y-z");
|
||||
});
|
||||
|
||||
it("drops blank repository rows and keeps an empty branch as the default", () => {
|
||||
expect(
|
||||
cleanRepos([
|
||||
{ url: " https://h/r.git ", branch: " ", folder: "" },
|
||||
{ url: "", branch: null, folder: "" },
|
||||
]),
|
||||
).toEqual([{ url: "https://h/r.git", branch: null, folder: "r" }]);
|
||||
});
|
||||
|
||||
it("guards a stop with unsaved or unknown work", () => {
|
||||
const repo = { folder: "a", branch: "main", dirty: false, unpushed: 0 };
|
||||
expect(stopGuardNeeded({ checked: true, repos: [repo], error: null })).toBe(false);
|
||||
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, dirty: true }], error: null })).toBe(true);
|
||||
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, unpushed: 1 }], error: null })).toBe(true);
|
||||
expect(stopGuardNeeded({ checked: false, repos: [], error: "x" })).toBe(true);
|
||||
});
|
||||
|
||||
it("selects only ready environments the user joined", () => {
|
||||
expect(environmentSelectable(environment("a", "ready", true))).toBe(true);
|
||||
expect(environmentSelectable(environment("a", "update_available", true))).toBe(true);
|
||||
expect(environmentSelectable(environment("a", "ready", false))).toBe(false);
|
||||
expect(environmentSelectable(environment("a", "deploying", true))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type {
|
||||
AwsWorkspaceConfig,
|
||||
DetectedEnvironment,
|
||||
Project,
|
||||
RepoSource,
|
||||
UnsavedWork,
|
||||
} from "./types";
|
||||
|
||||
/** Why a Local-only option is off on an AWS project (P6). */
|
||||
export const NOT_ON_AWS = "Not available on AWS (Fargate)";
|
||||
/** R4: the AWS host forces Claude Code's sandbox off until it is verified on Fargate. */
|
||||
export const SANDBOX_OFF_ON_AWS = "Off on AWS for now";
|
||||
export const EPHEMERAL_WARNING =
|
||||
"Claude login and history are lost when the workspace stops.";
|
||||
|
||||
export function isAwsProject(p: Pick<Project, "host_id">): boolean {
|
||||
return p.host_id != null;
|
||||
}
|
||||
|
||||
/** Fargate CPU sizes (units of 1/1024 vCPU). */
|
||||
export const FARGATE_CPUS = [256, 512, 1024, 2048, 4096, 8192, 16384] as const;
|
||||
|
||||
/** Mirrors Rust `fargate_memory_range`: `[min, max, step]` MiB for a CPU size. */
|
||||
export function fargateMemoryRange(cpu: number): [number, number, number] | null {
|
||||
switch (cpu) {
|
||||
case 256:
|
||||
return [512, 2048, 512];
|
||||
case 512:
|
||||
return [1024, 4096, 1024];
|
||||
case 1024:
|
||||
return [2048, 8192, 1024];
|
||||
case 2048:
|
||||
return [4096, 16384, 1024];
|
||||
case 4096:
|
||||
return [8192, 30720, 1024];
|
||||
case 8192:
|
||||
return [16384, 61440, 4096];
|
||||
case 16384:
|
||||
return [32768, 122880, 8192];
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every memory size valid with `cpu`, smallest first. */
|
||||
export function memoryOptions(cpu: number): number[] {
|
||||
const range = fargateMemoryRange(cpu);
|
||||
if (!range) return [];
|
||||
const [min, max, step] = range;
|
||||
const out: number[] = [];
|
||||
for (let m = min; m <= max; m += step) out.push(m);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Null when `memory` MiB is valid with `cpu`; otherwise the reason (as Rust words it). */
|
||||
export function memoryError(cpu: number, memory: number): string | null {
|
||||
const range = fargateMemoryRange(cpu);
|
||||
if (!range) return `${cpu} is not a Fargate CPU size`;
|
||||
const [min, max, step] = range;
|
||||
if (!Number.isInteger(memory) || memory < min || memory > max || (memory - min) % step !== 0) {
|
||||
return `${memory} MiB of memory is not valid with ${cpu} CPU units: use ${min} to ${max} MiB in steps of ${step}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The valid memory size nearest `memory` for `cpu` (used when the CPU changes). */
|
||||
export function nearestMemory(cpu: number, memory: number): number {
|
||||
const opts = memoryOptions(cpu);
|
||||
return opts.reduce((best, m) => (Math.abs(m - memory) < Math.abs(best - memory) ? m : best), opts[0]);
|
||||
}
|
||||
|
||||
export function formatCpu(cpu: number): string {
|
||||
return `${cpu / 1024} vCPU`;
|
||||
}
|
||||
|
||||
export function formatMemory(mib: number): string {
|
||||
return mib % 1024 === 0 ? `${mib / 1024} GiB` : `${mib} MiB`;
|
||||
}
|
||||
|
||||
/** Mirrors Rust `AwsWorkspaceConfig::default()`. */
|
||||
export function defaultAwsWorkspace(): AwsWorkspaceConfig {
|
||||
return {
|
||||
cpu: 1024,
|
||||
memory_mib: 4096,
|
||||
arch: "x86_64",
|
||||
storage: "hybrid",
|
||||
ephemeral_gib: 21,
|
||||
spot: false,
|
||||
idle_stop_minutes: null,
|
||||
repos: [],
|
||||
wip_push_on_stop: true,
|
||||
task_arn: null,
|
||||
access_point_id: null,
|
||||
task_definition_arn: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The folder a clone of `url` would get: its last path part without `.git`,
|
||||
* reduced to the characters Rust's folder rule allows. */
|
||||
export function repoFolderFromUrl(url: string): string {
|
||||
const last = url.trim().replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
|
||||
return last.replace(/\.git$/, "").replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64);
|
||||
}
|
||||
|
||||
/** Rows the editors hold, minus blank ones; a branch left empty is the default branch. */
|
||||
export function cleanRepos(rows: RepoSource[]): RepoSource[] {
|
||||
return rows
|
||||
.filter((r) => r.url.trim() || r.folder.trim() || (r.branch ?? "").trim())
|
||||
.map((r) => ({
|
||||
url: r.url.trim(),
|
||||
branch: (r.branch ?? "").trim() || null,
|
||||
folder: r.folder.trim() || repoFolderFromUrl(r.url),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Whether Stop must ask first (mirrors Rust `needs_guard`). */
|
||||
export function stopGuardNeeded(work: UnsavedWork): boolean {
|
||||
return !work.checked || work.repos.some((r) => r.dirty || r.unpushed > 0);
|
||||
}
|
||||
|
||||
/** An environment a project can be placed in: ready (or merely behind) and joined. */
|
||||
export function environmentSelectable(env: DetectedEnvironment): boolean {
|
||||
const ready = env.state.state === "ready" || env.state.state === "update_available";
|
||||
return ready && env.onboarding?.state === "joined";
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { Project, ProjectPath, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
|
||||
import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
|
||||
|
||||
// Docker
|
||||
export const checkDocker = () => invoke<boolean>("check_docker");
|
||||
@@ -10,16 +10,33 @@ export const getContainerInfo = (projectId: string) =>
|
||||
|
||||
// Projects
|
||||
export const listProjects = () => invoke<Project[]>("list_projects");
|
||||
export const addProject = (name: string, paths: ProjectPath[]) =>
|
||||
invoke<Project>("add_project", { name, paths });
|
||||
export const removeProject = (projectId: string) =>
|
||||
invoke<ProjectRemovalReport>("remove_project", { projectId });
|
||||
export const addProject = (name: string, paths: ProjectPath[], host?: NewProjectHost) =>
|
||||
invoke<Project>("add_project", {
|
||||
name,
|
||||
paths,
|
||||
hostId: host?.hostId ?? null,
|
||||
awsPlacement: host?.awsPlacement ?? null,
|
||||
aws: host?.aws ?? null,
|
||||
});
|
||||
export const removeProject = (projectId: string, opts: RemoveProjectOptions = {}) =>
|
||||
invoke<ProjectRemovalReport>("remove_project", {
|
||||
projectId,
|
||||
discardData: opts.discardData ?? null,
|
||||
forgetAwsResources: opts.forgetAwsResources ?? null,
|
||||
});
|
||||
export const updateProject = (project: Project) =>
|
||||
invoke<Project>("update_project", { project });
|
||||
export const startProjectContainer = (projectId: string) =>
|
||||
invoke<Project>("start_project_container", { projectId });
|
||||
export const stopProjectContainer = (projectId: string) =>
|
||||
invoke<void>("stop_project_container", { projectId });
|
||||
/** `wip` is the stop guard's choice for an AWS project (a local one ignores it). */
|
||||
export const stopProjectContainer = (projectId: string, wip?: WipChoice) =>
|
||||
invoke<void>("stop_project_container", { projectId, wip: wip ?? null });
|
||||
export const checkUnsavedWork = (projectId: string) =>
|
||||
invoke<UnsavedWork>("check_unsaved_work", { projectId });
|
||||
export const awsTaskLog = (projectId: string, limit: number) =>
|
||||
invoke<string[]>("aws_task_log", { projectId, limit });
|
||||
export const removeAwsResources = (projectId: string, discardData: boolean) =>
|
||||
invoke<Project>("remove_aws_resources", { projectId, discardData });
|
||||
export const rebuildProjectContainer = (projectId: string) =>
|
||||
invoke<ProjectResetOutcome>("rebuild_project_container", { projectId });
|
||||
export const reconcileProjectStatuses = () =>
|
||||
|
||||
@@ -107,6 +107,40 @@ export interface AwsWorkspaceConfig {
|
||||
task_definition_arn: string | null;
|
||||
}
|
||||
|
||||
/** Where a new project runs: omitted (or all null) = local Docker. An AWS
|
||||
* project passes all three and no folders. */
|
||||
export interface NewProjectHost {
|
||||
hostId: string | null;
|
||||
awsPlacement: AwsPlacement | null;
|
||||
aws: AwsWorkspaceConfig | null;
|
||||
}
|
||||
|
||||
export interface RemoveProjectOptions {
|
||||
/** AWS: also delete the workspace's saved files (its EFS access point). */
|
||||
discardData?: boolean;
|
||||
/** AWS: the connection is gone; remove the project and leave its AWS resources. */
|
||||
forgetAwsResources?: boolean;
|
||||
}
|
||||
|
||||
/** What Stop does with an AWS workspace's unsaved git work (Rust `WipChoice`). */
|
||||
export type WipChoice = "push" | "discard";
|
||||
|
||||
/** One repository line of `triple-c-wip-push --dry-run` (Rust `RepoState`). */
|
||||
export interface RepoState {
|
||||
folder: string;
|
||||
dirty: boolean;
|
||||
unpushed: number;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
/** What `checkUnsavedWork` found (Rust `UnsavedWork`). `checked: false` (with
|
||||
* `error`) when the workspace could not be asked. */
|
||||
export interface UnsavedWork {
|
||||
checked: boolean;
|
||||
repos: RepoState[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export type ProjectStatus =
|
||||
| "stopped"
|
||||
| "starting"
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { DetectedEnvironment, Project } from "../lib/types";
|
||||
import { defaultAwsWorkspace } from "../lib/awsWorkspace";
|
||||
|
||||
/** A complete local project for component tests. */
|
||||
export function localProject(over: Partial<Project> = {}): Project {
|
||||
return {
|
||||
id: "p1",
|
||||
name: "api-server",
|
||||
paths: [{ host_path: "/src/api", mount_name: "api" }],
|
||||
container_id: null,
|
||||
status: "stopped",
|
||||
backend: "anthropic",
|
||||
bedrock_config: null,
|
||||
ollama_config: null,
|
||||
llamacpp_config: null,
|
||||
openai_compatible_config: null,
|
||||
allow_docker_access: true,
|
||||
sandbox_mode_enabled: true,
|
||||
mission_control_enabled: false,
|
||||
auth_bridge_enabled: false,
|
||||
browser_view_enabled: false,
|
||||
vpn_support_enabled: true,
|
||||
use_shared_auth_token: true,
|
||||
full_permissions: false,
|
||||
permission_mode: null,
|
||||
ssh_key_path: null,
|
||||
ca_cert_path: null,
|
||||
git_token: null,
|
||||
git_user_name: null,
|
||||
git_user_email: null,
|
||||
custom_env_vars: [],
|
||||
port_mappings: [{ host_port: 3000, container_port: 3000, protocol: "tcp" }],
|
||||
claude_instructions: null,
|
||||
claude_code_settings: null,
|
||||
renamed_session_names: {},
|
||||
marketplace_installs: [],
|
||||
marketplace_disabled: [],
|
||||
host_id: null,
|
||||
aws_placement: null,
|
||||
aws: null,
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
updated_at: "2026-01-01T00:00:00Z",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** The same project placed on an AWS connection `c1`. */
|
||||
export function awsProject(over: Partial<Project> = {}): Project {
|
||||
return localProject({
|
||||
paths: [],
|
||||
host_id: "c1",
|
||||
aws_placement: { region: "eu-west-1", environment: "dev" },
|
||||
aws: {
|
||||
...defaultAwsWorkspace(),
|
||||
repos: [{ url: "https://example.com/org/api.git", branch: null, folder: "api" }],
|
||||
},
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
export function environment(
|
||||
name: string,
|
||||
state: DetectedEnvironment["state"]["state"],
|
||||
joined: boolean,
|
||||
): DetectedEnvironment {
|
||||
return {
|
||||
name,
|
||||
template_version: 1,
|
||||
state: { state } as DetectedEnvironment["state"],
|
||||
actions: [],
|
||||
info: null,
|
||||
onboarding: joined ? { state: "joined" } : { state: "not_joined" },
|
||||
onboarding_actions: [],
|
||||
onboarded_users: 1,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user