fix(ui): address audit page review findings

This commit is contained in:
sam committed 2026-10-25 22:14:33 +11:00
1 parent d28aa2184b
commit 9d8156790e
5 files changed
+205 -128

No files matched your search

+4 -2
View File
@@ -8,6 +8,7 @@ import { MetadataList } from "@/components/ui/metadata-list";
import {
changesFromFields,
metadataRows,
targetHref,
type AuditRecord,
} from "./audit";
@@ -16,6 +17,7 @@ defineEmits<{ revert: [] }>();
const changes = computed(() => changesFromFields(props.record.detail));
const rows = computed(() => metadataRows(props.record));
const href = computed(() => targetHref(props.record.target));
</script>
<template>
@@ -24,8 +26,8 @@ const rows = computed(() => metadataRows(props.record));
<MetadataList v-if="rows.length" :rows="rows">
<template #value="{ row }">
<RouterLink
v-if="row.key === 'target' && record.target?.href"
:to="record.target.href"
v-if="row.key === 'target' && href"
:to="href"
class="hover:underline"
>{{ row.value }}</RouterLink>
<template v-else>{{ row.value }}</template>
+5 -4
View File
@@ -10,8 +10,9 @@ import {
} from "@/components/ui/dropdown-menu";
import { api, type QueryParams } from "@/lib/api";
/** Export is a browser download: the anchor navigates, so the server owns the
* filename and streams the body to disk. */
/** Export is a navigation, not a fetch: the server owns the filename through
* Content-Disposition. A new tab keeps a failed export's response visible
* instead of saving the error text as a file. */
const props = defineProps<{ params: QueryParams }>();
function url(format: "csv" | "json"): string {
@@ -26,10 +27,10 @@ function url(format: "csv" | "json"): string {
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem as-child>
<a :href="url('csv')" download aria-label="Export as CSV">CSV</a>
<a :href="url('csv')" target="_blank" rel="noopener" aria-label="Export as CSV">CSV</a>
</DropdownMenuItem>
<DropdownMenuItem as-child>
<a :href="url('json')" download aria-label="Export as JSON">JSON</a>
<a :href="url('json')" target="_blank" rel="noopener" aria-label="Export as JSON">JSON</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
+57 -19
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
@@ -10,7 +10,6 @@ import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
@@ -53,11 +52,13 @@ import {
emptyMessage,
exportFilterParams,
hasFilters,
hasTarget,
queryFromRoute,
readSavedViews,
recordKey,
routeQueryFor,
targetDetail,
targetHref,
writeSavedViews,
type AuditQuery,
type AuditRecord,
@@ -87,9 +88,11 @@ const columns: DataTableColumn<AuditRecord>[] = [
const status = ref("");
const liveError = ref("");
const pending = ref<AuditRecord[]>([]);
const tableHost = ref<HTMLElement | null>(null);
let liveTimer: ReturnType<typeof setTimeout> | undefined;
let liveBusy = false;
let liveAgain = false;
let lastToken: string | null = null;
function reload(): void {
void audit.load(query.value);
@@ -104,10 +107,26 @@ onMounted(() => {
if (!accounts.status) void accounts.load();
});
const stopLive = session.subscribe("audit-head", () => {
const stopLive = session.subscribe("audit-head", (data) => {
const token =
typeof (data as { token?: unknown })?.token === "string"
? (data as { token: string }).token
: null;
// The hub republishes the token on its poll; only a new head is a fetch. A
// payload without a token is an older server, so it always refetches.
if (token !== null && token === lastToken) return;
lastToken = token;
clearTimeout(liveTimer);
liveTimer = setTimeout(() => void pullLive(), 400);
});
// A reconnect replays the latest token; forgetting it makes the first frame
// after the connection refetch rather than skip what was missed.
watch(
() => session.connectionRevision,
() => {
lastToken = null;
},
);
onUnmounted(() => {
clearTimeout(liveTimer);
stopLive();
@@ -130,12 +149,15 @@ async function pullLive(): Promise<void> {
pending.value = dedupeRecords([...incoming, ...pending.value]);
status.value = `${pending.value.length} new ${pending.value.length === 1 ? "event" : "events"}`;
} else {
audit.prepend(incoming);
status.value = `${incoming.length} new ${incoming.length === 1 ? "event" : "events"}`;
const merged = dedupeRecords([...incoming, ...pending.value]);
audit.prepend(merged);
pending.value = [];
status.value = `${merged.length} new ${merged.length === 1 ? "event" : "events"}`;
}
} catch (err) {
liveError.value = String((err as Error)?.message || err || "Audit could not refresh.");
status.value = "Audit could not refresh.";
lastToken = null;
} finally {
liveBusy = false;
if (liveAgain) {
@@ -145,13 +167,18 @@ async function pullLive(): Promise<void> {
}
}
function showPending(): void {
const count = pending.value.length;
if (!count) return;
audit.prepend(pending.value);
async function showPending(): Promise<void> {
const held = pending.value;
if (!held.length) return;
audit.prepend(held);
pending.value = [];
status.value = `${count} new ${count === 1 ? "event" : "events"}`;
status.value = `${held.length} new ${held.length === 1 ? "event" : "events"}`;
window.scrollTo({ top: 0 });
await nextTick();
const rows = [...(tableHost.value?.querySelectorAll<HTMLElement>("[data-row-key]") ?? [])];
const first = rows.find((row) => row.dataset.rowKey === recordKey(held[0]));
if (first) first.focus({ preventScroll: true });
else tableHost.value?.focus({ preventScroll: true });
}
function changeFilters(patch: Partial<AuditQuery>): void {
@@ -251,6 +278,14 @@ function askRevert(record: AuditRecord): void {
revertOpen.value = true;
}
function onRevertOpen(open: boolean): void {
revertOpen.value = open;
if (!open) {
revertTarget.value = null;
revertError.value = "";
}
}
async function confirmRevert(): Promise<void> {
const target = revertTarget.value;
if (!target || reverting.value) return;
@@ -271,11 +306,12 @@ async function confirmRevert(): Promise<void> {
return;
}
settings.stageRestore(target.kind, previous.value);
revertTarget.value = null;
revertOpen.value = false;
} catch (err) {
revertError.value = String((err as Error)?.message || err);
} finally {
reverting.value = false;
revertTarget.value = null;
}
}
@@ -358,10 +394,9 @@ async function saveRetention(): Promise<void> {
<AuditFilters :query="query" :facets="facets" @change="changeFilters" />
<p v-if="revertError" class="mb-3 text-sm text-danger" role="alert">{{ revertError }}</p>
<p v-if="liveError" class="mb-3 text-sm text-danger" role="alert">{{ liveError }}</p>
<div class="relative">
<div ref="tableHost" tabindex="-1" class="relative outline-none focus-visible:outline-2 focus-visible:outline-ring">
<div v-if="pending.length" class="sticky top-2 z-20 mb-2 flex justify-center">
<Button size="sm" @click="showPending">{{ pending.length }} new {{ pending.length === 1 ? "event" : "events" }}</Button>
</div>
@@ -382,9 +417,11 @@ async function saveRetention(): Promise<void> {
<Badge v-if="badgeFor(row)" :variant="badgeFor(row)!.variant">{{ badgeFor(row)!.label }}</Badge>
</div>
<p class="mt-0.5 text-xs text-fg-subtle sm:hidden">
<RouterLink v-if="row.target?.href" :to="row.target.href" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target?.label || row.target?.id }}</span>
·
<template v-if="hasTarget(row.target)">
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target.label || row.target.id }}</span>
·
</template>
<span>{{ row.actor.name || row.actor.id }}</span>
·
<Timestamp :at="row.at" />
@@ -392,7 +429,7 @@ async function saveRetention(): Promise<void> {
</div>
</template>
<template #cell-target="{ row }">
<RouterLink v-if="row.target?.href" :to="row.target.href" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target?.label || row.target?.id }}</span>
<span class="block text-xs text-fg-subtle">{{ targetDetail(row.target) }}</span>
</template>
@@ -424,16 +461,17 @@ async function saveRetention(): Promise<void> {
<p class="sr-only" role="status">{{ status }}</p>
<AlertDialog :open="revertOpen" @update:open="(open) => (revertOpen = open)">
<AlertDialog :open="revertOpen" @update:open="onRevertOpen">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Revert this change?</AlertDialogTitle>
<AlertDialogDescription v-if="revertUnsaved">Unsaved changes to this resource will be replaced.</AlertDialogDescription>
<AlertDialogDescription v-else>The previous version opens for review before saving.</AlertDialogDescription>
</AlertDialogHeader>
<p v-if="revertError" class="text-sm text-danger" role="alert">{{ revertError }}</p>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction :disabled="reverting" @click="confirmRevert">Revert</AlertDialogAction>
<Button :disabled="reverting" @click="confirmRevert"><Spinner v-if="reverting" data-icon="inline-start" />Revert</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+45 -9
View File
@@ -36,8 +36,8 @@ export interface AuditDetail {
table?: string;
}
export type AuditCategory = "settings" | "access" | "identity" | "runtime";
export type AuditSeverity = "info" | "warning" | "critical";
export type AuditCategory = "settings" | "access" | "identity" | "runtime" | "automation";
export type AuditSeverity = "info" | "warning" | "error";
export type AuditOutcome = "success" | "denied" | "failure";
export interface AuditRecord {
@@ -270,7 +270,16 @@ export function presetLabel(query: AuditQuery): string {
}
export interface AuditChip {
key: "kind" | "action" | "actor" | "severity" | "target_kind" | "target_id" | "from" | "to";
key:
| "kind"
| "action"
| "actor"
| "severity"
| "outcome"
| "target_kind"
| "target_id"
| "from"
| "to";
value: string;
text: string;
}
@@ -313,6 +322,17 @@ export function filterChips(query: AuditQuery, facets: AuditFacets): AuditChip[]
},
]
: []),
// Denied has its own toggle; any other outcome is reachable only by URL,
// so it gets a chip or it would filter invisibly.
...(query.outcome && query.outcome !== "denied"
? [
{
key: "outcome" as const,
value: query.outcome,
text: `Outcome: ${valueLabel(query.outcome)}`,
},
]
: []),
...(query.target_kind
? [
{
@@ -332,11 +352,12 @@ export function filterChips(query: AuditQuery, facets: AuditFacets): AuditChip[]
export type AuditBadgeVariant = "danger" | "warn" | "info";
/** A textual badge carries severity; colour alone never does. */
/** A textual badge carries severity; colour alone never does. An error is a
* failure of the event whether or not its outcome says success. */
export function badgeFor(record: AuditRecord): { label: string; variant: AuditBadgeVariant } | null {
if (record.outcome === "denied") return { label: "Denied", variant: "danger" };
if (record.outcome === "failure") return { label: "Failed", variant: "danger" };
if (record.severity === "critical") return { label: "Critical", variant: "danger" };
if (record.outcome === "failure" || record.severity === "error")
return { label: "Failed", variant: "danger" };
if (record.severity === "warning") return { label: "Warning", variant: "warn" };
return null;
}
@@ -366,7 +387,7 @@ function humanise(field: string): string {
export function metadataRows(record: AuditRecord): AuditMetadataRow[] {
const detail = record.detail ?? {};
const rows: AuditMetadataRow[] = [];
if (!detail.fields?.length) {
if (!detail.fields?.length && hasTarget(record.target)) {
rows.push({
key: "target",
label: "Target",
@@ -387,7 +408,7 @@ export function metadataRows(record: AuditRecord): AuditMetadataRow[] {
}
if (detail.table) rows.push({ key: "table", label: "Table", value: detail.table, mono: true });
if (detail.source) rows.push({ key: "source", label: "Source", value: detail.source, mono: true });
if (detail.version != null)
if ((detail.version ?? 0) > 0)
rows.push({ key: "version", label: "Version", value: String(detail.version), mono: true });
if (detail.request_id)
rows.push({ key: "request", label: "Request", value: detail.request_id, mono: true });
@@ -398,11 +419,26 @@ export function recordKey(record: AuditRecord): string {
return record.id;
}
/** A target exists when it names anything; an event may have none. */
export function hasTarget(target?: AuditTarget): boolean {
return !!target && !!(target.kind || target.id);
}
/** The dashboard route for a target. A task route is built from its id, so an
* older server href cannot send the operator to the wrong page. */
export function targetHref(target?: AuditTarget): string {
if (target?.kind === "task" && target.id)
return `/tasks/${encodeURIComponent(target.id)}`;
return target?.href ?? "";
}
/** The target's own id when it adds anything beyond the label: the settings
* resource kind, a record key, or a task id. */
export function targetDetail(target?: AuditTarget): string {
if (!target?.id) return "";
return target.id === target.label ? "" : target.id;
const label = target.label ?? "";
if (label && (label === target.id || label.endsWith(target.id))) return "";
return target.id;
}
/** Keeps the first occurrence, so a live page and an older page cannot show