All files / src/components/sessions SessionsTable.tsx

97.67% Statements 42/43
81.48% Branches 44/54
100% Functions 22/22
97.36% Lines 37/38

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                                                                                                7x                               163x 163x 163x     163x         163x                   5x                                                                   6x                                                                     136x 136x   136x           2x                                                                         163x                                                         73x 73x 73x   73x 56x     73x 73x 28x         73x 73x 71x     73x 71x       73x 2x 2x 2x     2x   2x       73x         289x           4x                             39x                                           136x                                
/**
 * Sessions activity monitor — a live, environment-grouped table of every
 * session (task-bound and ad-hoc).
 *
 * This is the discovery surface for sessions that aren't reachable through the
 * Tasks tree: ad-hoc `grackle spawn`s, debug sessions, and superseded task
 * attempts. Sessions are grouped under their host environment (the one field
 * every session always has), with the owning task surfaced as a link when
 * present and an `ad-hoc` marker otherwise.
 *
 * Pure presentational component — no `useGrackle()`. All branchy view logic
 * lives in {@link ./sessionsView.js}.
 */
 
import { useMemo, useState, type JSX } from "react";
import { AnimatePresence, motion } from "motion/react";
import { ChevronDown, ChevronRight, ClipboardList, Monitor, Search, Terminal } from "lucide-react";
import type { Environment, PersonaData, Session, TaskData } from "../../hooks/types.js";
import { ICON_SM } from "../../utils/iconSize.js";
import { formatCost, formatTokens } from "../../utils/format.js";
import { formatRelativeTime } from "../../utils/time.js";
import {
  buildStatusChips,
  describeSessionStatus,
  filterSessions,
  groupSessionsByEnvironment,
  type SessionGroup,
  type StatusFilter,
} from "./sessionsView.js";
import styles from "./SessionsTable.module.scss";
 
/** Props for {@link SessionsTable}. */
export interface SessionsTableProps {
  /** All sessions to display (task-bound and ad-hoc). */
  sessions: Session[];
  /** Environments, for group headers and name resolution. */
  environments: Environment[];
  /** Tasks, for resolving task titles on the task chip (optional). */
  tasks?: TaskData[];
  /** Personas, for resolving persona names (optional). */
  personas?: PersonaData[];
  /** Called when a session row is activated. */
  onOpenSession: (sessionId: string) => void;
  /** Called when a session's task chip is activated. */
  onOpenTask: (taskId: string) => void;
}
 
/** Entrance/exit animation timing for collapsing a group (seconds). */
const COLLAPSE_DURATION_S: number = 0.18;
 
/** A single session row. */
function SessionRow({
  session,
  taskTitle,
  personaName,
  onOpenSession,
  onOpenTask,
}: {
  session: Session;
  taskTitle: string | undefined;
  personaName: string | undefined;
  onOpenSession: (sessionId: string) => void;
  onOpenTask: (taskId: string) => void;
}): JSX.Element {
  const status = describeSessionStatus(session);
  const totalTokens = (session.inputTokens ?? 0) + (session.outputTokens ?? 0);
  const cost = session.costMillicents ?? 0;
  // Bind to a const so TypeScript narrows it to `string` inside the branch
  // below (a property access would not narrow within the onClick closure).
  const taskId = session.taskId;
 
  // The clickable session area and the task-association control are siblings,
  // not nested, so each is an independent, keyboard-accessible <button> (no
  // invalid nested-interactive ARIA, no key-event double-firing between them).
  return (
    <li
      className={styles.row}
      data-status-tone={status.tone}
      data-testid={`session-row-${session.id}`}
    >
      <button
        type="button"
        className={styles.rowButton}
        aria-label={`Open session: ${session.prompt || session.id}`}
        onClick={() => onOpenSession(session.id)}
        data-testid={`session-open-${session.id}`}
      >
        <span className={styles.statusDot} data-tone={status.tone} aria-hidden="true" />
        <div className={styles.rowContent}>
          <div className={styles.promptLine}>
            <span className={styles.prompt}>
              {session.prompt || <span className={styles.promptEmpty}>(no prompt)</span>}
            </span>
          </div>
          <div className={styles.meta}>
            <span className={styles.statusLabel} data-tone={status.tone}>
              {status.label}
            </span>
            <span className={styles.runtimeBadge}>{session.runtime || "unknown"}</span>
            {personaName !== undefined && (
              <span className={styles.personaBadge} data-testid={`session-persona-${session.id}`}>
                {personaName}
              </span>
            )}
            <span className={styles.time}>{formatRelativeTime(session.startedAt)}</span>
            {totalTokens > 0 && (
              <span className={styles.tokens}>{formatTokens(totalTokens)} tok</span>
            )}
            {cost > 0 && <span className={styles.cost}>{formatCost(cost)}</span>}
          </div>
        </div>
      </button>
      <div className={styles.association}>
        {taskId ? (
          <button
            type="button"
            className={styles.taskChip}
            title={taskTitle ?? taskId}
            onClick={() => onOpenTask(taskId)}
            data-testid={`session-task-${session.id}`}
          >
            <ClipboardList size={ICON_SM} aria-hidden="true" />
            <span className={styles.taskChipLabel}>{taskTitle ?? taskId}</span>
          </button>
        ) : (
          <span className={styles.adHocChip} data-testid={`session-adhoc-${session.id}`}>
            <Terminal size={ICON_SM} aria-hidden="true" />
            ad-hoc
          </span>
        )}
      </div>
    </li>
  );
}
 
/** A collapsible environment group of sessions. */
function EnvironmentGroup({
  group,
  collapsed,
  onToggle,
  taskTitleById,
  personaNameById,
  onOpenSession,
  onOpenTask,
}: {
  group: SessionGroup;
  collapsed: boolean;
  onToggle: (environmentId: string) => void;
  taskTitleById: Map<string, string>;
  personaNameById: Map<string, string>;
  onOpenSession: (sessionId: string) => void;
  onOpenTask: (taskId: string) => void;
}): JSX.Element {
  const { environment, environmentId } = group;
  const name = environment?.displayName ?? environmentId;
 
  return (
    <section className={styles.group} data-testid={`session-group-${environmentId}`}>
      <button
        type="button"
        className={styles.groupHeader}
        aria-expanded={!collapsed}
        onClick={() => onToggle(environmentId)}
        data-testid={`session-group-toggle-${environmentId}`}
      >
        {collapsed ? (
          <ChevronRight size={ICON_SM} aria-hidden="true" />
        ) : (
          <ChevronDown size={ICON_SM} aria-hidden="true" />
        )}
        <Monitor size={ICON_SM} className={styles.groupIcon} aria-hidden="true" />
        <span className={styles.groupName}>{name}</span>
        {environment !== undefined ? (
          <span
            className={styles.envStatusDot}
            data-status={environment.status}
            aria-hidden="true"
          />
        ) : (
          <span className={styles.missingEnv}>missing</span>
        )}
        <span className={styles.groupSpacer} />
        {group.activeCount > 0 && (
          <span className={styles.activePill} data-testid={`session-group-active-${environmentId}`}>
            {group.activeCount} active
          </span>
        )}
        <span className={styles.countBadge}>{group.sessions.length}</span>
      </button>
      <AnimatePresence initial={false}>
        {!collapsed && (
          <motion.ul
            className={styles.rows}
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: COLLAPSE_DURATION_S, ease: [0.16, 1, 0.3, 1] }}
          >
            {group.sessions.map((session) => (
              <SessionRow
                key={session.id}
                session={session}
                taskTitle={session.taskId ? taskTitleById.get(session.taskId) : undefined}
                personaName={session.personaId ? personaNameById.get(session.personaId) : undefined}
                onOpenSession={onOpenSession}
                onOpenTask={onOpenTask}
              />
            ))}
          </motion.ul>
        )}
      </AnimatePresence>
    </section>
  );
}
 
/**
 * The Sessions activity monitor: a searchable, status-filterable, environment-
 * grouped table of all sessions. Updates live as the parent's session list
 * changes (statuses flow in through the sessions domain hook).
 */
export function SessionsTable({
  sessions,
  environments,
  tasks,
  personas,
  onOpenSession,
  onOpenTask,
}: SessionsTableProps): JSX.Element {
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [query, setQuery] = useState("");
  const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
 
  const environmentNameById = useMemo(
    () => new Map(environments.map((e) => [e.id, e.displayName])),
    [environments],
  );
  const taskTitleById = useMemo(() => new Map((tasks ?? []).map((t) => [t.id, t.title])), [tasks]);
  const personaNameById = useMemo(
    () => new Map((personas ?? []).map((p) => [p.id, p.name])),
    [personas],
  );
 
  // Chips reflect the full set; filtering narrows what's shown below.
  const chips = useMemo(() => buildStatusChips(sessions), [sessions]);
  const filtered = useMemo(
    () => filterSessions(sessions, statusFilter, query, environmentNameById),
    [sessions, statusFilter, query, environmentNameById],
  );
  const groups = useMemo(
    () => groupSessionsByEnvironment(filtered, environments),
    [filtered, environments],
  );
 
  const toggleGroup = (environmentId: string): void => {
    setCollapsed((prev) => {
      const next = new Set(prev);
      Iif (next.has(environmentId)) {
        next.delete(environmentId);
      } else {
        next.add(environmentId);
      }
      return next;
    });
  };
 
  return (
    <div className={styles.container} data-testid="sessions-table">
      <div className={styles.toolbar}>
        <div className={styles.chips} role="group" aria-label="Filter by status">
          {chips.map((chip) => (
            <button
              key={chip.value}
              type="button"
              className={`${styles.chip} ${statusFilter === chip.value ? styles.chipActive : ""}`}
              data-tone={chip.value === "all" ? undefined : chip.value}
              aria-pressed={statusFilter === chip.value}
              onClick={() => setStatusFilter(chip.value)}
              data-testid={`session-filter-${chip.value}`}
            >
              {chip.label}
              <span className={styles.chipCount}>{chip.count}</span>
            </button>
          ))}
        </div>
        <div className={styles.search}>
          <Search size={ICON_SM} className={styles.searchIcon} aria-hidden="true" />
          <input
            type="text"
            className={styles.searchInput}
            placeholder="Search sessions..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            aria-label="Search sessions"
            data-testid="sessions-search"
          />
        </div>
      </div>
 
      {groups.length === 0 ? (
        <div className={styles.empty} data-testid="sessions-empty">
          <Terminal size={32} aria-hidden="true" />
          <p className={styles.emptyTitle}>
            {sessions.length === 0 ? "No sessions yet" : "No matching sessions"}
          </p>
          <p className={styles.emptyHint}>
            {sessions.length === 0
              ? "Spawn an agent or start a task and it will show up here."
              : "Try a different status filter or search term."}
          </p>
        </div>
      ) : (
        <div className={styles.scroll}>
          {groups.map((group) => (
            <EnvironmentGroup
              key={group.environmentId}
              group={group}
              collapsed={collapsed.has(group.environmentId)}
              onToggle={toggleGroup}
              taskTitleById={taskTitleById}
              personaNameById={personaNameById}
              onOpenSession={onOpenSession}
              onOpenTask={onOpenTask}
            />
          ))}
        </div>
      )}
    </div>
  );
}