fleet/frontend/pages/hosts/components/CommandDetailsModal/CommandDetailsModal.tsx
Ian Littman da6cfd8e9f
Show configuration profile name and more fine-grained status (#42126)
Resolves #40177 and subissues.

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files)
for more information.

- [x] Input data is properly validated, `SELECT *` is avoided, SQL
injection is prevented (using placeholders for values in statements), JS
inline code is prevented especially for url redirects, and untrusted
data interpolated into shell scripts/commands is validated against shell
metacharacters.

## Testing

- [x] Added/updated automated tests
- [x] Where appropriate, [automated tests simulate multiple hosts and
test for host
isolation](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/reference/patterns-backend.md#unit-testing)
(updates to one hosts's records do not affect another)

- [sorta] QA'd all new/changed functionality manually

## Database migrations

- [x] Checked schema for all modified table for columns that will
auto-update timestamps during migration.
- [x] Confirmed that updating the timestamps is acceptable, and will not
cause unwanted side effects.
- [x] Ensured the correct collation is explicitly set for character
columns (`COLLATE utf8mb4_unicode_ci`).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Profile names are now displayed alongside mobile device management
commands for installing or removing profiles. These names are visible in
command details modals and within device activity timelines.
* Added "NotNow" status for deferred profile commands, providing
improved transparency into which profiles are being managed and the
current status of profile installation or removal operations.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-09 12:46:11 -05:00

220 lines
5.7 KiB
TypeScript

import React from "react";
import { useQuery } from "react-query";
import { formatDistanceToNow } from "date-fns";
import { DEFAULT_USE_QUERY_OPTIONS } from "utilities/constants";
import { ICommand, ICommandResult } from "interfaces/command";
import commandApi, {
IGetCommandResultsResponse,
IGetHostCommandResultsQueryKey,
} from "services/entities/command";
import InputField from "components/forms/fields/InputField";
import Modal from "components/Modal";
import Spinner from "components/Spinner";
import DataError from "components/DataError";
import IconStatusMessage from "components/IconStatusMessage";
import { IconNames } from "components/icons";
import ModalFooter from "components/ModalFooter";
import Button from "components/buttons/Button";
const baseClass = "command-details-modal";
const getIconName = (status: string): IconNames => {
switch (status) {
case "Error":
return "error";
case "CommandFormatError":
return "error";
case "Acknowledged":
return "success";
case "Pending":
return "pending-outline";
case "NotNow":
return "pending-outline";
default:
// FIXME: update for other platforms and design appropriate default handling for unknown
// statuses; for now, just return warning icon to indicate unknown state
return "warning";
}
};
const getStatusMessage = (result: ICommandResult): React.ReactNode => {
const displayTime = result.updated_at
? ` (${formatDistanceToNow(new Date(result.updated_at), {
includeSeconds: true,
addSuffix: true,
})})`
: null;
const namePart = result.name ? (
<>
{" "}
for <b>{result.name}</b>
</>
) : null;
switch (result.status) {
case "CommandFormatError":
case "Error":
return (
<span>
The <b>{result.request_type}</b> command{namePart} failed on{" "}
<b>{result.hostname}</b>
{displayTime}.
</span>
);
case "Acknowledged":
return (
<span>
The <b>{result.request_type}</b> command{namePart} was acknowledged by{" "}
<b>{result.hostname}</b>
{displayTime}.
</span>
);
case "Pending":
return (
<span>
The <b>{result.request_type}</b> command{namePart} is pending on{" "}
<b>{result.hostname}</b>.
</span>
);
case "NotNow":
return (
<span>
The <b>{result.request_type}</b> command{namePart} is deferred on{" "}
<b>{result.hostname}</b> because the host was locked or was running on
battery power while in Power Nap. Fleet will try again.
</span>
);
default:
// FIXME: update for other platforms and design appropriate default handling for unknown
// statuses; for now, just fallback to status string
return <span>{`Status: ${result.status}`}</span>;
}
};
const ModalContent = ({
data,
isLoading,
error,
}: {
data: IGetCommandResultsResponse | undefined;
isLoading: boolean;
error: Error | null;
}) => {
if (isLoading) {
return <Spinner />;
}
if (error) {
return <DataError description="Close this modal and try again." />;
}
if (!data?.results?.[0]) {
// this should not happen, but just in case
console.error("No results found in MDM command results data");
return <DataError description="Close this modal and try again." />;
}
if (data.results.length > 1) {
// this should not happen, but just in case
console.error(
`Expected one result, but found ${data.results.length} results.`
);
return <DataError description="Close this modal and try again." />;
}
const result = data.results[0];
return (
<div className={`${baseClass}__modal-content`}>
<IconStatusMessage
className={`${baseClass}__status-message`}
iconName={getIconName(result.status)}
message={getStatusMessage(result)}
/>
{!!result.payload && (
<InputField
type="textarea"
label="Request payload:"
value={result.payload}
readOnly
enableCopy
/>
)}
{!!result.result && (
<InputField
type="textarea"
label={
<>
Response from <b>{result.hostname}</b>:
</>
}
value={result.result}
readOnly
enableCopy
/>
)}
</div>
);
};
interface ICommandResultsModalProps {
command: ICommand;
onDone: () => void;
}
const CommandResultsModal = ({
command: { host_uuid: host_identifier, command_uuid },
onDone,
}: ICommandResultsModalProps) => {
const { data, isLoading, error } = useQuery<
IGetCommandResultsResponse,
Error,
IGetCommandResultsResponse,
IGetHostCommandResultsQueryKey[]
>(
[{ scope: "command_results", host_identifier, command_uuid }],
({ queryKey }) =>
commandApi.getHostCommandResults(queryKey[0]).then((resp) => {
if (!resp?.results) {
// this should not happen, but just in case return the response as is
return resp;
}
return {
results: resp.results.map?.((r) => ({
...r,
payload: atob(r.payload),
result: atob(r.result),
})),
};
}),
{
...DEFAULT_USE_QUERY_OPTIONS,
keepPreviousData: true,
staleTime: 2000,
}
);
return (
<Modal
className={baseClass}
width="large"
title="MDM command details"
onExit={onDone}
>
<ModalContent data={data} isLoading={isLoading} error={error} />
<ModalFooter primaryButtons={<Button onClick={onDone}>Close</Button>} />
</Modal>
);
};
export default CommandResultsModal;