All files / src/apps/user/pages RuleActivity.tsx

87.75% Statements 43/49
82.69% Branches 43/52
75% Functions 15/20
87.23% Lines 41/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424                                                                                                                                        1x   1x               1x   4x           1x           1x             1x 30x               1x 30x           30x     120x   60x                                       1x 30x       30x                     30x 32x   30x       30x                                                                                                                         60x                 1x           28x   28x   28x                                                             1x 42x 42x   42x                 42x         42x 14x       42x                   14x                                       42x     42x 42x   42x                                                                 1x                                                         30x 30x                                                      
import {
  FilterSelect,
  ResourceCollection,
  SegmentedFilter,
  useCollectionFilters,
} from "@/components/collection";
import {
  encodeResourceId,
  GOVERNANCE_OUTCOME,
  StatusBadge,
} from "@/components/detail";
import RuleEventRow from "@/components/governance/RuleEventRow";
import {
  describeGroupOutcome,
  describeSubject,
  GovernanceActivityList,
  GovernanceActivitySummary,
  GovernanceGroup,
  GovernanceOutcome,
  OUTCOME_LABELS,
} from "@/objects/Governance";
import { RuleLayer } from "@/objects/Rule";
import { RULE_LAYERS, ruleLayerMeta } from "@/apps/user/pages/rules/ruleLayer";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { chatMessageHref, decisionHref } from "@/routes/resourceHref";
import { useCurrentUserId } from "@/context/AuthContext";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import {
  Bot,
  ChevronLeft,
  ChevronRight,
  MessageSquare,
  ScanSearch,
  ScrollText,
} from "lucide-react";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { parseServerDate } from "@/util/time";
 
/**
 * Governance → Rules → Activity: what the rules have actually done.
 *
 * The page exists for the rules that did **nothing**. Until the backend kept
 * this log, a rule's effects were visible only inside a conversation's
 * execution trace, and an action with nothing to do emitted no event at all —
 * so a redaction rule over a prompt containing no PII was indistinguishable
 * from a rule that had never been evaluated. "Was this governed, and by
 * what?" had no answer anywhere in the product.
 *
 * So every row is one rule evaluated once, and the outcome badge carries the
 * distinction: it acted, it ran and found nothing to do, it stood aside, or
 * it refused the invocation. Three of those four are a rule working.
 *
 * The rows are grouped into the **message** they ran on. A single turn is
 * routinely governed by half a dozen rules across both phases, and read as a
 * flat list those interleave with every other agent's traffic — somebody
 * monitoring a fleet is asking "what happened to this message?", not "what
 * did rule 4 do at 11:03". So the page pages by turn, not by row: a card is
 * one invocation, headed by what it ran against and how it came out.
 *
 * Filtering, counting and paging happen on the server, like the reviewer
 * queue: the summary counts every row the filters select rather than the
 * fifty in hand, which would answer a different question from the one it
 * appears to.
 */
 
const PAGE_SIZE = 25;
 
const OUTCOME_OPTIONS: { value: string; label: string }[] = [
  { value: "all", label: "All" },
  { value: "applied", label: OUTCOME_LABELS.applied },
  { value: "blocked", label: OUTCOME_LABELS.blocked },
  { value: "no_change", label: OUTCOME_LABELS.no_change },
  { value: "not_matched", label: OUTCOME_LABELS.not_matched },
];
 
const LAYER_OPTIONS = [
  { value: "all", label: "Any layer" },
  ...RULE_LAYERS.map((layer) => ({
    value: layer,
    label: ruleLayerMeta(layer).label,
  })),
];
 
const PHASE_OPTIONS = [
  { value: "all", label: "Input & output" },
  { value: "input", label: "Against the prompt" },
  { value: "output", label: "Against the response" },
];
 
const WINDOW_OPTIONS = [
  { value: "all", label: "All time" },
  { value: "1", label: "Last 24 hours" },
  { value: "7", label: "Last 7 days" },
  { value: "30", label: "Last 30 days" },
];
 
const formatWhen = (value?: string | null): string =>
  value ? parseServerDate(value).toLocaleString() : "—";
 
// ─── Row ──────────────────────────────────────────────────────────────────────
 
// ─── Group ────────────────────────────────────────────────────────────────────
 
/** The outcome counts for one turn, strongest first. Silent about outcomes
 *  that did not occur — a card claiming "0 blocked" says nothing. */
const GroupOutcomes: React.FC<{ group: GovernanceGroup }> = ({ group }) => {
  const order: GovernanceOutcome[] = [
    "blocked",
    "applied",
    "no_change",
    "not_matched",
  ];
  return (
    <div className="flex items-center gap-1.5 flex-wrap">
      {order
        .filter((outcome) => (group.outcomes[outcome] ?? 0) > 0)
        .map((outcome) => (
          <StatusBadge
            key={outcome}
            status={outcome}
            scale={GOVERNANCE_OUTCOME}
            label={`${group.outcomes[outcome]} ${OUTCOME_LABELS[outcome].toLowerCase()}`}
            size="xs"
          />
        ))}
    </div>
  );
};
 
/**
 * One message, and every rule that ran on it.
 *
 * The card is the unit of the page. Its header answers "what was governed,
 * when, and how did it come out?" in one line, so a reader scanning a fleet's
 * traffic can skip a turn where nothing happened without reading four rules
 * to find that out.
 */
const InvocationCard: React.FC<{ group: GovernanceGroup }> = ({ group }) => {
  const headline = describeGroupOutcome(group);
  // The message these rules ran on. Null when the turn never persisted — a
  // run that failed before it was saved genuinely has nothing to open, and
  // saying so beats a link to the agent's chat at whatever it is showing.
  const messageHref = chatMessageHref({
    agentId: group.agent_id,
    modelId: group.ai_model_id,
    conversationId: group.conversation_id,
    messageId: group.message_id,
  });
  // The turn's decision record — for an answer or a skill run, the turns
  // that have one (an evaluation cell's rules group here too, and have
  // none), and only the viewer's own: a governance editor sees a member's
  // turns here, whose record opens to them only through a flag on it — from
  // the review queue.
  const me = useCurrentUserId();
  const ownTurn = !!me && group.events.some((e) => e.owner_user_id === me);
  const recordHref =
    ownTurn && (group.message_id || group.execution_type === "skill")
      ? decisionHref(group.invocation_id)
      : null;
 
  return (
    <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-hidden">
      <div className="flex items-start justify-between gap-3 px-4 py-3 border-b border-gray-100 dark:border-gray-700 bg-gray-50/70 dark:bg-gray-800/60">
        <div className="min-w-0">
          <div className="flex items-center gap-2 min-w-0">
            <Bot className="size-4 shrink-0 text-gray-400 dark:text-gray-500" />
            {/* The agent's own page, when it still exists — the message
                itself is the action on the right. */}
            {group.agent_id && group.subject ? (
              <Link
                to={APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
                  ROUTE_PARAMS.AGENT.id,
                  encodeResourceId(group.agent_id),
                )}
                className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate hover:underline"
              >
                {describeSubject(group)}
              </Link>
            ) : (
              <span className="text-sm font-semibold text-gray-600 dark:text-gray-300 truncate">
                {describeSubject(group)}
              </span>
            )}
            <span className="text-[11px] text-gray-400 dark:text-gray-500 shrink-0">
              {formatWhen(group.occurred_at)}
            </span>
          </div>
          <p className="mt-0.5 text-[11px] text-gray-400 dark:text-gray-500">
            {group.events.length === 1
              ? "1 rule ran on this message"
              : `${group.events.length} rules ran on this message`}
            {headline.outcome === "blocked" ? " — it was refused" : ""}
          </p>
        </div>
        <div className="shrink-0 flex items-center gap-2">
          <GroupOutcomes group={group} />
          {messageHref && (
            <Link
              to={messageHref}
              title="Open the message these rules ran on"
              className="inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-gray-200 dark:border-gray-600 text-[11px] font-medium text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-white dark:hover:bg-gray-700 transition-colors"
            >
              <MessageSquare className="size-3.5" />
              Open message
            </Link>
          )}
          {recordHref && (
            <Link
              to={recordHref}
              title="Everything this turn recorded"
              className="inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-gray-200 dark:border-gray-600 text-[11px] font-medium text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-white dark:hover:bg-gray-700 transition-colors"
            >
              <ScanSearch className="size-3.5" />
              Why?
            </Link>
          )}
        </div>
      </div>
 
      <div className="p-3 space-y-2">
        {group.events.map((event) => (
          <RuleEventRow key={event.id} event={event} />
        ))}
      </div>
    </div>
  );
};
 
// ─── Paging ───────────────────────────────────────────────────────────────────
 
const Pager: React.FC<{
  offset: number;
  count: number;
  total: number;
  onOffset: (offset: number) => void;
}> = ({ offset, count, total, onOffset }) => {
  Eif (total <= PAGE_SIZE) return null;
  const first = total === 0 ? 0 : offset + 1;
  const last = offset + count;
 
  return (
    <div className="flex items-center justify-between gap-3 pt-1">
      <span className="text-xs text-gray-500 dark:text-gray-400 tabular-nums">
        {first}–{last} of {total}
      </span>
      <div className="flex items-center gap-2">
        <button
          type="button"
          disabled={offset === 0}
          onClick={() => onOffset(Math.max(0, offset - PAGE_SIZE))}
          className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-40"
        >
          <ChevronLeft className="size-3.5" />
          Previous
        </button>
        <button
          type="button"
          disabled={last >= total}
          onClick={() => onOffset(offset + PAGE_SIZE)}
          className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-40"
        >
          Next
          <ChevronRight className="size-3.5" />
        </button>
      </div>
    </div>
  );
};
 
// ─── Activity content (Governance → Rules → Activity) ────────────────────────
 
export const RuleActivityContent: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const [offset, setOffset] = useState(0);
 
  const collection = useCollectionFilters<{
    outcome: string;
    layer: string;
    phase: string;
    window: string;
  }>({
    defaults: { outcome: "all", layer: "all", phase: "all", window: "all" },
    view: "list",
  });
  const { filters, setFilter } = collection;
 
  // Any change to what is being asked for starts at the first page; staying
  // on page 4 of a different filter shows an empty list that looks like no
  // results.
  useEffect(
    () => setOffset(0),
    [filters.outcome, filters.layer, filters.phase, filters.window],
  );
 
  const { data, isLoading } = useQuery<GovernanceActivityList | null>({
    queryKey: [
      QUERY_KEYS.GET.RULE_ACTIVITY,
      filters.outcome,
      filters.layer,
      filters.phase,
      filters.window,
      offset,
    ],
    queryFn: () =>
      getApiHandler().rule_router.activity({
        ...(filters.outcome === "all"
          ? {}
          : { outcome: filters.outcome as GovernanceOutcome }),
        ...(filters.layer === "all"
          ? {}
          : { layer: filters.layer as RuleLayer }),
        ...(filters.phase === "all"
          ? {}
          : { phase: filters.phase as "input" | "output" }),
        ...(filters.window === "all" ? {} : { days: Number(filters.window) }),
        limit: PAGE_SIZE,
        offset,
      }),
    // The previous page stays on screen while the next one loads, so paging
    // and filtering do not flash a skeleton over a list the reader is using.
    placeholderData: keepPreviousData,
    staleTime: 15_000,
  });
 
  const groups: GovernanceGroup[] = data?.groups ?? [];
  // Turns, not rules: the page pages by invocation so a card is never cut in
  // half at a page boundary.
  const total = data?.total ?? 0;
  const summary: GovernanceActivitySummary | null = data?.summary ?? null;
 
  return (
    <div className="space-y-4">
      <ResourceCollection<GovernanceGroup>
        description="Every rule that ran, grouped into the message it ran on. A rule that matched and found nothing to do is recorded here too — that a policy was evaluated and stood aside is the answer to a question an audit asks first, and it is not visible anywhere else."
        stats={[
          // Messages first: it is the unit the page is read in, and the one
          // the pager counts.
          { label: "Messages", value: total, loading: isLoading },
          {
            label: "Evaluations",
            value: summary?.total ?? 0,
            loading: isLoading,
          },
          {
            label: OUTCOME_LABELS.applied,
            value: summary?.applied ?? 0,
            loading: isLoading,
          },
          {
            label: OUTCOME_LABELS.blocked,
            value: summary?.blocked ?? 0,
            loading: isLoading,
          },
          {
            label: OUTCOME_LABELS.no_change,
            value: summary?.no_change ?? 0,
            loading: isLoading,
          },
        ]}
        filters={
          <>
            <SegmentedFilter
              value={filters.outcome}
              onChange={(value) => setFilter("outcome", value)}
              options={OUTCOME_OPTIONS}
            />
            <FilterSelect
              value={filters.layer}
              onValueChange={(value) => setFilter("layer", value)}
              placeholder="Any layer"
              options={LAYER_OPTIONS}
              active={filters.layer !== "all"}
            />
            <FilterSelect
              value={filters.phase}
              onValueChange={(value) => setFilter("phase", value)}
              placeholder="Input & output"
              options={PHASE_OPTIONS}
              active={filters.phase !== "all"}
            />
            <FilterSelect
              value={filters.window}
              onValueChange={(value) => setFilter("window", value)}
              placeholder="All time"
              options={WINDOW_OPTIONS}
              active={filters.window !== "all"}
            />
          </>
        }
        activeFilterCount={collection.activeFilterCount}
        onClear={collection.clear}
        items={groups}
        itemKey={(group) => group.invocation_id ?? group.events[0]?.id ?? ""}
        renderRow={(group) => <InvocationCard group={group} />}
        listVariant="rows"
        loading={isLoading}
        filtered={collection.activeFilterCount > 0}
        empty={{
          Icon: ScrollText,
          title: "Nothing has been governed yet.",
          hint: "Once a rule is evaluated against a prompt or a response, the message appears here with every rule that ran on it — including the ones that found nothing to do.",
          dashed: true,
        }}
        emptyFilteredTitle="No messages match these filters."
        emptyFilteredHint="Try widening the outcome or the time window."
      />
 
      {/* Below the list, like the reviewer queue's: paging belongs after what
          it pages, not between the toolbar and the first row. */}
      <Pager
        offset={offset}
        count={groups.length}
        total={total}
        onOffset={setOffset}
      />
    </div>
  );
};
 
export default RuleActivityContent;