From b9c94f6f63b24a24dc71807a1f358b7ea1b5271e Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sat, 22 Aug 2026 07:22:12 +0300 Subject: [PATCH 1/2] =?UTF-8?q?fix(webui):=20quiet=20the=20Activity=20Log?= =?UTF-8?q?=20=E2=80=94=20de-colour=20success,=20compact=20header,=20real?= =?UTF-8?q?=20Intent=20column?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Activity Log spent its loudest signals on its most common outcome. Success rows carried a green pill, five stat cards plus a permanently open nine-control filter grid pushed the first row below the fold, "code_execution" was printed twice on the same line, and the Intent column was a 52px slot holding a coloured `read` pill whose glyph overflowed it โ€” with the declared REASON hidden in a tooltip. Semantic colour is now reserved for states that need attention: - Status renders through a new pure `statusPresentation(status)` helper โ€” success is plain muted text (no pill, no green), error keeps a red pill, blocked an amber one, rejected and any other oddity a neutral grey chip. Applied to the table column, the detail drawer and ActivityWidget from one shared mapping. The Success and Rejected KPI values lost their colour too. - The `code_execution` marker appears once per row: the Type-column badge is dropped when the Details column already prints the same word (a quiet ๐Ÿงฉ glyph sits beside that text instead), and the child badge is ghost/muted context rather than an accent alert. - The page opens on ONE compact strip: "54 calls ยท 6 errors ยท 1 blocked" (zeros omitted, only error/blocked coloured, each segment still driving the Status filter per #436), a Filters toggle with an active-filter count badge, Export, and the active filters as dismissable chips โ€” visible even collapsed. The stat cards and the filter grid render only when expanded; the choice is persisted in localStorage behind try/catch and defaults to collapsed. - Intent is a real column: an operation glyph followed by the reason on one line, ellipsised, with the full text in `title`. No colour pill, no clipped icon; a muted dash when nothing was declared. Parent/child navigation, every existing filter and SSE live updates are unchanged. New pure helpers (`statusPresentation`, `intentPresentation`, `compactSummaryParts`, `activeFilterChips`, `activityDetailsText`, `showParentBadgeInTypeColumn`) live in utils/activity.ts, which also absorbed the type/status/intent maps that Activity.vue and ActivityWidget.vue had been duplicating locally. Co-Authored-By: Claude Fable 5 --- frontend/src/components/ActivityWidget.vue | 35 +- frontend/src/utils/activity.ts | 364 ++++++++++++++ frontend/src/views/Activity.vue | 461 ++++++++++++------ .../tests/unit/activity-compact-view.spec.ts | 252 ++++++++++ frontend/tests/unit/activity.spec.ts | 227 +++++++++ 5 files changed, 1160 insertions(+), 179 deletions(-) create mode 100644 frontend/tests/unit/activity-compact-view.spec.ts diff --git a/frontend/src/components/ActivityWidget.vue b/frontend/src/components/ActivityWidget.vue index bafcfad84..e6b548661 100644 --- a/frontend/src/components/ActivityWidget.vue +++ b/frontend/src/components/ActivityWidget.vue @@ -19,7 +19,8 @@
Success
-
{{ summary.success_count }}
+ +
{{ summary.success_count }}
Errors
@@ -67,10 +68,11 @@
{{ formatRelativeTime(activity.timestamp) }}
+ โ†ณ via code_execution @@ -78,12 +80,13 @@
-
+ - {{ activity.status }} -
+ {{ statusPresentation(activity.status).label }} + @@ -95,7 +98,12 @@ import { ref, onMounted } from 'vue' import { useRouter } from 'vue-router' import api from '@/services/api' import type { ActivityRecord, ActivitySummaryResponse } from '@/types/api' -import { formatPreflightSummary, isChildCall, isPreflightActivity } from '@/utils/activity' +import { + formatPreflightSummary, + isChildCall, + isPreflightActivity, + statusPresentation, +} from '@/utils/activity' const router = useRouter() @@ -160,17 +168,6 @@ const getTypeIcon = (type: string): string => { return typeIcons[type] || '๐Ÿ“‹' } -const getStatusBadgeClass = (status: string): string => { - const statusClasses: Record = { - 'success': 'badge-success', - 'error': 'badge-error', - 'blocked': 'badge-warning', - // Spec 093: shed by a concurrency limit (backpressure, not an upstream fault). - 'rejected': 'badge-info' - } - return statusClasses[status] || 'badge-ghost' -} - // Lifecycle onMounted(() => { loadData() diff --git a/frontend/src/utils/activity.ts b/frontend/src/utils/activity.ts index b1b2c3677..518b4e35f 100644 --- a/frontend/src/utils/activity.ts +++ b/frontend/src/utils/activity.ts @@ -6,6 +6,10 @@ // Activity type labels const typeLabels: Record = { 'tool_call': 'Tool Call', + 'system_start': 'System Start', + 'system_stop': 'System Stop', + 'internal_tool_call': 'Internal Tool Call', + 'config_change': 'Config Change', 'policy_decision': 'Policy Decision', 'quarantine_change': 'Quarantine Change', 'server_change': 'Server Change', @@ -16,6 +20,10 @@ const typeLabels: Record = { // Activity type icons const typeIcons: Record = { 'tool_call': '๐Ÿ”ง', + 'system_start': '๐Ÿš€', + 'system_stop': '๐Ÿ›‘', + 'internal_tool_call': 'โš™๏ธ', + 'config_change': 'โšก', 'policy_decision': '๐Ÿ›ก๏ธ', 'quarantine_change': 'โš ๏ธ', 'server_change': '๐Ÿ”„', @@ -77,11 +85,88 @@ export const formatStatus = (status: string): string => { /** * Get badge CSS class for status + * + * @deprecated Prefer {@link statusPresentation}, which also decides whether the + * status deserves a pill at all. Kept for the few places that still want a raw + * DaisyUI badge modifier. */ export const getStatusBadgeClass = (status: string): string => { return statusClasses[status] || 'badge-ghost' } +// --- status presentation ---------------------------------------------------- +// +// The activity table is SCANNED, not read. Success is the norm โ€” roughly 90% of +// rows โ€” so painting it green makes the whole column shout and buries the two +// rows that actually need a human. Semantic colour is therefore spent only on +// states that need attention: +// +// success plain muted text, no pill ("this is fine, move on") +// error red pill (upstream fault) +// blocked amber pill (policy stopped it) +// rejected / other neutral grey pill (odd, but not an alarm) +// +// Both the table column and the dashboard widget render from this one mapping so +// they cannot drift apart. + +/** How loudly a status is allowed to speak. */ +export type StatusTone = 'muted' | 'error' | 'warning' | 'neutral' + +export interface StatusPresentation { + /** Human label, e.g. "Success". Unknown statuses keep their raw value. */ + label: string + tone: StatusTone + /** False = render as plain text (success only); true = render as a pill. */ + pill: boolean + /** Full class list for the rendered element, pill or text. */ + className: string +} + +const statusPresentations: Record = { + // No pill, no colour: the default outcome must not compete for attention. + success: { + label: 'Success', + tone: 'muted', + pill: false, + className: 'text-sm text-base-content/60', + }, + error: { + label: 'Error', + tone: 'error', + pill: true, + className: 'badge badge-sm badge-error', + }, + blocked: { + label: 'Blocked', + tone: 'warning', + pill: true, + className: 'badge badge-sm badge-warning', + }, + // Spec 093: shed by a concurrency limit. Worth noticing, not worth alarming โ€” + // badge-ghost is a neutral chip that reads in both light and dark themes. + rejected: { + label: 'Rejected', + tone: 'neutral', + pill: true, + className: 'badge badge-sm badge-ghost', + }, +} + +/** + * Pure status -> presentation mapping. Anything unrecognised is an oddity, not + * an alarm: neutral grey pill carrying the raw status value. + */ +export const statusPresentation = (status: string): StatusPresentation => { + const known = statusPresentations[status] + if (known) return known + return { + label: statusLabels[status] || status, + tone: 'neutral', + pill: true, + className: 'badge badge-sm badge-ghost', + } +} + /** * Get icon for intent operation type */ @@ -91,11 +176,66 @@ export const getIntentIcon = (operationType: string): string => { /** * Get badge CSS class for intent operation type + * + * @deprecated The table renders intent through {@link intentPresentation} (glyph + * + reason, no coloured pill). Still used by the detail drawer, where a single + * badge has room to be explicit. */ export const getIntentBadgeClass = (operationType: string): string => { return intentClasses[operationType] || 'badge-ghost' } +// --- intent presentation ---------------------------------------------------- +// +// Spec 018/024 intent: {operation_type, reason, data_sensitivity}. The old table +// cell rendered a coloured `read` pill with the glyph crammed inside it (the +// glyph overflowed the badge box) and hid the REASON โ€” the only part an operator +// actually wants โ€” behind a tooltip. The reason is the payload; the operation is +// a one-character prefix. + +/** The intent object as it is stored on `metadata.intent`. */ +export interface ActivityIntent { + operation_type?: string + reason?: string + data_sensitivity?: string +} + +export interface IntentPresentation { + /** False when the record declared no operation type โ€” render a muted dash. */ + present: boolean + /** Operation glyph: book / pencil / warning. Empty when absent. */ + icon: string + /** Operation type, e.g. "read". Exposed for screen readers, not painted. */ + label: string + /** Declared reason, single line in the cell. Empty when none was given. */ + reason: string + /** Full hover text (`title`), so a truncated reason is still readable. */ + title: string +} + +const EMPTY_INTENT: IntentPresentation = { present: false, icon: '', label: '', reason: '', title: '' } + +/** + * Pure intent -> presentation mapping: glyph + reason text, never a colour pill. + * A missing operation type means "no intent declared", which the caller renders + * as a muted dash rather than a `โ“` chip. + */ +export const intentPresentation = (intent?: ActivityIntent | null): IntentPresentation => { + const operationType = intent?.operation_type + if (!operationType) return EMPTY_INTENT + + const reason = (intent?.reason ?? '').trim() + return { + present: true, + icon: getIntentIcon(operationType), + label: operationType, + reason, + // Hover shows the operation too โ€” the glyph alone is ambiguous, and the + // reason may be ellipsised in the cell. + title: reason ? `${operationType} โ€” ${reason}` : operationType, + } +} + // --- Spec 098: preflight activity records ----------------------------------- // // A preflight record is set-scoped, not server-scoped: `server_name` and @@ -164,6 +304,230 @@ export const isCodeExecutionActivity = (a?: ActivityLinkFields | null): boolean /** True for a sub-call: a record that names the parent it was dispatched from. */ export const isChildCall = (a?: ActivityLinkFields | null): boolean => Boolean(a?.parent_id) +/** + * What the table's Details column will print for a record. Extracted so the Type + * column can tell whether its `code_execution` marker would be a second copy of + * the same six characters on the same row. + */ +export const activityDetailsText = ( + a?: (ActivityLinkFields & { metadata?: Record | null }) | null +): string => { + if (!a) return '' + if (a.tool_name) return a.tool_name + if (isPreflightActivity(a as { type?: string })) { + const summary = formatPreflightSummary(a.metadata) + if (summary) return summary + } + const action = a.metadata?.action + return action ? String(action) : '' +} + +/** + * True when the Type column should still carry the `code_execution` badge: the + * record IS a sandbox parent and the Details column is not already saying so. + * When this is false the row shows a single quiet puzzle glyph beside the + * Details text instead โ€” one marker per row, never the same word twice. + */ +export const showParentBadgeInTypeColumn = ( + a?: (ActivityLinkFields & { metadata?: Record | null }) | null +): boolean => { + if (!isCodeExecutionActivity(a)) return false + return !activityDetailsText(a).includes('code_execution') +} + +/** Last 8 chars of a correlation id โ€” enough to recognise, short enough to fit. */ +export const shortId = (id: string): string => (id.length > 8 ? `โ€ฆ${id.slice(-8)}` : id) + +// --- compact header: counts strip + active-filter chips --------------------- +// +// Five stat cards plus an always-open nine-control filter grid pushed the first +// activity row below the fold. The default view is now one line: the total plus +// only the counts that want attention, and a Filters button carrying a count of +// what is currently narrowing the list. The cards and the controls still exist โ€” +// they just wait until they are asked for. + +/** One segment of the compact counts strip. */ +export interface CompactSummaryPart { + key: 'total' | 'error' | 'blocked' | 'rejected' + label: string + tone: StatusTone + /** Status value this segment filters to; '' clears the status filter. */ + status: string +} + +interface ActivitySummaryCounts { + total_count?: number + error_count?: number + blocked_count?: number + rejected_count?: number +} + +const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}` + +/** + * Compact counts strip, e.g. "54 calls ยท 6 errors ยท 1 blocked". The total is + * always present and muted; a zero attention count is omitted entirely rather + * than rendered as a reassuring "0 errors" that costs a line of scanning. + */ +export const compactSummaryParts = ( + summary?: ActivitySummaryCounts | null +): CompactSummaryPart[] => { + if (!summary) return [] + + const parts: CompactSummaryPart[] = [ + { + key: 'total', + label: plural(summary.total_count ?? 0, 'call', 'calls'), + tone: 'muted', + status: '', + }, + ] + + if ((summary.error_count ?? 0) > 0) { + parts.push({ + key: 'error', + label: plural(summary.error_count as number, 'error', 'errors'), + tone: 'error', + status: 'error', + }) + } + if ((summary.blocked_count ?? 0) > 0) { + parts.push({ + key: 'blocked', + label: `${summary.blocked_count} blocked`, + tone: 'warning', + status: 'blocked', + }) + } + if ((summary.rejected_count ?? 0) > 0) { + parts.push({ + key: 'rejected', + label: `${summary.rejected_count} rejected`, + tone: 'neutral', + status: 'rejected', + }) + } + + return parts +} + +/** Every filter the Activity Log can apply, in one plain object. */ +export interface ActivityFilterState { + types?: string[] + parentId?: string + server?: string + status?: string + authType?: string + agentName?: string + sensitiveData?: string + severity?: string + session?: string + /** Resolved display label for `session`; falls back to a shortened id. */ + sessionLabel?: string + startDate?: string + endDate?: string +} + +/** A dismissable chip in the compact strip. `kind` selects the clear action. */ +export interface ActiveFilterChip { + kind: + | 'type' + | 'parent' + | 'server' + | 'status' + | 'auth' + | 'agent' + | 'sensitive' + | 'severity' + | 'session' + | 'start' + | 'end' + /** Unique within one render, so it can key a v-for. */ + key: string + label: string + /** Payload the clear action needs (the type value for a type chip). */ + value?: string + title?: string +} + +const localDateLabel = (value: string): string => { + const date = new Date(value) + return Number.isNaN(date.getTime()) ? value : date.toLocaleString() +} + +/** + * The active filters, as chips. Pure and order-stable: types first (they are + * multi-select), then the sub-call view, then the single-value filters in the + * order the expanded controls present them. + */ +export const activeFilterChips = (state: ActivityFilterState): ActiveFilterChip[] => { + const chips: ActiveFilterChip[] = [] + + for (const type of state.types ?? []) { + chips.push({ + kind: 'type', + key: `type:${type}`, + label: `${getTypeIcon(type)} ${formatType(type)}`, + value: type, + }) + } + + if (state.parentId) { + chips.push({ + kind: 'parent', + key: 'parent', + label: `โ†ณ Sub-calls of ${shortId(state.parentId)}`, + value: state.parentId, + title: `Sub-calls of code_execution ${state.parentId}`, + }) + } + if (state.server) { + chips.push({ kind: 'server', key: 'server', label: `Server: ${state.server}` }) + } + if (state.status) { + chips.push({ kind: 'status', key: 'status', label: `Status: ${state.status}` }) + } + if (state.authType) { + chips.push({ + kind: 'auth', + key: 'auth', + label: `Auth: ${state.authType === 'admin' ? '๐Ÿ”‘ Admin' : '๐Ÿค– Agent'}`, + }) + } + if (state.agentName) { + chips.push({ kind: 'agent', key: 'agent', label: `Agent: ${state.agentName}` }) + } + if (state.sensitiveData) { + chips.push({ + kind: 'sensitive', + key: 'sensitive', + label: `Sensitive: ${state.sensitiveData === 'true' ? 'โš ๏ธ Detected' : 'Clean'}`, + }) + } + if (state.severity) { + chips.push({ kind: 'severity', key: 'severity', label: `Severity: ${state.severity}` }) + } + if (state.session) { + chips.push({ + kind: 'session', + key: 'session', + label: `Session: ${state.sessionLabel || shortId(state.session)}`, + }) + } + if (state.startDate) { + chips.push({ kind: 'start', key: 'start', label: `From: ${localDateLabel(state.startDate)}` }) + } + if (state.endDate) { + chips.push({ kind: 'end', key: 'end', label: `To: ${localDateLabel(state.endDate)}` }) + } + + return chips +} + +/** Badge count for the Filters toggle: how many filters are narrowing the list. */ +export const activeFilterCount = (state: ActivityFilterState): number => + activeFilterChips(state).length + /** * Read `metadata.reasons` into a DETERMINISTIC order: most frequent first, ties * broken alphabetically. Object key order is insertion-dependent, so without the diff --git a/frontend/src/views/Activity.vue b/frontend/src/views/Activity.vue index c860faff9..d4b9cfdb7 100644 --- a/frontend/src/views/Activity.vue +++ b/frontend/src/views/Activity.vue @@ -30,8 +30,115 @@ + +
+
+
+ +
+ +
+ +
+ + + + + + +
+ + +
+ Filters: + + +
+
+
+ -
+
- -
+ +
@@ -254,63 +363,6 @@ > Clear Filters - - -
- - - -
- - -
- Active filters: - - {{ getTypeIcon(type) }} {{ formatType(type) }} - - - - - - - โ†ณ Sub-calls of {{ shortId(filterParentId) }} - - - - - Server: {{ filterServer }} - Status: {{ filterStatus }} - Auth: {{ filterAuthType === 'admin' ? '๐Ÿ”‘ Admin' : '๐Ÿค– Agent' }} - Agent: {{ filterAgentName }} - - Sensitive: {{ filterSensitiveData === 'true' ? 'โš ๏ธ Detected' : 'Clean' }} - - Severity: {{ filterSeverity }} - Session: {{ getSessionLabel(filterSession) }} - From: {{ new Date(filterStartDate).toLocaleString() }} - To: {{ new Date(filterEndDate).toLocaleString() }}
@@ -357,7 +409,8 @@ Details Sensitive - Intent + + Intent Status {{ getSortIndicator('status') }} @@ -389,20 +442,24 @@ โ†ณ via code_execution ๐Ÿงฉ code_execution @@ -421,8 +478,21 @@ - -
- +
+ + + ๐Ÿงฉ + + {{ activity.tool_name }} - + +
- - {{ getIntentIcon(activity.metadata.intent.operation_type) }} - {{ activity.metadata.intent.operation_type }} + + {{ intentOf(activity).label }} + + {{ intentOf(activity).reason }}
- + -
- {{ formatStatus(activity.status) }} -
+ {{ statusPresentation(activity.status).label }} + @@ -570,12 +655,15 @@
- +
Status: -
- {{ formatStatus(selectedActivity.status) }} -
+ + {{ statusPresentation(selectedActivity.status).label }} +
@@ -856,14 +944,26 @@ import { // Spec 098: preflight records carry their verdict in metadata; the renderers // are shared (and unit-tested) rather than re-derived in the template. import { + activeFilterChips, + compactSummaryParts, formatPreflightSummary, + formatType, + getIntentBadgeClass, + getIntentIcon, getPreflightVerdictBadgeClass, + getTypeIcon, + intentPresentation, isChildCall, isCodeExecutionActivity, isPreflightActivity, preflightIdsCount, preflightPerTool, preflightReasonRollup, + showParentBadgeInTypeColumn, + statusPresentation, + type ActiveFilterChip, + type CompactSummaryPart, + type StatusTone, } from '@/utils/activity' import JsonViewer from '@/components/JsonViewer.vue' @@ -1107,6 +1207,116 @@ const hasActiveFilters = computed(() => { return selectedTypes.value.length > 0 || filterServer.value || filterSession.value || filterStatus.value || filterSensitiveData.value || filterSeverity.value || filterAuthType.value || filterAgentName.value || filterStartDate.value || filterEndDate.value || filterParentId.value }) +// --- compact header --------------------------------------------------------- + +/** + * Whether the stat cards + full filter grid are shown. Persisted per browser so + * an operator who wants the controls open keeps them open, while a first visit + * lands on the compact strip. localStorage can throw outright (private windows, + * blocked site data), so every touch is guarded and falls back to collapsed. + */ +const FILTER_PANEL_STORAGE_KEY = 'mcpproxy.activity.filtersExpanded' + +const readFilterPanelPref = (): boolean => { + try { + return window.localStorage.getItem(FILTER_PANEL_STORAGE_KEY) === 'true' + } catch { + return false + } +} + +const showFilterPanel = ref(readFilterPanelPref()) + +watch(showFilterPanel, expanded => { + try { + window.localStorage.setItem(FILTER_PANEL_STORAGE_KEY, expanded ? 'true' : 'false') + } catch { + // Preference is a convenience; never let a storage failure break the page. + } +}) + +/** "54 calls ยท 6 errors ยท 1 blocked" โ€” zeros omitted. */ +const summaryParts = computed(() => compactSummaryParts(summary.value)) + +/** Only error/blocked spend colour; the total and oddities stay quiet. */ +const summaryToneClass = (tone: StatusTone): string => { + switch (tone) { + case 'error': + return 'text-error font-medium' + case 'warning': + return 'text-warning font-medium' + case 'neutral': + return 'text-base-content/70' + default: + return 'text-base-content/60' + } +} + +/** Clicking a count drives the Status filter (issue #436, kept from the cards). */ +const applySummaryFilter = (part: CompactSummaryPart) => { + filterStatus.value = filterStatus.value === part.status ? '' : part.status +} + +/** Active filters as dismissable chips โ€” visible whether or not the grid is. */ +const activeChips = computed(() => + activeFilterChips({ + types: selectedTypes.value, + parentId: filterParentId.value, + server: filterServer.value, + status: filterStatus.value, + authType: filterAuthType.value, + agentName: filterAgentName.value, + sensitiveData: filterSensitiveData.value, + severity: filterSeverity.value, + session: filterSession.value, + sessionLabel: filterSession.value ? getSessionLabel(filterSession.value) : undefined, + startDate: filterStartDate.value, + endDate: filterEndDate.value, + }) +) + +/** The sub-call chip keeps its own hook โ€” it is the code_execution exit door. */ +const chipTestId = (chip: ActiveFilterChip): string => + chip.kind === 'parent' ? 'activity-parent-filter-chip' : `activity-filter-chip-${chip.kind}` + +const clearChip = (chip: ActiveFilterChip) => { + switch (chip.kind) { + case 'type': + if (chip.value) toggleTypeFilter(chip.value) + break + case 'parent': + void clearParentFilter() + break + case 'server': + filterServer.value = '' + break + case 'status': + filterStatus.value = '' + break + case 'auth': + filterAuthType.value = '' + break + case 'agent': + filterAgentName.value = '' + break + case 'sensitive': + filterSensitiveData.value = '' + break + case 'severity': + filterSeverity.value = '' + break + case 'session': + filterSession.value = '' + break + case 'start': + filterStartDate.value = '' + break + case 'end': + filterEndDate.value = '' + break + } +} + const filteredActivities = computed(() => { let result = activities.value @@ -1247,9 +1457,6 @@ const clearFilters = () => { if (hadParentFilter) void loadActivities() } -/** Last 8 chars of a correlation id โ€” enough to recognise, short enough to fit. */ -const shortId = (id: string): string => (id.length > 8 ? `โ€ฆ${id.slice(-8)}` : id) - /** Sub-calls of this run among the rows we hold. */ const subCallCount = (parent: ActivityRecord): number => { if (!parent.request_id) return 0 @@ -1435,60 +1642,8 @@ const formatRelativeTime = (timestamp: string): string => { return `${Math.floor(diff / 86400000)}d ago` } -const formatType = (type: string): string => { - // Spec 024: Include new activity types - const typeLabels: Record = { - 'tool_call': 'Tool Call', - 'system_start': 'System Start', - 'system_stop': 'System Stop', - 'internal_tool_call': 'Internal Tool Call', - 'config_change': 'Config Change', - 'policy_decision': 'Policy Decision', - 'quarantine_change': 'Quarantine Change', - 'server_change': 'Server Change', - // Spec 098 - 'preflight': 'Preflight' - } - return typeLabels[type] || type -} - -const getTypeIcon = (type: string): string => { - // Spec 024: Include new activity types - const typeIcons: Record = { - 'tool_call': '๐Ÿ”ง', - 'system_start': '๐Ÿš€', - 'system_stop': '๐Ÿ›‘', - 'internal_tool_call': 'โš™๏ธ', - 'config_change': 'โšก', - 'policy_decision': '๐Ÿ›ก๏ธ', - 'quarantine_change': 'โš ๏ธ', - 'server_change': '๐Ÿ”„', - // Spec 098 - 'preflight': '๐Ÿ›ซ' - } - return typeIcons[type] || '๐Ÿ“‹' -} - -const formatStatus = (status: string): string => { - const statusLabels: Record = { - 'success': 'Success', - 'error': 'Error', - 'blocked': 'Blocked', - 'rejected': 'Rejected' - } - return statusLabels[status] || status -} - -const getStatusBadgeClass = (status: string): string => { - const statusClasses: Record = { - 'success': 'badge-success', - 'error': 'badge-error', - 'blocked': 'badge-warning', - // Spec 093: shed by a concurrency limit (backpressure, not an upstream fault). - 'rejected': 'badge-info' - } - return statusClasses[status] || 'badge-ghost' -} +// Type / status / intent renderers are imported from @/utils/activity so the +// table, the dashboard widget and the unit tests share ONE mapping. const formatDuration = (ms: number): string => { if (ms < 1000) return `${Math.round(ms)}ms` @@ -1526,23 +1681,9 @@ const getSeverityBadgeClass = (severity?: string): string => { return classes[severity || ''] || 'badge-warning' } -const getIntentIcon = (operationType: string): string => { - const icons: Record = { - 'read': '๐Ÿ“–', - 'write': 'โœ๏ธ', - 'destructive': 'โš ๏ธ' - } - return icons[operationType] || 'โ“' -} - -const getIntentBadgeClass = (operationType: string): string => { - const classes: Record = { - 'read': 'badge-info', - 'write': 'badge-warning', - 'destructive': 'badge-error' - } - return classes[operationType] || 'badge-ghost' -} +/** Intent as the table renders it: glyph + reason, no coloured pill. */ +const intentOf = (activity: ActivityRecord) => + intentPresentation(activity.metadata?.intent as Parameters[0]) // Check if there's additional metadata beyond what we show in dedicated sections const hasAdditionalMetadata = (activity: ActivityRecord): boolean => { diff --git a/frontend/tests/unit/activity-compact-view.spec.ts b/frontend/tests/unit/activity-compact-view.spec.ts new file mode 100644 index 000000000..b43a1e21a --- /dev/null +++ b/frontend/tests/unit/activity-compact-view.spec.ts @@ -0,0 +1,252 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { mount, flushPromises } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { createRouter, createWebHistory } from 'vue-router' + +// Activity Log density (user feedback): five stat cards plus a permanently open +// nine-control filter grid ate half the viewport before the first row. The page +// now opens on ONE compact strip โ€” total + non-zero attention counts, a Filters +// toggle carrying a count badge, and the active-filter chips. The cards and the +// controls are still there, one click away, and the choice is remembered. +// +// The same pass de-coloured success (plain muted text, no pill) and removed the +// duplicated "code_execution" that appeared in Type AND Details on one row. + +const PARENT = { + id: 'act-parent', + type: 'internal_tool_call', + status: 'success', + timestamp: '2026-08-21T10:00:00Z', + tool_name: 'code_execution', + request_id: 'req-parent-abcdefgh', + duration_ms: 900, + metadata: { internal_tool_name: 'code_execution' }, +} + +const OK_CALL = { + id: 'act-ok', + type: 'tool_call', + status: 'success', + timestamp: '2026-08-21T09:59:00Z', + server_name: 'github', + tool_name: 'list_repos', + request_id: 'req-ok', + duration_ms: 40, + metadata: { intent: { operation_type: 'read', reason: 'enumerate repositories for the release notes' } }, +} + +const FAILED_CALL = { + id: 'act-bad', + type: 'tool_call', + status: 'error', + timestamp: '2026-08-21T09:58:00Z', + server_name: 'slack', + tool_name: 'post_message', + request_id: 'req-bad', + duration_ms: 80, + metadata: { intent: { operation_type: 'write' } }, +} + +vi.mock('@/services/api', () => { + const ok = (data: unknown) => Promise.resolve({ success: true, data }) + return { + default: { + getActivities: vi.fn(() => { + const activities = [PARENT, OK_CALL, FAILED_CALL] + return ok({ activities, total: activities.length, limit: 200, offset: 0 }) + }), + getActivitySummary: vi.fn(() => + ok({ + period: '24h', + total_count: 54, + success_count: 47, + error_count: 6, + blocked_count: 1, + rejected_count: 0, + }) + ), + getSessions: vi.fn(() => ok({ sessions: [] })), + getActivityExportUrl: vi.fn(() => 'http://localhost/api/v1/activity/export?format=json'), + }, + } +}) + +async function mountActivity() { + const Activity = (await import('@/views/Activity.vue')).default + const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/activity', component: { template: '
' } }, + { path: '/servers/:serverName', component: { template: '
' } }, + ], + }) + await router.push('/activity') + await router.isReady() + const wrapper = mount(Activity, { global: { plugins: [createPinia(), router] } }) + await flushPromises() + return wrapper +} + +type Wrapper = Awaited> + +const rows = (wrapper: Wrapper) => wrapper.findAll('[data-test="activity-row"]') +const rowFor = (wrapper: Wrapper, text: string) => rows(wrapper).find(r => r.text().includes(text))! + +describe('Activity Log โ€” compact header', () => { + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + window.localStorage.clear() + }) + + it('opens collapsed: one counts strip, no stat cards, no filter grid', async () => { + const wrapper = await mountActivity() + + const strip = wrapper.find('[data-test="activity-compact-summary"]') + expect(strip.exists()).toBe(true) + expect(strip.text()).toContain('54 calls') + expect(strip.text()).toContain('6 errors') + expect(strip.text()).toContain('1 blocked') + // Zero rejected never earns a segment. + expect(strip.text()).not.toContain('rejected') + + expect(wrapper.find('[data-test="kpi-card-total"]').exists()).toBe(false) + expect(wrapper.find('[data-test="activity-filter-panel"]').exists()).toBe(false) + }) + + it('colours only the attention counts', async () => { + const wrapper = await mountActivity() + + expect(wrapper.find('[data-test="activity-compact-total"]').classes().join(' ')).not.toMatch(/text-(error|warning|success)/) + expect(wrapper.find('[data-test="activity-compact-error"]').classes()).toContain('text-error') + expect(wrapper.find('[data-test="activity-compact-blocked"]').classes()).toContain('text-warning') + }) + + it('a count segment drives the Status filter, and clicking it again clears it', async () => { + const wrapper = await mountActivity() + + await wrapper.find('[data-test="activity-compact-error"]').trigger('click') + await flushPromises() + expect(rows(wrapper)).toHaveLength(1) + expect(wrapper.find('[data-test="activity-filter-chip-status"]').text()).toContain('Status: error') + + await wrapper.find('[data-test="activity-compact-error"]').trigger('click') + await flushPromises() + expect(rows(wrapper)).toHaveLength(3) + }) + + it('reveals the stat cards and the filter grid on toggle, and persists the choice', async () => { + const wrapper = await mountActivity() + + await wrapper.find('[data-test="activity-filters-toggle"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-test="kpi-card-total"]').exists()).toBe(true) + expect(wrapper.find('[data-test="activity-filter-panel"]').exists()).toBe(true) + expect(window.localStorage.getItem('mcpproxy.activity.filtersExpanded')).toBe('true') + + // A fresh mount honours the stored preference. + const reopened = await mountActivity() + expect(reopened.find('[data-test="activity-filter-panel"]').exists()).toBe(true) + }) + + it('survives a localStorage that throws (private window / blocked site data)', async () => { + // Scoped to OUR key: the shared system store touches localStorage too and is + // not what this test is about. + const KEY = 'mcpproxy.activity.filtersExpanded' + const realGet = Storage.prototype.getItem + const realSet = Storage.prototype.setItem + const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(function (this: Storage, key: string) { + if (key === KEY) throw new Error('SecurityError') + return realGet.call(this, key) + }) + const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (this: Storage, key: string, value: string) { + if (key === KEY) throw new Error('SecurityError') + return realSet.call(this, key, value) + }) + + try { + const wrapper = await mountActivity() + // Defaults to collapsed rather than blowing up the page. + expect(wrapper.find('[data-test="activity-filter-panel"]').exists()).toBe(false) + await wrapper.find('[data-test="activity-filters-toggle"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-test="activity-filter-panel"]').exists()).toBe(true) + } finally { + getItem.mockRestore() + setItem.mockRestore() + } + }) + + it('shows active filters as dismissable chips with a count badge, even collapsed', async () => { + const wrapper = await mountActivity() + + expect(wrapper.find('[data-test="activity-active-filters"]').exists()).toBe(false) + expect(wrapper.find('[data-test="activity-filters-count"]').exists()).toBe(false) + + await wrapper.find('[data-test="activity-compact-blocked"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-test="activity-filter-panel"]').exists()).toBe(false) + expect(wrapper.find('[data-test="activity-active-filters"]').exists()).toBe(true) + expect(wrapper.find('[data-test="activity-filters-count"]').text()).toBe('1') + + await wrapper.find('[data-test="activity-filter-chip-status"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-test="activity-active-filters"]').exists()).toBe(false) + }) +}) + +describe('Activity Log โ€” row treatment', () => { + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + window.localStorage.clear() + }) + + it('renders success as plain muted text and error as a red pill', async () => { + const wrapper = await mountActivity() + + const okStatus = rowFor(wrapper, 'list_repos').find('[data-test="activity-status"]') + expect(okStatus.text()).toBe('Success') + expect(okStatus.classes().join(' ')).not.toContain('badge') + expect(okStatus.classes().join(' ')).not.toContain('success') + + const badStatus = rowFor(wrapper, 'post_message').find('[data-test="activity-status"]') + expect(badStatus.text()).toBe('Error') + expect(badStatus.classes()).toContain('badge-error') + }) + + it('says code_execution once on the parent row, not twice', async () => { + const wrapper = await mountActivity() + + const parentRow = rowFor(wrapper, 'code_execution') + const occurrences = parentRow.text().split('code_execution').length - 1 + expect(occurrences).toBe(1) + + // The marker survives as a quiet glyph beside the Details text. + const marker = parentRow.find('[data-test="activity-parent-badge"]') + expect(marker.exists()).toBe(true) + expect(marker.text()).toBe('๐Ÿงฉ') + expect(marker.classes().join(' ')).not.toContain('badge-accent') + }) + + it('shows the intent reason inline, glyph first, no coloured pill', async () => { + const wrapper = await mountActivity() + + const intent = rowFor(wrapper, 'list_repos').find('[data-test="activity-intent"]') + expect(intent.exists()).toBe(true) + expect(intent.attributes('title')).toBe('read โ€” enumerate repositories for the release notes') + expect(intent.text()).toContain('enumerate repositories for the release notes') + expect(intent.classes().join(' ')).not.toContain('badge') + expect(intent.find('[data-test="activity-intent-reason"]').classes()).toContain('truncate') + + // Declared operation with no reason: glyph only, no dangling text node. + const noReason = rowFor(wrapper, 'post_message').find('[data-test="activity-intent"]') + expect(noReason.attributes('title')).toBe('write') + expect(noReason.find('[data-test="activity-intent-reason"]').exists()).toBe(false) + + // No intent at all: a muted dash, not a "โ“" chip. + expect(rowFor(wrapper, 'code_execution').find('[data-test="activity-intent"]').exists()).toBe(false) + }) +}) diff --git a/frontend/tests/unit/activity.spec.ts b/frontend/tests/unit/activity.spec.ts index bd0dc6aa8..2d9da795e 100644 --- a/frontend/tests/unit/activity.spec.ts +++ b/frontend/tests/unit/activity.spec.ts @@ -11,6 +11,14 @@ import { filterActivities, paginateActivities, calculateTotalPages, + statusPresentation, + intentPresentation, + compactSummaryParts, + activeFilterChips, + activeFilterCount, + activityDetailsText, + showParentBadgeInTypeColumn, + shortId, type ActivityRecord, type ActivityFilterOptions } from '../../src/utils/activity' @@ -137,6 +145,225 @@ describe('Status Badge Colors', () => { }) }) +// Status treatment: success is the norm and must NOT shout. Colour is reserved +// for the rows that need a human; everything else is quiet. +describe('statusPresentation', () => { + it('renders success as plain muted text โ€” no pill, no green', () => { + const p = statusPresentation('success') + expect(p.label).toBe('Success') + expect(p.pill).toBe(false) + expect(p.tone).toBe('muted') + expect(p.className).not.toContain('badge') + expect(p.className).not.toContain('success') + expect(p.className).toContain('text-base-content/60') + }) + + it('keeps a red pill for error', () => { + const p = statusPresentation('error') + expect(p).toMatchObject({ label: 'Error', pill: true, tone: 'error' }) + expect(p.className).toContain('badge-error') + }) + + it('keeps an amber pill for blocked', () => { + const p = statusPresentation('blocked') + expect(p).toMatchObject({ label: 'Blocked', pill: true, tone: 'warning' }) + expect(p.className).toContain('badge-warning') + }) + + it('gives rejected a NEUTRAL pill, not the old info blue', () => { + const p = statusPresentation('rejected') + expect(p).toMatchObject({ label: 'Rejected', pill: true, tone: 'neutral' }) + expect(p.className).toContain('badge-ghost') + expect(p.className).not.toContain('badge-info') + }) + + it('treats any other status as a neutral oddity, keeping its raw label', () => { + const p = statusPresentation('timeout') + expect(p).toMatchObject({ label: 'timeout', pill: true, tone: 'neutral' }) + expect(p.className).toContain('badge-ghost') + }) + + it('only ever colours statuses that need attention', () => { + const coloured = ['success', 'error', 'blocked', 'rejected', 'weird'] + .filter(s => statusPresentation(s).tone === 'error' || statusPresentation(s).tone === 'warning') + expect(coloured).toEqual(['error', 'blocked']) + }) +}) + +// Intent: the REASON is the payload, the operation type is a glyph in front of +// it. The old cell showed a coloured `read` pill and hid the reason in a tooltip. +describe('intentPresentation', () => { + it('renders glyph + reason and a full hover title', () => { + const p = intentPresentation({ operation_type: 'read', reason: 'list open issues' }) + expect(p.present).toBe(true) + expect(p.icon).toBe('๐Ÿ“–') + expect(p.label).toBe('read') + expect(p.reason).toBe('list open issues') + expect(p.title).toBe('read โ€” list open issues') + }) + + it('uses the pencil glyph for write and the warning glyph for destructive', () => { + expect(intentPresentation({ operation_type: 'write' }).icon).toBe('โœ๏ธ') + expect(intentPresentation({ operation_type: 'destructive' }).icon).toBe('โš ๏ธ') + }) + + it('falls back to just the glyph when no reason was declared', () => { + const p = intentPresentation({ operation_type: 'write' }) + expect(p.present).toBe(true) + expect(p.reason).toBe('') + expect(p.title).toBe('write') + }) + + it('ignores a whitespace-only reason', () => { + expect(intentPresentation({ operation_type: 'read', reason: ' ' }).reason).toBe('') + }) + + it('is absent when no operation type was declared (caller renders a dash)', () => { + expect(intentPresentation(undefined).present).toBe(false) + expect(intentPresentation(null).present).toBe(false) + expect(intentPresentation({}).present).toBe(false) + expect(intentPresentation({ reason: 'orphan reason' }).present).toBe(false) + }) +}) + +// Compact header strip: total plus only the counts that want attention. +describe('compactSummaryParts', () => { + it('shows the total plus non-zero attention counts', () => { + const parts = compactSummaryParts({ + total_count: 54, + error_count: 6, + blocked_count: 1, + rejected_count: 0, + }) + expect(parts.map(p => p.label)).toEqual(['54 calls', '6 errors', '1 blocked']) + expect(parts.map(p => p.tone)).toEqual(['muted', 'error', 'warning']) + }) + + it('omits zero counts entirely rather than printing a reassuring "0 errors"', () => { + const parts = compactSummaryParts({ total_count: 12, error_count: 0, blocked_count: 0 }) + expect(parts).toHaveLength(1) + expect(parts[0]).toMatchObject({ key: 'total', label: '12 calls', status: '' }) + }) + + it('gives rejected a neutral tone', () => { + const parts = compactSummaryParts({ total_count: 3, rejected_count: 2 }) + expect(parts[1]).toMatchObject({ key: 'rejected', label: '2 rejected', tone: 'neutral' }) + }) + + it('singularises', () => { + expect(compactSummaryParts({ total_count: 1, error_count: 1 }).map(p => p.label)) + .toEqual(['1 call', '1 error']) + }) + + it('carries the status each segment filters to', () => { + const parts = compactSummaryParts({ total_count: 9, error_count: 1, blocked_count: 1 }) + expect(parts.map(p => p.status)).toEqual(['', 'error', 'blocked']) + }) + + it('returns nothing when the summary has not loaded', () => { + expect(compactSummaryParts(null)).toEqual([]) + expect(compactSummaryParts(undefined)).toEqual([]) + }) +}) + +// Compact-strip active-filter summary: what is narrowing the list is visible +// even when the filter grid itself is collapsed. +describe('activeFilterChips', () => { + it('is empty when nothing is filtered', () => { + expect(activeFilterChips({})).toEqual([]) + expect(activeFilterCount({})).toBe(0) + }) + + it('emits one chip per selected type, icon included', () => { + const chips = activeFilterChips({ types: ['tool_call', 'preflight'] }) + expect(chips.map(c => c.label)).toEqual(['๐Ÿ”ง Tool Call', '๐Ÿ›ซ Preflight']) + expect(chips.map(c => c.kind)).toEqual(['type', 'type']) + expect(chips.map(c => c.value)).toEqual(['tool_call', 'preflight']) + }) + + it('always includes the sub-call chip, shortening the correlation id', () => { + const chips = activeFilterChips({ parentId: 'req-parent-abcdefgh' }) + expect(chips).toHaveLength(1) + expect(chips[0].kind).toBe('parent') + expect(chips[0].label).toBe(`โ†ณ Sub-calls of ${shortId('req-parent-abcdefgh')}`) + expect(chips[0].title).toContain('req-parent-abcdefgh') + }) + + it('labels the single-value filters', () => { + const chips = activeFilterChips({ + server: 'github', + status: 'error', + authType: 'agent', + agentName: 'claude', + sensitiveData: 'true', + severity: 'critical', + session: 'sess-0123456789', + sessionLabel: 'Claude Code ยท 14:32', + startDate: '', + endDate: '', + }) + expect(chips.map(c => c.label)).toEqual([ + 'Server: github', + 'Status: error', + 'Auth: ๐Ÿค– Agent', + 'Agent: claude', + 'Sensitive: โš ๏ธ Detected', + 'Severity: critical', + 'Session: Claude Code ยท 14:32', + ]) + }) + + it('falls back to a shortened session id when no label resolved', () => { + const chips = activeFilterChips({ session: 'sess-0123456789' }) + expect(chips[0].label).toBe(`Session: ${shortId('sess-0123456789')}`) + }) + + it('counts every active filter for the Filters toggle badge', () => { + expect( + activeFilterCount({ types: ['tool_call', 'preflight'], server: 'github', parentId: 'req-1' }) + ).toBe(4) + }) + + it('keys are unique so the chips can drive a v-for', () => { + const chips = activeFilterChips({ types: ['tool_call', 'preflight'], server: 'a', status: 'error' }) + expect(new Set(chips.map(c => c.key)).size).toBe(chips.length) + }) +}) + +// De-duplication of the code_execution marker: one line, once. +describe('code_execution marker placement', () => { + const PARENT_WITH_TOOL_NAME = { + type: 'internal_tool_call', + tool_name: 'code_execution', + metadata: { internal_tool_name: 'code_execution' }, + } + + it('reads the Details text a row will print', () => { + expect(activityDetailsText(PARENT_WITH_TOOL_NAME)).toBe('code_execution') + expect(activityDetailsText({ type: 'server_change', metadata: { action: 'enabled' } })).toBe('enabled') + expect(activityDetailsText({ type: 'tool_call' })).toBe('') + expect(activityDetailsText(null)).toBe('') + }) + + it('drops the Type-column badge when Details already says code_execution', () => { + expect(showParentBadgeInTypeColumn(PARENT_WITH_TOOL_NAME)).toBe(false) + }) + + it('keeps the Type-column badge when Details would say nothing', () => { + expect( + showParentBadgeInTypeColumn({ + type: 'internal_tool_call', + metadata: { internal_tool_name: 'code_execution' }, + }) + ).toBe(true) + }) + + it('never badges a non-parent row', () => { + expect(showParentBadgeInTypeColumn({ type: 'tool_call', tool_name: 'code_execution' })).toBe(false) + expect(showParentBadgeInTypeColumn(null)).toBe(false) + }) +}) + // T066 - Filter logic tests describe('Filter Logic', () => { const mockActivities: ActivityRecord[] = [ From b702c10dfc0ad473191d18cb182374d56614a24a Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sat, 22 Aug 2026 07:33:26 +0300 Subject: [PATCH 2/2] fix(webui): severity chip is active only while sensitive-data filter is Detected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cross-review finding on #1024: filtering applies severity only when the sensitive-data filter is 'true', but the compact strip chipped and counted a leftover severity value after sensitive-data was switched off โ€” the collapsed UI claimed a filter that wasn't narrowing anything. Co-Authored-By: Claude Fable 5 --- frontend/src/utils/activity.ts | 6 +++++- frontend/tests/unit/activity.spec.ts | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/frontend/src/utils/activity.ts b/frontend/src/utils/activity.ts index 518b4e35f..b1ba46432 100644 --- a/frontend/src/utils/activity.ts +++ b/frontend/src/utils/activity.ts @@ -504,7 +504,11 @@ export const activeFilterChips = (state: ActivityFilterState): ActiveFilterChip[ label: `Sensitive: ${state.sensitiveData === 'true' ? 'โš ๏ธ Detected' : 'Clean'}`, }) } - if (state.severity) { + // Severity only narrows the list while the sensitive-data filter is + // "Detected" (the view applies it under that same condition) โ€” a severity + // value left behind after switching sensitive-data off must not read as an + // active filter. + if (state.severity && state.sensitiveData === 'true') { chips.push({ kind: 'severity', key: 'severity', label: `Severity: ${state.severity}` }) } if (state.session) { diff --git a/frontend/tests/unit/activity.spec.ts b/frontend/tests/unit/activity.spec.ts index 2d9da795e..35dddfb83 100644 --- a/frontend/tests/unit/activity.spec.ts +++ b/frontend/tests/unit/activity.spec.ts @@ -646,3 +646,25 @@ describe('Relative Time Formatting', () => { }) }) }) + + +describe('activeFilterChips severity gating', () => { + it('does not count a leftover severity as active once sensitive-data is off', () => { + const chips = activeFilterChips({ + types: [], + sensitiveData: '', + severity: 'critical', + }) + expect(chips.find(c => c.kind === 'severity')).toBeUndefined() + expect(activeFilterCount({ types: [], sensitiveData: '', severity: 'critical' })).toBe(0) + }) + + it('counts severity while sensitive-data is Detected', () => { + const chips = activeFilterChips({ + types: [], + sensitiveData: 'true', + severity: 'critical', + }) + expect(chips.map(c => c.kind)).toEqual(['sensitive', 'severity']) + }) +})