feat: Add Fleet Sharing functionality to the UI (#1228)

https://github.com/Termix-SSH/Support/issues/1228
This commit is contained in:
LukeGus committed 2026-09-20 18:12:10 -05:00
1 parent 6837144ad5
commit da840b925c
3 files changed
+509 -2

No files matched your search

+35 -1
View File
@@ -1,4 +1,9 @@
import { authApi, handleApiError } from "@/main-axios";
import {
authApi,
handleApiError,
type SharePermissionLevel,
type ShareTarget,
} from "@/main-axios";
export interface FleetRow {
id: number;
@@ -245,3 +250,32 @@ export async function runFleetPackageAction(
throw handleApiError(error, "run fleet package action");
}
}
export interface FleetShareHostResult {
hostId: number;
shared: boolean;
reason?: string;
}
export async function shareFleet(
fleetId: number,
shareData: {
targets: ShareTarget[];
permissionLevel: SharePermissionLevel;
durationHours?: number;
},
): Promise<{
success: boolean;
permissionLevel: SharePermissionLevel;
expiresAt: string | null;
hostsShared: number;
hostsTotal: number;
hostResults: FleetShareHostResult[];
}> {
try {
const response = await authApi.post(`/fleets/${fleetId}/share`, shareData);
return response.data;
} catch (error) {
throw handleApiError(error, "share fleet");
}
}
+8 -1
View File
@@ -4370,7 +4370,14 @@
"packageUpgradeAll": "Upgrade all packages",
"packageNameLabel": "Package name",
"packageNameRequired": "A package name is required",
"packageHint": "Requires manage-level access per host and elevates using the host's stored sudo password."
"packageHint": "Requires manage-level access per host and elevates using the host's stored sudo password.",
"shareFleet": "Share Fleet",
"shareFleetTitle": "Share \"{{name}}\"",
"shareFleetDescription": "Shares this fleet's current member hosts with the selected users or roles. Hosts added to the fleet later are not shared automatically - share again to include them.",
"shareSelectionRequired": "Select at least one user or role",
"fleetSharedSuccessfully": "Shared {{shared}} of {{total}} host(s) in this fleet",
"failedToShareFleet": "Failed to share fleet",
"noMembersToShare": "This fleet has no member hosts to share yet."
},
"workspaces": {
"title": "Workspaces",
+466
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
Boxes,
Check,
ChevronLeft,
Download,
ExternalLink,
@@ -15,8 +16,11 @@ import {
Search,
Server,
Settings2,
Share2,
Shield,
Trash2,
Upload,
User,
X,
} from "lucide-react";
import { Button } from "@/components/button";
@@ -34,6 +38,15 @@ import {
} from "@/components/dialog";
import { FOLDER_COLORS } from "@/lib/theme";
import { getSSHHosts } from "@/api/ssh-host-management-api";
import { getUserList } from "@/api/user-management-api";
import { getRoles, type SharePermissionLevel, type ShareTarget } from "@/api/rbac-api";
import { Select2 } from "@/components/select2";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
import {
extractSnippetInputs,
type SnippetInput,
@@ -52,14 +65,34 @@ import {
getFleetInventory,
refreshFleetInventory,
runFleetPackageAction,
shareFleet,
type FleetRow,
type FleetMemberRow,
type FleetHostResult,
type FleetInventoryEntry,
type FleetPackageAction,
type FleetShareHostResult,
} from "@/api/fleets-api";
import type { SSHHost } from "@/types/index";
const SHARE_PERMISSION_LEVELS: SharePermissionLevel[] = [
"connect",
"view",
"edit",
"manage",
];
const SHARE_EXPIRY_PRESETS = [
{ key: "never", hours: undefined },
{ key: "oneHour", hours: 1 },
{ key: "oneDay", hours: 24 },
{ key: "sevenDays", hours: 24 * 7 },
{ key: "thirtyDays", hours: 24 * 30 },
{ key: "custom", hours: undefined },
] as const;
type ShareExpiryPresetKey = (typeof SHARE_EXPIRY_PRESETS)[number]["key"];
function formatUptime(seconds: number | null): string {
if (seconds === null) return "-";
const d = Math.floor(seconds / 86400);
@@ -373,6 +406,406 @@ function MemberPickerDialog({
);
}
function FleetShareDialog({
open,
onClose,
fleet,
}: {
open: boolean;
onClose: () => void;
fleet: FleetRow | null;
}) {
const { t } = useTranslation();
const [targetTab, setTargetTab] = useState<"user" | "role">("user");
const [search, setSearch] = useState("");
const [shareUsers, setShareUsers] = useState<
{ id: string; username: string }[]
>([]);
const [shareRoles, setShareRoles] = useState<
{ id: number; name: string; displayName?: string }[]
>([]);
const [selectedUserIds, setSelectedUserIds] = useState<Set<string>>(
new Set(),
);
const [selectedRoleIds, setSelectedRoleIds] = useState<Set<number>>(
new Set(),
);
const [permissionLevel, setPermissionLevel] =
useState<SharePermissionLevel>("connect");
const [expiryPreset, setExpiryPreset] =
useState<ShareExpiryPresetKey>("never");
const [customHours, setCustomHours] = useState("");
const [submitting, setSubmitting] = useState(false);
const [summary, setSummary] = useState<{
hostsShared: number;
hostsTotal: number;
hostResults: FleetShareHostResult[];
} | null>(null);
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedUserIds(new Set());
setSelectedRoleIds(new Set());
setPermissionLevel("connect");
setExpiryPreset("never");
setCustomHours("");
setTargetTab("user");
setSummary(null);
Promise.all([
getUserList().catch(() => ({ users: [] })),
getRoles().catch(() => ({ roles: [] })),
]).then(([usersRes, rolesRes]) => {
setShareUsers(
(usersRes.users ?? []).map((u) => ({
id: String(u.userId),
username: u.username,
})),
);
setShareRoles(
(rolesRes.roles ?? [])
.filter((r) => !r.isSystem)
.map((r) => ({
id: Number(r.id),
name: r.name,
displayName: r.displayName,
})),
);
});
}, [open]);
const filteredUsers = useMemo(() => {
const q = search.trim().toLowerCase();
return q
? shareUsers.filter((u) => u.username.toLowerCase().includes(q))
: shareUsers;
}, [shareUsers, search]);
const filteredRoles = useMemo(() => {
const q = search.trim().toLowerCase();
return q
? shareRoles.filter(
(r) =>
r.name.toLowerCase().includes(q) ||
(r.displayName ?? "").toLowerCase().includes(q),
)
: shareRoles;
}, [shareRoles, search]);
const selectedCount = selectedUserIds.size + selectedRoleIds.size;
const durationHours = (() => {
if (expiryPreset === "never") return undefined;
if (expiryPreset === "custom") {
const hours = Number(customHours);
return Number.isFinite(hours) && hours > 0 ? hours : undefined;
}
return (
SHARE_EXPIRY_PRESETS.find((p) => p.key === expiryPreset)?.hours ??
undefined
);
})();
async function handleShare() {
if (!fleet || selectedCount === 0) return;
const targets: ShareTarget[] = [
...[...selectedUserIds].map(
(id) => ({ type: "user", id }) as ShareTarget,
),
...[...selectedRoleIds].map(
(id) => ({ type: "role", id }) as ShareTarget,
),
];
setSubmitting(true);
try {
const result = await shareFleet(fleet.id, {
targets,
permissionLevel,
...(durationHours ? { durationHours } : {}),
});
setSummary({
hostsShared: result.hostsShared,
hostsTotal: result.hostsTotal,
hostResults: result.hostResults,
});
setSelectedUserIds(new Set());
setSelectedRoleIds(new Set());
toast.success(
t("newUi.sidebar.fleets.fleetSharedSuccessfully", {
shared: result.hostsShared,
total: result.hostsTotal,
}),
);
} catch (error) {
const message = getErrorMessage(error, "");
toast.error(message || t("newUi.sidebar.fleets.failedToShareFleet"));
} finally {
setSubmitting(false);
}
}
return (
<Dialog open={open} onOpenChange={(next) => !next && onClose()}>
<DialogContent className="sm:max-w-md flex flex-col max-h-[85dvh]">
<DialogHeader>
<DialogTitle>
{t("newUi.sidebar.fleets.shareFleetTitle", {
name: fleet?.name ?? "",
})}
</DialogTitle>
<DialogDescription>
{t("newUi.sidebar.fleets.shareFleetDescription")}
</DialogDescription>
</DialogHeader>
<div className="flex-1 min-h-0 overflow-y-auto flex flex-col gap-3">
{fleet && fleet.memberCount === 0 ? (
<div className="text-xs text-muted-foreground text-center py-6">
{t("newUi.sidebar.fleets.noMembersToShare")}
</div>
) : (
<>
<div className="flex gap-1.5">
{(["user", "role"] as const).map((tab) => (
<button
key={tab}
type="button"
onClick={() => setTargetTab(tab)}
className={`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${targetTab === tab ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
>
{tab === "user" ? (
<User className="size-3 shrink-0" />
) : (
<Shield className="size-3 shrink-0" />
)}
{tab === "user"
? t("hosts.sharing.usersTab")
: t("hosts.sharing.rolesTab")}
{tab === "user" && selectedUserIds.size > 0 && (
<span>({selectedUserIds.size})</span>
)}
{tab === "role" && selectedRoleIds.size > 0 && (
<span>({selectedRoleIds.size})</span>
)}
</button>
))}
</div>
<div className="relative shrink-0">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground/50" />
<Input
placeholder={t("hosts.sharing.searchPlaceholder")}
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-8"
/>
</div>
<div className="flex flex-col border border-border h-28 overflow-y-auto shrink-0">
{targetTab === "user" &&
(filteredUsers.length === 0 ? (
<div className="px-3 py-4 text-xs text-muted-foreground/50 text-center">
{t("hosts.sharing.noMatches")}
</div>
) : (
filteredUsers.map((user) => {
const isSelected = selectedUserIds.has(user.id);
return (
<button
key={user.id}
type="button"
onClick={() =>
setSelectedUserIds((prev) => {
const next = new Set(prev);
if (next.has(user.id)) next.delete(user.id);
else next.add(user.id);
return next;
})
}
className={`flex items-center gap-2 px-2.5 py-1.5 text-xs text-left border-b border-border/50 last:border-0 transition-colors shrink-0 ${isSelected ? "bg-accent-brand/10 text-accent-brand" : "hover:bg-muted/40"}`}
>
<div
className={`size-3.5 border flex items-center justify-center shrink-0 transition-colors ${isSelected ? "border-accent-brand bg-accent-brand" : "border-border bg-background"}`}
>
{isSelected && (
<Check className="size-2.5 text-background" />
)}
</div>
<User className="size-3 text-muted-foreground shrink-0" />
<span className="truncate">{user.username}</span>
</button>
);
})
))}
{targetTab === "role" &&
(filteredRoles.length === 0 ? (
<div className="px-3 py-4 text-xs text-muted-foreground/50 text-center">
{t("hosts.sharing.noMatches")}
</div>
) : (
filteredRoles.map((role) => {
const isSelected = selectedRoleIds.has(role.id);
return (
<button
key={role.id}
type="button"
onClick={() =>
setSelectedRoleIds((prev) => {
const next = new Set(prev);
if (next.has(role.id)) next.delete(role.id);
else next.add(role.id);
return next;
})
}
className={`flex items-center gap-2 px-2.5 py-1.5 text-xs text-left border-b border-border/50 last:border-0 transition-colors shrink-0 ${isSelected ? "bg-accent-brand/10 text-accent-brand" : "hover:bg-muted/40"}`}
>
<div
className={`size-3.5 border flex items-center justify-center shrink-0 transition-colors ${isSelected ? "border-accent-brand bg-accent-brand" : "border-border bg-background"}`}
>
{isSelected && (
<Check className="size-2.5 text-background" />
)}
</div>
<Shield className="size-3 text-muted-foreground shrink-0" />
<span className="truncate">
{role.displayName || role.name}
</span>
</button>
);
})
))}
</div>
<div className="flex items-end gap-2 shrink-0">
<div className="flex flex-col gap-1 flex-1 min-w-0">
<span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
{t("hosts.sharing.permissionLevelLabel")}
</span>
<Select2
value={permissionLevel}
onChange={(e) =>
setPermissionLevel(
e.target.value as SharePermissionLevel,
)
}
className="h-8 w-full px-2.5 text-xs border border-border bg-background hover:bg-muted/40 transition-colors"
>
{SHARE_PERMISSION_LEVELS.map((level) => (
<option key={level} value={level}>
{t(`hosts.sharing.levels.${level}.label`)}
</option>
))}
</Select2>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex flex-col gap-1 shrink-0"
>
<span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground text-left">
{t("hosts.sharing.expiryLabel")}
</span>
<span className="h-8 flex items-center justify-center px-2.5 text-xs border border-border hover:bg-muted/40 transition-colors whitespace-nowrap">
{t(`hosts.sharing.expiry.${expiryPreset}`)}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="text-xs">
{SHARE_EXPIRY_PRESETS.map((preset) => (
<DropdownMenuItem
key={preset.key}
onClick={() => setExpiryPreset(preset.key)}
>
{expiryPreset === preset.key ? (
<Check className="size-3 mr-1.5" />
) : (
<span className="size-3 mr-1.5" />
)}
{t(`hosts.sharing.expiry.${preset.key}`)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<p className="text-[11px] text-muted-foreground leading-snug shrink-0">
{t(`hosts.sharing.levels.${permissionLevel}.description`)}
</p>
{expiryPreset === "custom" && (
<Input
type="number"
autoFocus
placeholder={t("hosts.sharing.customHoursPlaceholder")}
value={customHours}
onChange={(e) => setCustomHours(e.target.value)}
className="shrink-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
/>
)}
{summary && (
<div className="flex flex-col gap-1 text-xs text-muted-foreground border-t border-border pt-2 shrink-0">
<span>
{t("newUi.sidebar.fleets.fleetSharedSuccessfully", {
shared: summary.hostsShared,
total: summary.hostsTotal,
})}
</span>
{summary.hostResults.some((r) => !r.shared) && (
<div className="flex flex-col gap-0.5">
{summary.hostResults
.filter((r) => !r.shared)
.map((r) => (
<span
key={r.hostId}
className="text-[10px] text-destructive"
>
{t("newUi.sidebar.fleets.resultFailed")}: #
{r.hostId} ({r.reason ?? "unknown"})
</span>
))}
</div>
)}
</div>
)}
</>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{t("common.close")}
</Button>
{fleet && fleet.memberCount > 0 && (
<Button
variant="outline"
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
disabled={
selectedCount === 0 ||
submitting ||
(expiryPreset === "custom" && !durationHours)
}
onClick={handleShare}
>
{submitting ? (
<Loader2 className="size-3.5 mr-1.5 animate-spin" />
) : (
<Share2 className="size-3.5 mr-1.5" />
)}
{selectedCount > 0
? t("hosts.sharing.shareWithCount", { count: selectedCount })
: t("hosts.sharing.shareButton")}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function RunCommandTab({ fleetId }: { fleetId: number }) {
const { t } = useTranslation();
const [command, setCommand] = useState("");
@@ -821,6 +1254,7 @@ function FleetDetail({
const [members, setMembers] = useState<FleetMemberRow[]>([]);
const [loadingMembers, setLoadingMembers] = useState(true);
const [pickerOpen, setPickerOpen] = useState(false);
const [shareOpen, setShareOpen] = useState(false);
const [actionView, setActionView] = useState<FleetActionView>("run");
const loadMembers = useCallback(async () => {
@@ -865,6 +1299,14 @@ function FleetDetail({
variant="outline"
size="sm"
className="ml-auto"
onClick={() => setShareOpen(true)}
>
<Share2 className="size-3.5 mr-1.5" />
{t("newUi.sidebar.fleets.shareFleet")}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPickerOpen(true)}
>
<Settings2 className="size-3.5 mr-1.5" />
@@ -930,6 +1372,12 @@ function FleetDetail({
memberIds={memberIds}
onChanged={handleMembersChanged}
/>
<FleetShareDialog
open={shareOpen}
onClose={() => setShareOpen(false)}
fleet={fleet}
/>
</div>
);
}
@@ -950,6 +1398,7 @@ export function FleetsPanel({
const [formOpen, setFormOpen] = useState(false);
const [editingFleet, setEditingFleet] = useState<FleetRow | null>(null);
const [deleteTarget, setDeleteTarget] = useState<FleetRow | null>(null);
const [shareTarget, setShareTarget] = useState<FleetRow | null>(null);
const hasLoadedRef = useRef(false);
const loadFleets = useCallback(async () => {
@@ -1090,6 +1539,17 @@ export function FleetsPanel({
count: fleet.memberCount,
})}
</Badge>
<Button
variant="ghost"
size="sm"
className="shrink-0 opacity-0 group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
setShareTarget(fleet);
}}
>
<Share2 className="size-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
@@ -1126,6 +1586,12 @@ export function FleetsPanel({
onSaved={loadFleets}
/>
<FleetShareDialog
open={!!shareTarget}
onClose={() => setShareTarget(null)}
fleet={shareTarget}
/>
<Dialog
open={!!deleteTarget}
onOpenChange={(next) => !next && setDeleteTarget(null)}