File size: 19,419 Bytes
a5981db
85f794d
a5981db
c920df3
 
daae64a
 
85f794d
daae64a
85f794d
c920df3
 
 
 
 
 
 
a5981db
c920df3
 
 
 
 
a5981db
c920df3
 
a5981db
 
 
 
 
 
c920df3
 
a5981db
 
 
 
 
 
 
 
 
 
c920df3
a5981db
 
 
 
 
 
c920df3
 
a5981db
 
 
 
c920df3
 
 
 
 
 
 
c72f0a1
a5981db
c920df3
 
 
a5981db
85f794d
c920df3
 
 
 
 
 
a5981db
85f794d
 
a5981db
85f794d
 
a5981db
 
 
85f794d
a5981db
85f794d
 
a5981db
 
 
 
 
 
 
c920df3
a5981db
 
81a8217
c920df3
 
 
 
 
a5981db
c920df3
 
 
a5981db
c920df3
a5981db
 
c920df3
 
 
 
 
 
daae64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c920df3
 
 
a5981db
 
 
c920df3
 
a5981db
 
85f794d
a5981db
 
 
 
c920df3
 
 
a5981db
 
 
85f794d
a5981db
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
a5981db
 
 
 
 
 
 
 
 
 
 
 
85f794d
c920df3
a5981db
 
 
 
 
85f794d
 
 
a5981db
 
 
 
 
daae64a
a5981db
 
 
c920df3
 
 
a5981db
daae64a
 
 
a5981db
 
 
 
 
 
daae64a
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c920df3
 
 
 
 
a5981db
c920df3
 
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
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ArrowClockwise, ArrowsLeftRight, CaretRight, CursorClick, Funnel, Globe, MagnifyingGlass, WarningCircle } from "@phosphor-icons/react";
import { API_V1, CREDENTIALS, checkTenant, UNAUTHORIZED_EVENT } from "../apiContract";
import { isAdmin } from "../shell/session";
import type { SessionUser } from "../shell/session";
import { FilterBuilderPanel, Popover, countConditions, createFilterRule, opsForType } from "../filter-kit";
import type { Field, FilterTree } from "../filter-kit";
import { LockMark } from "../customer-grid/icons";
import { DEFAULT_FILTERS, activityDescription, activityFieldConditionCount, activityFilterFields, activityTargetName, filterActivity, groupActivityByDay } from "./activityLog";
import type { ActivityEntry, ActivityEvent, ActivityFilters, ActivityLimits, MovementSample } from "./activityLog";
import "./activityLog.css";

interface SessionRow {
  sessionId: string;
  dropped: number;
  prunedEvents: number;
}
interface SessionList { sessions: SessionRow[]; limits: ActivityLimits }
interface Timeline {
  events: ActivityEvent[];
  total: number;
  offset: number;
  limit: number;
  limits: ActivityLimits;
}

class ActivityReadError extends Error {
  readonly denied: boolean;
  readonly missing: boolean;
  constructor(message: string, denied = false, missing = false) {
    super(message); this.denied = denied; this.missing = missing;
  }
}

async function call<T>(path: string, signal: AbortSignal): Promise<T> {
  const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, signal, cache: "no-store" });
  if (checkTenant(response)) throw new ActivityReadError("Reopen Settings to view this workspace's activity.", true);
  if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
  if (!response.ok) throw new ActivityReadError(response.status === 403
    ? "You do not have access to this activity."
    : response.status === 404 ? "This activity session is no longer available." : "Activity could not be loaded.",
  response.status === 401 || response.status === 403, response.status === 404);
  return await response.json() as T;
}

// Bound concurrent reads, never the number of sessions or event pages.
async function readEach<T>(items: T[], read: (item: T) => Promise<void>, signal: AbortSignal): Promise<void> {
  let next = 0;
  await Promise.all(Array.from({ length: Math.min(4, items.length) }, async () => {
    while (next < items.length && !signal.aborted) await read(items[next++]);
  }));
}

const PAGE_SIZE = 50;
const number = (value: number) => value.toLocaleString();
const clock = (ts: number) => new Date(ts).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });

function movementDetail(sample: MovementSample): string {
  if (sample.kind === "keypress") return sample.key ?? "Key";
  if (sample.kind === "pointer" || sample.kind === "scroll") return `${number(sample.x ?? 0)}, ${number(sample.y ?? 0)}`;
  return "";
}

function Skeleton() {
  return <div className="activity-loading set-skeleton" role="status" aria-label="Loading activity" aria-busy="true">
    {[0, 1, 2, 3, 4].map(row => <span key={row} className="set-skeleton-line" aria-hidden="true" />)}
  </div>;
}

function EventRow({ entry }: { entry: ActivityEntry }) {
  const { event, actor, role, limits } = entry;
  const [expanded, setExpanded] = useState(false);
  const [samplePage, setSamplePage] = useState(0);
  const regionId = useId();
  const buttonId = useId();
  const samples = event.movement ?? [];
  const sampleSize = 50;
  const description = activityDescription(event);
  const failed = event.kind === "error" || (event.kind === "api" && (event.status === 0 || (event.status ?? 0) >= 400));
  const Icon = failed ? WarningCircle : event.kind === "click" ? CursorClick : event.kind === "api" ? ArrowsLeftRight : Globe;
  const content = <>
    <span className={`activity-event-icon${failed ? " is-error" : ""}`} role={failed ? "img" : undefined}
      aria-label={failed ? "Failed" : undefined} title={failed ? "Failed" : undefined}><Icon size={18} aria-hidden="true" /></span>
    <span className="activity-event-copy">
      <span className="activity-description"><span className="activity-kind">{description.action}</span>{" "}
        <span className="activity-target" title={event.target?.path?.join(" > ")}>{description.target}</span></span>
      <span className="activity-event-meta"><time dateTime={new Date(event.ts).toISOString()} title={new Date(event.ts).toLocaleString()}>{clock(event.ts)}</time></span>
    </span>
    <span className="activity-actor"><span className="activity-role" title="Current role">{role || "Role unavailable"}</span>
      <span className="activity-actor-name" title={actor}>{actor}</span></span>
    {event.kind === "error" ? <CaretRight size={16} className={`activity-chevron${expanded ? " is-open" : ""}`} aria-hidden="true" /> : null}
  </>;

  return <li className={`activity-event${event.kind === "error" ? " activity-event-error" : ""}`}>
    {event.kind === "error" ? <button type="button" id={buttonId} className="activity-entry activity-entry-toggle"
      aria-expanded={expanded} aria-controls={expanded ? regionId : undefined} onClick={() => setExpanded(open => !open)}>{content}</button>
      : <div className="activity-entry">{content}</div>}
    {expanded ? <div id={regionId} role="region" aria-labelledby={buttonId} className="activity-trail">
      <h4 className="set-h4">Before the error</h4>
      <p className="set-help">Up to {number(limits.movementWindowSeconds)} seconds and {number(limits.maxMovementSamples)} movement samples</p>
      {event.movementDropped ? <p className="set-notice" role="status">{number(event.movementDropped)} samples were omitted by the capture limits.</p> : null}
      {samples.length === 0 ? <p className="set-help">No movement was captured before this error.</p> : <>
        <ol className="activity-movement">
          {samples.slice(samplePage * sampleSize, (samplePage + 1) * sampleSize).map((sample, index) => <li key={`${sample.ts}-${index}`}>
            <span className="activity-number">{Math.max(0, (event.ts - sample.ts) / 1000).toFixed(1)} s before</span>
            <span className="activity-sample-kind">{sample.kind}</span>
            <span className="activity-target" title={sample.target.path?.join(" > ")}>{activityTargetName(sample.target)}</span>
            <span className="activity-number">{movementDetail(sample)}</span>
          </li>)}
        </ol>
        {samples.length > sampleSize ? <div className="activity-pagination">
          <span className="set-help">Samples {number(samplePage * sampleSize + 1)} to {number(Math.min((samplePage + 1) * sampleSize, samples.length))} of {number(samples.length)}</span>
          <button type="button" className="set-secondary" disabled={samplePage === 0} onClick={() => setSamplePage(page => page - 1)}>Earlier samples</button>
          <button type="button" className="set-secondary" disabled={(samplePage + 1) * sampleSize >= samples.length} onClick={() => setSamplePage(page => page + 1)}>Later samples</button>
        </div> : null}
      </>}
    </div> : null}
  </li>;
}

function ActivityFilterMenu({ field, fields, conditions, onChange }: {
  field?: Field; fields: Field[]; conditions: FilterTree; onChange: (conditions: FilterTree) => void;
}) {
  const count = field ? activityFieldConditionCount(conditions.nodes, field.key) : countConditions(conditions.nodes);
  const label = field?.label ?? "Filter";
  const focused = useMemo(() => {
    if (!field || count) return conditions;
    // An unfinished shared rule stays inactive until the builder commits a value.
    return { ...conditions, nodes: [...conditions.nodes,
      createFilterRule({ colId: field.key, op: opsForType(field.type)[0], value: "" })] };
  }, [conditions, field, count]);
  const choices = field ? [field, ...fields.filter(item => item.key !== field.key)] : fields;
  return <Popover label={count ? `${label} (${count})` : label} icon={<Funnel size={16} aria-hidden="true" />}
    active={count > 0} tone="filter" wide>
    {() => <FilterBuilderPanel database={null} fields={choices} filters={focused} onChange={onChange} />}
  </Popover>;
}

function ActivityFilterToolbar({ user, fields, filters, resultsId, hasFilters, loading, refreshedAt, onChange, onClear, onRefresh }: {
  user: SessionUser; fields: Field[]; filters: ActivityFilters; resultsId: string; hasFilters: boolean;
  loading: boolean; refreshedAt: number | null; onChange: (patch: Partial<ActivityFilters>) => void;
  onClear: () => void; onRefresh: () => void;
}) {
  const conditions: FilterTree = filters.conditions ?? { conj: "and", nodes: [] };
  const changeConditions = (conditions: FilterTree) => onChange({ conditions });
  return <div className="activity-toolbar" role="group" aria-label="Activity filters">
    <label className="activity-search"><MagnifyingGlass size={16} aria-hidden="true" />
      <input type="search" aria-label="Search activity" placeholder="Search activity" value={filters.search}
        onChange={event => onChange({ search: event.target.value })} aria-controls={resultsId} />
    </label>
    {fields.filter(field => field.filterable !== false).map(field => <ActivityFilterMenu key={field.key}
      field={field} fields={fields} conditions={conditions} onChange={changeConditions} />)}
    {!isAdmin(user) ? <span className="activity-access-limit" title="Set by your access" aria-label={`User: ${user.username}, locked by your access`}>
      <LockMark size={14} title="Set by your access" />User: {user.username}</span> : null}
    <ActivityFilterMenu fields={fields} conditions={conditions} onChange={changeConditions} />
    <button type="button" className="set-secondary" disabled={!hasFilters} onClick={onClear}>Clear</button>
    <button type="button" className="set-secondary activity-refresh" aria-label="Refresh activity" title="Refresh activity" disabled={loading}
      onClick={onRefresh}><ArrowClockwise size={16} aria-hidden="true" />
      {refreshedAt ? <>Refreshed <time dateTime={new Date(refreshedAt).toISOString()} title={new Date(refreshedAt).toLocaleString()}>{clock(refreshedAt)}</time></> : "Refresh"}</button>
  </div>;
}

function ActivityPane({ user }: { user: SessionUser }) {
  const admin = isAdmin(user);
  const [users, setUsers] = useState<string[]>([user.username]);
  const [entries, setEntries] = useState<ActivityEntry[]>([]);
  const [filters, setFilters] = useState<ActivityFilters>(DEFAULT_FILTERS);
  const [page, setPage] = useState(0);
  const [revision, setRevision] = useState(0);
  const [loading, setLoading] = useState(true);
  const [problem, setProblem] = useState("");
  const [denied, setDenied] = useState(false);
  const [refreshedAt, setRefreshedAt] = useState<number | null>(null);
  const [omitted, setOmitted] = useState({ dropped: 0, pruned: 0 });
  const resultsRef = useRef<HTMLDivElement>(null);
  const headingId = useId();
  const resultsId = useId();

  useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;
    setLoading(true); setProblem(""); setDenied(false); setEntries([]); setPage(0);
    const clearIdentity = () => {
      controller.abort(); setEntries([]); setUsers([user.username]); setRefreshedAt(null); setLoading(false); setProblem(""); setDenied(true);
    };
    window.addEventListener(UNAUTHORIZED_EVENT, clearIdentity);
    async function load() {
      try {
        const owners = admin
          ? Array.from(new Set([user.username, ...(await call<{ users: string[] }>("/activity/users", signal)).users]))
          : [user.username];
        if (signal.aborted) return;
        setUsers(owners);
        // Roles come from the existing admin directory, never inferred from another actor's name.
        const directory = admin ? await call<{ users: Array<{ username: string; role: string }> }>("/admin/users", signal)
          .catch(() => ({ users: [] })) : { users: [] };
        if (signal.aborted) return;
        const roleRows = Array.isArray(directory.users) ? directory.users : [];
        const roles = new Map(roleRows.filter(actor => typeof actor?.username === "string" && typeof actor.role === "string")
          .map(actor => [actor.username, actor.role]));
        roles.set(user.username, user.role);
        const sessions: Array<{ actor: string; row: SessionRow; limits: ActivityLimits }> = [];
        await readEach(owners, async actor => {
          const query = admin ? `?user=${encodeURIComponent(actor)}` : "";
          const list = await call<SessionList>(`/activity/sessions${query}`, signal);
          for (const row of list.sessions) sessions.push({ actor, row, limits: list.limits });
        }, signal);
        const loaded: ActivityEntry[] = [];
        await readEach(sessions, async ({ actor, row, limits }) => {
          let offset = 0;
          let total: number | undefined;
          const sessionEntries: ActivityEntry[] = [];
          try {
            while (!signal.aborted && (total === undefined || offset < total)) {
              const query = new URLSearchParams({ limit: "100", offset: String(offset) });
              if (admin) query.set("user", actor);
              const timeline = await call<Timeline>(`/activity/sessions/${encodeURIComponent(row.sessionId)}?${query}`, signal);
              for (const event of timeline.events) sessionEntries.push({ event, actor, role: roles.get(actor), sessionId: row.sessionId, limits: timeline.limits ?? limits });
              // Advance over the server slice even if sanitization omitted an event.
              const next = timeline.offset + timeline.limit;
              if (next <= offset) throw new ActivityReadError("Activity could not be loaded.");
              offset = next;
              // Freeze the session's extent so live capture cannot extend this read forever.
              total ??= timeline.total;
            }
          } catch (error) {
            // Retention can remove a session between listing it and reading its pages.
            if (error instanceof ActivityReadError && error.missing) return;
            throw error;
          }
          for (const entry of sessionEntries) loaded.push(entry);
        }, signal);
        if (signal.aborted) return;
        loaded.sort((a, b) => b.event.ts - a.event.ts || a.actor.localeCompare(b.actor));
        setEntries(loaded);
        setRefreshedAt(Date.now());
        setOmitted(sessions.reduce((sum, { row }) => ({ dropped: sum.dropped + row.dropped, pruned: sum.pruned + row.prunedEvents }), { dropped: 0, pruned: 0 }));
        setLoading(false);
      } catch (error) {
        if (signal.aborted) return;
        controller.abort();
        setEntries([]); setLoading(false);
        setDenied(error instanceof ActivityReadError && error.denied);
        setProblem(error instanceof ActivityReadError ? error.message : "Activity could not be loaded.");
      }
    }
    void load();
    return () => { controller.abort(); window.removeEventListener(UNAUTHORIZED_EVENT, clearIdentity); };
  }, [admin, user.username, user.role, revision]);

  const filtered = useMemo(() => filterActivity(entries, filters), [entries, filters]);
  const lastPage = Math.max(0, Math.ceil(filtered.length / PAGE_SIZE) - 1);
  const currentPage = Math.min(page, lastPage);
  const offset = currentPage * PAGE_SIZE;
  const groups = groupActivityByDay(filtered.slice(offset, offset + PAGE_SIZE));
  const fields = useMemo(() => activityFilterFields(users, admin && !denied), [users, admin, denied]);
  const conditionCount = countConditions(filters.conditions?.nodes ?? []);
  const hasFilters = Boolean(filters.search || filters.actor || filters.action !== "all" || filters.timeframe !== "all" || conditionCount);
  useLayoutEffect(() => {
    // Reset after rendering so scroll anchoring cannot hide the filters.
    resultsRef.current?.closest(".set-body")?.scrollTo({ top: 0, behavior: "instant" });
  }, [currentPage, filters]);
  function updateFilters(patch: Partial<ActivityFilters>) { setFilters(value => ({ ...value, ...patch })); setPage(0); }
  function clearFilters() { setFilters(DEFAULT_FILTERS); setPage(0); }
  function changePage(next: number) {
    setPage(next);
    resultsRef.current?.focus({ preventScroll: true });
  }

  return <div className="set-pane activity-pane">
    <h3 className="set-h" id={headingId}>Activity log</h3>
    <ActivityFilterToolbar user={user} fields={fields} filters={filters} resultsId={resultsId} hasFilters={hasFilters}
      loading={loading} refreshedAt={refreshedAt} onChange={updateFilters} onClear={clearFilters}
      onRefresh={() => setRevision(value => value + 1)} />
    <div className="activity-results" id={resultsId} ref={resultsRef} tabIndex={-1} role="region" aria-labelledby={headingId} aria-busy={loading}>
      {denied ? <p className="set-notice" role="status">{problem || "You do not have access to this activity."}</p>
        : problem ? <div className="set-error" role="alert"><span>{problem}</span>
          <button type="button" className="set-secondary" onClick={() => setRevision(value => value + 1)}>Retry</button></div>
          : loading ? <Skeleton />
            : !filtered.length ? <div className="activity-empty" role="status"><p className="set-help">{hasFilters ? "No activity matches your filters." : "No activity yet."}</p>
              {hasFilters ? <button type="button" className="set-secondary" onClick={clearFilters}>Clear filters</button> : null}</div>
              : <>
                <div className="activity-groups">{groups.map(group => <section className="activity-day" key={group.day} aria-label={group.label}>
                  <h4 className="activity-day-heading"><time dateTime={group.day}>{group.label}</time></h4>
                  <ol className="activity-timeline" aria-label={`Activity for ${group.label}`}>
                    {group.entries.map((entry, index) => <EventRow key={`${entry.actor}:${entry.sessionId}:${entry.event.eventId || `${entry.event.ts}:${offset + index}`}`} entry={entry} />)}
                  </ol>
                </section>)}</div>
                <nav className="activity-pagination" aria-label="Activity pages">
                  <span className="set-help" role="status">{number(offset + 1)} to {number(Math.min(offset + PAGE_SIZE, filtered.length))} of {number(filtered.length)} entries</span>
                  <button type="button" className="set-secondary" disabled={currentPage === 0} onClick={() => changePage(currentPage - 1)}>Previous</button>
                  <button type="button" className="set-secondary" disabled={currentPage === lastPage} onClick={() => changePage(currentPage + 1)}>Next</button>
                </nav>
              </>}
      {!loading && !problem && !denied && (omitted.dropped > 0 || omitted.pruned > 0) ? <p className="set-notice activity-retention" role="status">
        {number(omitted.pruned)} older events are no longer available and {number(omitted.dropped)} events could not be captured.
      </p> : null}
    </div>
  </div>;
}

export default function ActivityLogPage({ user }: { user: SessionUser }) {
  // Remount fetched state when the signed-in identity changes.
  return <ActivityPane key={`${user.tenant}:${user.username}:${user.role}`} user={user} />;
}